Friday, July 26, 2019

WPF : How To Set Focus on another window (MVVM)


 How To Set Focus on another window (MVVM)?

I have two window (Parent-Child). Parent window opens Child window so child window is focused
(i.e. top most window) but when child replies to Parent, Parent window is not focused (i.e. it's not on top).

I have created a attached property in a separate class like:

class FocusAttched:DependencyObject
    {
        public static DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusAttched),
                new UIPropertyMetadata(false, OnIsFocusedChanged));
        public static bool GetIsFocused(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(IsFocusedProperty);
        }
        public static void SetIsFocused(DependencyObject dependencyObject, bool value)
        {
            dependencyObject.SetValue(IsFocusedProperty, value);
        }
        public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            ((FrameworkElement)dependencyObject).Focus(); //My Code-Niranjan
           
            // Removing hard coding
            //TextBox textBox = dependencyObject as TextBox;
            //bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
            //bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
            //if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
        }
    }

Now Attached this property to Parent window control (textbox)

                      VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" AcceptsReturn="True" HorizontalAlignment="Left"
                 Height="248" Margin="191,36,0,0"   VerticalAlignment="Top" Width="249"/>


I am binding this attached property with a new property in View Model, for this reason I am creating a new bool property in View model.

bool _setFoucs;
        public bool SetFocus {
            get { return _setFoucs; }
            set { _setFoucs = value; OnPropertyChanged(nameof(SetFocus)); }
        }

I will set this property in Callback method.

Summery : Idea is that when Child window sends a message to Parent window, callback method will get called by Child, in this Callback I am setting this 'SetFocus' Property which is attached to TextBox of Parent window, OnPropertyChnage callback of Attached/Dependency property I am calling Focus() method of FrameworkElement( TextBox is Framework element).

Thursday, July 25, 2019

WPF - Difference between ContentControl and ContentPresenter?



Difference between ContentControl and ContentPresenter?


ContentPresenter is a lightweight element. It's derived from FrameworkElements class. So, It has no Template property (i.e.) we can't set control Template for it, while we can set data template for it as it has Content property.

ContentPresenter has a addition property 'ContentSource' which is not present in Content Control.

Default value of 'ContentSource' property is content, So when we will put ContentPresenter inside of ControlTemplate we don't need to define binding explicitly.

ContentControl also uses ContentPrenseter in it's template to display data.

WPF - How to print Parent hierarchy of an element?



How to print Parent hierarchy of an element?

            DependencyObject _parent = myGrid.Parent;
            while (_parent != null)
            {
                System.Diagnostics.Debug.WriteLine(_parent);
                _parent = ((FrameworkElement)_parent)?.Parent;
            }

Every framework element has a Parent property, we can loop through like above code and print parent of particular element.

Tuesday, July 2, 2019

WCF : How to transfer large data via wcf service?


How to transfer large data from wcf service?

To transfer large data from wcf service, we need to change some configuration settings like:

MaxReceivedMessageSize
Transfer Mode
Max Depth (in ReaderQuotas)
MaxArrayLength

Above are necessary settings to transfer large data form WCF, apart from these settings, to increase performance you can change message encoding to "MTOM".

Complete binding configuration is :
 

    

Note : you need these settings in both Service and application config file (web.config and app.config).






Monday, June 24, 2019

Difference between Interface and Delegate in c#


Interface is a contract, a method declared inside of interface, class which implementing that Interface should provide definition for declared method inside interface.

