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.

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 ...