In case of delegate, if a class (let's say A) method needs callback function as a parameter or exposing a delegate (same like event) to subscribe. you need to implement callback method with same signature as delegate to subscribe delegate/callback.

In both cases (in case of interface and in case of delegate) you need to define a method with declared signature by interface/delegate so, in case of single method interface seems there is no difference between interface and delegate.

let's dig in detail,

  • for an interface method implementation, it's necessary to declare it public.
  • if interface has more than one method, implementer of interface need to define all the methods of interface.
  • we can subscribe a private method, or anonymous method to delegate, which is not possible in case of interface.
  • In case of interface, we need to define method same as method declared in interface (same name) but in case of delegate we can assign any method whose signature is same as delegate signature.
  • delegate provide multicast functionality, we can subscribe multiple methods to delegate but not to interface.
* Please let me know your comments...

Tuesday, June 4, 2019

WPF : C# Async methods



Below example shows how to create and use async methods in WPF application.
In below example, There are two ways to create void returning async method as well string returning
Async method.

you can copy and paste relevance code in any new WPF application and check it's functionality(mainly responsiveness). I tried to create long running operations and application responsiveness during long running operation.



.CS File

 public partial class AsyncWithWPF : Window
    {

        string strGlobalVariable = "";
        public AsyncWithWPF()
        {
            InitializeComponent();
        }
     
        private async void BtnAsyncReturnVoid1_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            await LongRunningTaskReturnvoid1();
            lblResult.Content += "Finished LongRunningTaskReturnvoid1() " + strGlobalVariable;
        }
        public Task LongRunningTaskReturnvoid1()
        {
            lblResult.Content += "   inside LongRunningTaskReturnvoid1() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                strGlobalVariable += " Async Task has finished ";
            });
        }
        private  void BtnAsyncReturnVoid2_Click(object sender, RoutedEventArgs e)
        {
         
                lblResult.Content = "";
                lblResult.Content += " Starting..  ";
                LongRunningTaskReturnvoid2();
           
            lblResult.Content += "after LongRunningTaskReturnvoid2() call";
        }
        public async void LongRunningTaskReturnvoid2()
        {
         
                await Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
             

            });
                lblResult.Content += "  finished LongRunningTaskReturnvoid2()";
           
        }
        private async void BtnAsyncReturn1_Click(object sender, RoutedEventArgs e)
         {
            string result = "";
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            try
            {
                result = await LongRunningTask();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Handled");
            }
            lblResult.Content += result +" Finished LongRunningTaskvoid()";
         
        }
        public Task LongRunningTask()
        {
            lblResult.Content += "   inside LongRunningTask() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000); //throw new Exception("test");// uncomment to check exception handling.
                return "Hello";
            });

        }
     
        private void BtnTestResponsiveness_Click(object sender, RoutedEventArgs e)
        {
              MessageBox.Show("Hello");
        }
   

    }

C# : Protected Members



Protected is a keyword in C#, used to define accessibility for class members like variables, properties and methods, etc.
protected members have similar accessibility as private member with only one difference that are also available in derived classes.

Note: for a class that is defining protected member and it's derived classes, they are available as private i.e. class defining protected member and it's derived classes are not able to access protected member via it's object, while any other public or protected member can use that newly defined protected members. please see below example:

class BaseClass
    {
        protected int Add(int a ,int b)
        {
            return a + b;
        }
        protected void AddWrapper()
        {
           Console.WriteLine( Add(5, 9));
        }
  }
  
class DerivedClass : BaseClass
    {
        public void m1()
        {
            int k = Add(4, 5);
            Console.WriteLine("Calling BaseClass's protected methods via Wrapper method m1()");
            AddWrapper();
        }
}

public class Tester
    {
        public static void Main()
        {
            BaseClass obj1 = new BaseClass();
            // not able to call Add method via BaseClass object.
            DerivedClass obj2 = new DerivedClass();
            obj2.m1();
            Console.Read();

        }
}




Friday, May 17, 2019

C# : Data Structure : Queue


Queue Implementation in C#

class Queue
    {
        int[] item;
        int rear;
        int front;
        readonly int capacity;

        public Queue()
        {
            capacity = 100;
            rear = -1;
            front = 0;
            item = new int[capacity];
        }
        public Queue( int capacity)
        {
            this.capacity = capacity;
            rear = -1;
            front = 0;
           
            item = new int[capacity];
        }

        public void Enqueue(int _item)
        {
            if (rear == capacity - 1)
            {
                Console.WriteLine("Queue is full");
                return;
            }
            item[rear + 1] = _item;
            rear++;
        }
        public int Dequeue()
        {
            if (front - 1==rear  )
            {
                Console.WriteLine("Queue is empty");
                return -1;
            }
            int itemtoReturn = item[front];
            front = front + 1;
            return itemtoReturn;
        }
    }
    public class QueueTest
    {
        //public static void Main()
        //{
        //    Queue que = new Queue(5);
        //    que.Enqueue(1);
        //    que.Enqueue(2);
        //    que.Enqueue(3);
        //    que.Enqueue(4);
        //    que.Enqueue(5);
        //    que.Enqueue(6);

        //    Console.WriteLine("items in queue :");
        //    Console.WriteLine(que.Dequeue());
        //    Console.WriteLine(que.Dequeue());
        //    Console.WriteLine(que.Dequeue());
        //    Console.WriteLine(que.Dequeue());
        //    Console.WriteLine(que.Dequeue());
        //                Console.WriteLine(que.Dequeue());
        //                Console.Read();
        //}

    }

C# : Data structure : Stack


Stack Implementation in C#

public class Stack
    {
        readonly int  _capacity;
        int top;
        int[] _stack ;
        public int Top
        {
            get { return top; }
        }
        public Stack()
        {
            _capacity = 1000;
            top = -1;
        }
        public Stack( int capacity)
        {
            _capacity = capacity;
            _stack = new int[_capacity];
            top = -1;
        }
        public void Push(int item)
        {
            if (top < _capacity - 1)
            {
                _stack[top + 1] = item;
                top++;
            }
            else
            {
                Console.WriteLine("Stack is full");
            }
        }
        public int Pop()
        {
            int itemToReturn=-1;
            if (top == -1)
            {
                Console.WriteLine("Stack empty!!");
             
            }
            else
            {
                 itemToReturn= _stack[top];
                top--;
             
            }
            return itemToReturn;
        }
        public int Peek()
        {
            if (top != -1)
            {
                return _stack[top];
            }
            else
            {
                Console.Write("Stack is empty!!!");
                return -1;

            }

         

        }

C# : Data Structure : Selection Sort



Selection Sort Algorithm in C#:

class SelectionSort
    {
        ///
        /// Selection Sort :
        //We will consider that at the first position element in array is minium,
        //and then serach in entire array smaller than
        // selected min we will exachange the array element
        //( for ex: at first itiration we consider that 0th element is min. if any other let's say 3rd element
        // is smaller then min.then we will exchange element of 0 and 3.now we have smallest elemnt of            //array at 0th position.similiarly we will do for first element and otehr in array.
        ///
        ///
        public static void Main()
        {
            int[] unSoretedArray = new int[] { 1, 8, 6, 4, 4, 2, 5 };
            PrintArray(unSoretedArray);
            for (int i = 0; i <= unSoretedArray.Length - 2; i++)
            {
                int min = unSoretedArray[i];

                int indexOfMin = i;
                for (int j = i + 1; j <= unSoretedArray.Length - 1; j++)
                {

                    if (min > unSoretedArray[j])
                    {
                        min = unSoretedArray[j];
                        indexOfMin = j;

                    }
                }
                unSoretedArray[indexOfMin] = unSoretedArray[i];
                unSoretedArray[i] = min;

                Console.Write("                                                           ");
                PrintArray(unSoretedArray);
                Console.WriteLine($"Changing position of elements from {indexOfMin} to {i}");

            }

            Console.Read();
        }
        public static void PrintArray(int [] unSoretedArray)
        {
            foreach (int i in unSoretedArray)
            {
                Console.Write($" {i}  " );
            }
            Console.WriteLine();

        }

C# : Data Structure : Insertion Sort



Insertion Sort Algorithm :

class InsertionSort
    {

        public static void Main()
        {
            int[] unSoredArray = new int[] { 4, 2, 3, 6, 9, 1, 2 };

            for (int i = 0; i <= unSoredArray.Length - 1; i++)
            {
                int val = unSoredArray[i];//4
                int j = i ;
                while(j>0 && unSoredArray[j-1] >val)//4- 2,2-4
                {
                    unSoredArray[j] = unSoredArray[j-1];
                    j--;
                }
                unSoredArray[j] = val;
            }
            PrintArray(unSoredArray);
            Console.Read();
        }
        public static void PrintArray(int[] unSoretedArray)
        {
            foreach (int i in unSoretedArray)
            {
                Console.Write($" {i}  ");
            }
            Console.WriteLine();
        }
    }

C# : Data Structure : Linked list implementation in C#



Linked List in C#:

 class LinkedListImpl
    {
        Node temp, head,last;
        int count = 0;
        public void InsertAtEnd(int value)
        {
            temp = new Node() { data = value, Next = null };
            if (head == null)
            {
                head = temp;
                last = temp;
            }
         
            last.Next = temp;
            last = temp;
         
            count++;
        }
        public void PrintLinkedList()
        {
            temp = head;
            if (temp == null) throw new Exception("Empty linked list!");

            while (temp != null)
            {
                Console.Write($"{temp.data}=>");
                temp = temp.Next;
            }

            Console.WriteLine("First element of List is " + head.data);
            Console.WriteLine("Last element of List is " + last.data);
        }
        public void InsertAtStart(int value)
        {
            temp = new Node() { data = value, Next = head };
            head = temp;

        }
        public void Insert(int insertAfter,int value)
        {
            temp = head;
            while (temp != null)
            {
                if (temp.data == insertAfter)
                {
                    Node temp2 = new Node { data = value, Next = temp.Next };
                    temp.Next = temp2;

                    // if inserted at last then need to Move last pointer.
                    if (temp2.Next is null)
                    {
                        last = temp2;
                    }
                    break;
                 
                }
                temp = temp.Next;
            }
        }

        public bool Find(int value)
        {
            temp = head;
            while (temp != null)
            {
                if (temp.data == value)
                {
                    return true;
                }
             
                temp = temp.Next;
            }
            return false;
        }
        public bool Delete(int value)
        {
            if (head.data == value)// if data is available at head node
            {
                head = head.Next;
                return true;
            }
            temp = head;
            while (temp != null)// moving till( desired node -1). i.e. before the desired node (1=>2=>5=>6=>7=>8 and we want to delete 6, so need to move till 5 th only.)
            {
             
                if (temp.Next?.data == value)
                {
                    temp.Next = temp.Next.Next;
                }

                if (temp.Next is null)// to set last node.
                {
                    last = temp;
                }
                temp = temp.Next;
             
            }
            return false;
        }
        class Node
        {
            public int data { get; set; }
            public Node Next { get; set; }
        }
/*
        public static void Main()
        {
            LinkedListImpl linkedList = new LinkedListImpl();

            linkedList.InsertAtEnd(2);
            linkedList.InsertAtEnd(4);
            linkedList.InsertAtEnd(6);

            linkedList.InsertAtStart(1);
            linkedList.InsertAtStart(0);

            linkedList.Insert(4, 5);
            linkedList.Insert(6, 7);
            linkedList.Insert(7, 8);


            Console.WriteLine(linkedList.Find(3));
            Console.WriteLine(linkedList.Find(0));
            Console.WriteLine(linkedList.Find(7));

            linkedList.PrintLinkedList();
            linkedList.Delete(7);
            linkedList.Delete(0);
            linkedList.Delete(8);
            linkedList.PrintLinkedList();
            Console.Read();

        }
        */

    }

Wednesday, May 15, 2019

SQL Server : Some common queries on Employee and Department table


Schema of Employee and Department table are as follows :





























Create Department :

Create table Department (DepartmentId integer not null primary key identity, DepartmentName varchar(50));


Create Employee :

Create table Employee(
EmployeeId integer not null identity primary key
,FirstName varchar(50)
,LastName varchar(50)
,DepartmentId integer
);

---------------Some common queries on above tables-----------------

--Department wise employees name and other details 
select d.DepartmentName, e.FirstName,e.LastName,e.Salary
from Employee e left join Department d on e.departmentId=d.DepartmentId

-- Find out no. of Employees in Each Deaprtment.
---------------------------------------------------------
select d.DepartmentName, count(e.Employeeid)
from Employee e
left join Department d on e.departmentId=d.DepartmentId
group by d.departmentID,d.departmentName
 --------------------------------------------------------
-- find out departments where no.of employee more than 3
select d.DepartmentName, count(e.Employeeid)
from Employee e
left join Department d on e.departmentId=d.DepartmentId
where d.departmentname is not null
group by d.departmentID,d.departmentName having  count(e.employeeid)>3

-----------------------------------------------------
-- Find out name of employee,salary and departmentName, who has max salary in their department .
--i.e. departmentname and name of employee who has max salary in their department.

SELECT DepartmentName, firstName,LastName, Salary, Salaryrank from
(select d.DepartmentName, e.firstName,e.LastName, e.Salary, row_number() over (partition by e.departmentID order by salary desc)  as Salaryrank
from Employee e
left join Department d on e.departmentId=d.DepartmentId) as result
where result.Salaryrank=1
-- Result will contains department name ,name of employee who has highest salary in their department, salary




SQL Server : How to create and alter table & columns



Create table in SQL Server, firstly you need to choose right database where you want to create table.
you can change database by below query :

USE  DB_NAME;

How to create table

Create table Employee(
                                           EmployeeId integer 
                                           ,FirstName varchar(50)
                                           ,LastName varchar(50)
                                           ,DepartmentId integer
);

above Employee table doesn't have primary key, we can add primary key via above query itself
or we can add primary key constraints, see below examples :

 -- Add constraints

  Alter table Employee add constraint Emp_pk primary key (EmployeeId); 

but when you will try to execute above query you will get "Cannot define PRIMARY KEY constraint on nullable column in table 'Employee" error message. because to create primary key on a column, column should be defined as 'NOT NULL'

So, we need to alter 'Employee table's 'EmployeeId' column like:

  Alter table Employee alter column EmployeeId integer NOT NULL;

(similarly, we can change any column's attributes like( name,datatype,etc.) Now, we can run previous statement to add constraint to add primary key.

We can also mention primary key, not null, identity column declaration with create table statement.
like :

Create table Employee(
EmployeeId integer not null identity primary key
,FirstName varchar(50)
,LastName varchar(50)
,DepartmentId integer
);

We can declare NOT NULL, CHECK and UNIQUE constraints at the time of table creation same like above.

Monday, May 13, 2019

C# : static at a glance


          
       Static 
  • Static is a keyword in C#, used to create class level (global) members, i.e. they are common for all the instance of a class. they are directly accessible via class name.
  • We can declare static variable,property, methods.
  • We can use access modifier with static members, i.e they can be public,private,etc.
  • Static methods can access static variable,methods inside it.
  • We can declare static constructor to initialize static member.
  • Static constructor can not have parameters and access modifiers, i.e we can not apply public ,private,etc modifier on static constructor.
  • Static constructor always called before instance constructor of a class.
  • If we have static constructor in derived class and also in base class then call hierarchy would be
  • Derived static constructor.
  • Base static constructor.
  • Base instance constructor.
  • Derived instance constructor.
     Static and Inheritance:
  • Static members also inherited i.e. Static members are available in derived class, we can use them in derived class, also they are accessible via derived class name if they are public.
  • We can't override static methods in derived class, if we create a static method in derived class with same signature as base class, derived class method will hide base class method.
  • for example we have a static method M1() in class A, and we are creating again a static method M1() in derived class B.  A.M1() will reference base class's static method while B.M1() will reference B's static method.

     class A
        {
            static A()
            {

            }
            public static void m1()
            {
                Console.WriteLine("Static M!");
            }
            public void InstanceA()
            {
                Console.WriteLine("Instance method of A");

            }
        }
        class B : A
        {
            public new static void m1() //hides base's static method.
            {
                Console.WriteLine("Providing new definition in B!");
            }
            public void InstanceB()
            {
                Console.WriteLine("Instance method of B");
             
            }
        }

        public static void Main()
        {
            A a = new A();
            a.InstanceA();
            A.m1();
            B.m1(); // Static method also inherited.
            Console.WriteLine();

            Console.Read();
        }

Sunday, May 12, 2019

C# : Jagged Array


Jagged Array : Jagged array is array of array.

Declaration of Jagged Array :

                                    int[][] jaggeedArry = new int[3][];

as mentioned before that Jagged array is array of array, in above declaration it's array of 3 arrays of int, and that 3 arrays are not necessary to be same in size. Let's understand by below example:

     public static void Main()
        {
            int[][] jaggeedArry = new int[3][];
           
            jaggeedArry[0] = new int[5]; // we can assign these arrays length at run time.
            jaggeedArry[1] = new int[3];
            jaggeedArry[2] = new int[2];

            Console.WriteLine(jaggeedArry.Length); //jagged array's length will be 3.

            //Inserting values in jaggedArray
            for (int i = 0; i < jaggeedArry.Length; i++){
                for(int j = 0; j < jaggeedArry[i].Length; j++)
                {
                    jaggeedArry[i][j] = 5 + i;
                }
            }
            //Printing values of jaggedArray
            for (int i = 0; i < jaggeedArry.Length; i++)
            {
                for (int j = 0; j < jaggeedArry[i].Length; j++)
                {
                    Console.Write(jaggeedArry[i][j] +"  ");
                }
                Console.WriteLine();
            }
            Console.Read();
        }

Friday, May 10, 2019

WPF : How to create and use Dependency Property for Window



How to create and use Dependency Property for Window
I am creating a dependency property in MainWindow class and trying to set it's value and use it in MainWindow.xaml.

I have created a dummy dependency property "Count" and used it to set lable's content.


C# Design Pattern : Decorator.



Decorator design Pattern allows you to change objects behavior/functionality at run time. in other words you can decorate it. for example you have a window (consider for a moment that window doesn't have border feature inbuilt) and we want to decorate it with border.one way we can create a derived class of Window and override it but important point to remember here is that, we have an object, we are decorating object at run time we don't/can't want to change it's template( i.e.class). below example will show you how to change object at run time without changing it's interface. (copy-paste below code to visual studio/code to see comments properly).

 public interface IWindows
    {
        void Draw();
        void Maximize();
        void Minimize();
    }
    public class Windows : IWindows
    {
        public void Draw()
        {
            Console.WriteLine("Drawing Window ...");
        }

        public void Maximize()
        {
            Console.WriteLine("Windows Maximized");
        }

        public void Minimize()
        {
            Console.WriteLine("Windows Minimized");
        }
    }

    class WindowsBorderDecorator : IWindows
    {
        // As you are implementing Iwindows interface so, you have to implement all of it's methods.
        // but as you are getting Window Objects from client which has already implemented Iwindow,
        //it means now you are free to use exsting implementation or you can override any method, as per your wish.
        // As we want to draw border around window so we will override Draw() method.

        private IWindows windowToDecorate;

        public WindowsBorderDecorator(IWindows window)
        {
            windowToDecorate = window;
        }
        public  void Draw()
        {
            // changing the drawing logic..now ,drawing window with border.
            // it's our logic or situation weather we are able to use some functionality
            //from existing window object ('windowToDecorate')
            //or we want to write logic from scratech.

            SetBorderAroundWindow();
            Console.Write("Decorating window with Border!");

        }

        private void SetBorderAroundWindow()
        {
           //Additional logic as per your requirement;
        }

        public  void Maximize()
        {
            windowToDecorate.Maximize();
        }

        public virtual void Minimize()
        {
            windowToDecorate.Minimize();
        }
    }
    class DecoratorDesignPatternTest
    {
        public static void Main()
        {
            IWindows window = new Windows();
            window.Draw();// actaul implementation. OUTPUT:Drawing Window ...
            //--------------instead of above code you can use like below (Note: interface is same)---------
            //want to decorate it with  border.
            IWindows decoratedWindow= new WindowsBorderDecorator(window);
            decoratedWindow.Draw(); //new impelemetation with border. OUTPUT:Decorating window with Border!
            Console.Read();
        }
    }  

C# : Design Pattern : Different flavor of Singleton design pattern implementation


Below code is showing different implementation of Singleton design pattern for Example

Thread safe singleton implementation:

 public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object locker = new object();
        private Singleton()
        {

        }
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null) //double locking.
                {
                    lock (locker)//each time it will lock weather object create is required or not.
                                 //so to avoid unnecessary locking we will use double locking pattern
                                 // means apply lock only when instance is null. we will check instance==null before locking.
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                            return instance;
                        }
                    }
                }
                return instance;
            }
        /*
       . other methods, properties of singleton class.
       .
       .
       .
       */
        }
    }

Note : class is sealed because no one should be able to inherit it. locker object is static and readonly so only one instance object will be present which will be used for locking purpose.
we are checking instance ==null two times to avoid unnecessary locking, locking will be applicable only if instance is null.

Eager loading Singleton Pattern:

 public sealed class SingletonEagerLoading
    {
        private static readonly SingletonEagerLoading instance = new SingletonEagerLoading();
        int counter = 0;
        private SingletonEagerLoading()
        {
            counter++;
            Console.WriteLine("No of instance=" + counter);
        }
        public static SingletonEagerLoading GetInstance
        {
            get { return instance; }
        }
     
        /*
        . other methods, properties of singleton class.
        .
        .
        .
        */

    }
// Note :No need to implement locking as we are creating instance at the time of declaration so framework will take care of instantiation and concurrency. (i.e. this implementation is Thread safe)

Lazy Loading Singleton Pattern :

public sealed class SingletonLazyLoading
    {
        private static readonly Lazy instance = new         Lazy(() => new SingletonLazyLoading());
        int counter = 0;
        private SingletonLazyLoading()
        {
            counter++;
            Console.WriteLine("No of instance=" + counter);
        }
        public static SingletonLazyLoading GetInstance
        {
            get { return instance.Value; }
        }

        /* other methods, properties of singleton class.*/
        public static void Main() //To Test
        {
            SingletonLazyLoading obj1 = SingletonLazyLoading.GetInstance;
            SingletonLazyLoading obj2 = SingletonLazyLoading.GetInstance;

        }

    }

Thursday, May 9, 2019

SQL Server : Count no. of employees in each department

Count no. of employees in each department

SELECT DEPT_NAME,COUNT(EMP_ID)
FROM DEPARTMENT D LEFT JOIN EMPLOYEE E ON D.DEPT_ID=E.DEPARTMENT_ID
GROUP BY DEPT_NAME


C# : How to declare Async method in Interface



We can not declare Async method in interface or it's not needed as Async is code marker for compiler it has no relation with overriding feature. If we want to declare Async methods in Interface we need to set return type of method to Task/Task also void method of interface can be implemented as Async. See below example :(Methods implemented in code are not providing any meaningful functionality,it's just to check/show use of Async from interface.)



C# : Can we return value from events?


Yes, we can return value from events but returned value will be available to the publisher of events.
Generally, publisher do not want any value from subscriber of event, he wants to notify subscriber, so the subscriber can perform appropriate action on the particular event. for example Button click, Button class is publisher of event and allowing subscriber to perform some action when button clicked. Yes, but if we will talk technically and tried to find out answer of question "can we return value from event so, answer will be yes. Please see below example :

namespace MyLibrary
{
 
    ///
    /// This class will show us use of delegate.
    ///
    public delegate bool LoopConditionChangingEvent();

    public class ReturnValuefromEvent
    {
       public event LoopConditionChangingEvent LoopConditionChanging;


        // This method will run loop till given condition by user and when i and conition are equal then it will ask to client, that still he wants to continue..."
        // by generating events and event will return value to the publisher of event.
        // hence conclusion is that event can return value back to the publisher.

        public void RunLoop(int condition)
        {
            for (int i = 0; i <= condition; i++)
            {
                //here we are doing some operation like :
                Console.Out.WriteLine("value of i=" + i);

                if (i == condition && condition != 100)
// here we are checking if loop is reached to it's initial condition provided by user, we will ask to user are you still want to continue.
                {                                     // and also we are setting maximum limit of loop i.e.100. 
                    if (LoopConditionChanging != null)
                    {
                        if (LoopConditionChanging())//Callback--asking to client and if client will tell yes we will increment loop
                        {
                            condition = condition + 10;
                        }
                    }
                }
            }
        }
    }
}

user will subscribe "LoopConditionChangingEvent " which will return bool value (true or false) that publisher will use inside of loop and according to given value either loop will continue or terminated.

Friday, April 12, 2019

WPF: Style definition and use


WPF : Style Introduction :

Style are way to set common property of a control at one place to reuse it.
Style are similar to CSS classes in HTML/Web Applications.
We can declare Style at multiple places like :
Resource Section of Control or it's Parent.(Scope :Control it self and it's child can use this Style)
Resource Section of Window.(Scope =containing form only)
Inside of Resource Dictionary.(Scope = Application level).


Below are some common attributes of Style:

TargetType :if we are setting only TargetType then Style will be application to all controls mention as Target type in applicableScope.

x:Key : used to declare a key, if we declare a Key then style will not be applied on controls automatically, we need to set explicitly.

BasedOn : used to create a new Style by inheriting from an existing Style.

    


Note : Control level Properties have higher precedence than Style. i.e. if you have applied style which is setting background color of control and you also have set background color at Control level, Color set at control will be applicable and system will ignore color what you mentioned in Style.




Thursday, April 11, 2019

WPF : How to use POCO object in XAML file and use converter in WPF


I am trying to use CLR object (Person) in XAML file and also demonstrating use of converter.
This example is just to demonstrate how to use above mentioned functionality, it's doesn't perform any meaningful functionality.

I have imported namespace for Person and Converter classes and created resource in Window for both classes (Note : We can initialize classes via resource only if class has a default constructor).

Definition of person and converter classes are as follows :


Wednesday, April 10, 2019

SQL Server : Some common query optimization techniques

  • Try to fetch relevant data as per your needs from SQL Server, so server need to consume resources for unwanted data.

  • Always provide column names in SELECT clause and provide only required column list.

  • Try to avoid DISTINCT clause, one work around to eliminate distinct is to add a unique/primary key column in result, so you will be able to decide weather record is duplicate of not based on different value of primary/unique key.

  • Try to avoid cross joins.

  • if you are grouping data and applying having clause try to put criteria in where clause if possible, as group by and having will be applied on result of query so you can limit the no. of rows by applying filter criteria in where clause so you will get lesser record and system will be able to perform grouping operation fast.

  • use Like clause carefully and efficiently as it will be more resource intensive for server and produce more unwanted records in query result. for ex if you want to search city name start from  'MA' use LIKE 'MA%' instead of  LIKE '%MA%'.

  • Avoid Co-related sub queries and use Join instead, for ex :  

SELECT c.Name, c.City,(SELECT CompanyName FROM Company WHERE ID = c.CompanyID) AS CompanyName
FROM Customer c        

you can achieve same result by using JOIN which will be faster than this. 

  • If you want to check if a record exists, use EXISTS() instead of COUNT() because count will scan entire table while Exist will return when matching record found. for ex: IF( SELECT COUNT(NAME) FROM PERSON WHERE AGE>100) >0) do something...instead use IF(EXISTS(SELECT NAME FROM PERSON WHERE AGE>100)

Monday, April 8, 2019

SQL Server : Generating xml from Query

Below query will generate xml for employee records

SELECT [EMP_ID]
      ,[FIRST_NAME]
      ,[LAST_NAME]
      ,[DEPARTMENT_ID]
      ,[SALARY]
  FROM [ABCD].[dbo].[Employee]
FOR XML RAW('Employee'), ROOT('Employees'), ELEMENTS XSINIL;

SQL Server : Delete duplicate rows from table


Delete duplicate rows from table , we are considering duplicate rows based on Name and City column Values.

--Works well if Table Desn't have primary key

WITH TEMP AS (
SELECT ROW_NUMBER() OVER ( PARTITION BY NAME,CITY ORDER BY NAME,CITY) as RN,NAME,CITY 
FROM TAbleDuplicate
)  
DELETE FROM TEMP WHERE
RN>1

Another way to delete duplicate from table (if primary key is present in table):

DELETE FROM EMPLOYEE WHERE EMP_ID NOT IN (
SELECT Min(EMP_ID) FROM EMPLOYEE
GROUP BY FIRST_NAME,LAST_NAME,SALARY ) 

SQL Server : Some common and useful queries


Find all the employees and their department name

select emp_id,first_name,Last_Name,dept_id,dept_name
from employee e
inner join 
department d on e.department_id = d.DEPT_ID

we can also apply where clause to add filter for emp_id or first_name and find department and other details for specific employee.

Find all the employees who is not part of any department

select emp_id,first_name,Last_Name,dept_id,dept_name from employee e
left join department d on e.department_id = d.DEPT_ID

where e.department_id is null

Find no. of employees in each department and sum of their salary (i.e. total salary distributed for each department)

select count(emp_id) as empCount,sum(salary),department_id from employee

group by department_id

Find the no.of employee and department where salary distributed is greater than 100000

select count(emp_id) as empCount,sum(salary) as totalSalary, department_id from employee

group by department_id having sum(salary) >100000

ROW_NUMBER(), RANK(), DENSE_RANK()


SELECT  
--ROW_NUMBER() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
 ROW_NUMBER() OVER ( PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,
EMP_ID,DEPARTMENT_ID,FIRST_NAME,SALARY 
FROM EMPLOYEE where salary is not null Order by DEPARTMENT_ID

SELECT  
--RANK() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
RANK() OVER (PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,
EMP_ID,FIRST_NAME,SALARY ,DEPARTMENT_ID
FROM EMPLOYEE  where salary is not null Order by DEPARTMENT_ID

SELECT  --DENSE_RANK() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
DENSE_RANK() OVER (PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,EMP_ID,FIRST_NAME,SALARY ,DEPARTMENT_ID
FROM EMPLOYEE where salary is not null and DEPARTMENT_ID IS NOT NULL
Order by DEPARTMENT_ID

Note: 
ROW_NUMBER will generate sequential row number based on given partition and order by columns.

RANK () will generate rank based on given partition and order by columns. for example :
if  you have given department_Id in partition and order by salary and lets consider that there are two employee who has same salary so for first employee rank would be 1 and second and third employee rank would be 2 and for fourth employee rank would be 4 as row count for 4th employee would be 4th.

DENSE_RANK() is same as rank but it will give rank 3rd for fourth employee instead of 4th.
i.e. rank assignment will not be depend on row number of particular result.
run above queries to see result.

Create Table :

CREATE TABLE [dbo].TEST (
    [Id] int IDENTITY(1,1) primary Key,
    [Name] nchar(50)  NOT NULL

);
creating table with primary key.

Primary key creation with clustered index :

ALTER TABLE [dbo].[Countries]
ADD CONSTRAINT [PK_Countries]
    PRIMARY KEY CLUSTERED ([CountryId] ASC);
GO

Renaming TABLE Column:

EXEC dbo.sp_rename @objname=N'[dbo].[Cities].[ref]', @newname=N're', @objtype=N'COLUMN'

Cursor Example :

ALTER PROCEDURE SP_TEST_DATETIME
 AS
 BEGIN

  DECLARE @WorkingStatrt DateTime
  DECLARE @WorkingEnd DateTime
  DECLARE @TempTime DateTime
  DECLARE @TotalTime datetime
  DECLARE @CaseKey int
  DECLARE @createTimeStamp datetime
  DECLARE @Action varchar(50)
  
DECLARE WorkingHorsCalculation CURSOR FOR
SELECT CASE_KEY,CREATE_TIMESTAMP,ACTION
FROM AUDIT_LOG_CASE 

-- Open cursor
OPEN WorkingHorsCalculation
-- Fetch data from cursor in to variable
FETCH NEXT FROM WorkingHorsCalculation
INTO @CaseKey,@createTimeStamp,@Action
WHILE @@FETCH_STATUS = 0
BEGIN
-- Do operation according to row value
if @Action='Working Case'
begin
PRINT @Action
SET @WorkingStatrt=@createTimeStamp;
PRINT @WorkingStatrt

end
-- Fetch the next cursor
FETCH NEXT FROM WorkingHorsCalculation
INTO @CaseKey,@createTimeStamp,@Action
END
-- Finally do not forget to close and deallocate the cursor
CLOSE WorkingHorsCalculation
DEALLOCATE WorkingHorsCalculation


END

--*******************************************************************----







Interview Questions and Answers on Exception handling in C#  ( Part-3 )

Question: Can we use try catch block inside of Catch block?
Answer: Yes.






C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...