Wednesday 13 January 2016

LINQ

LINQ (Part 1)

Definition: "LINQ(Language Integrated  Query) is a Microsoft programming methodology that adds formal query capabilities into .NET based programming languages".It offers comprehensive syntax for manipulating data .

Why LINQ:

  1. Reduce the Amount of Code.
  2. A better understanding of the intent of what the code is  doing .
  3. A similar set of LINQ queries can be applied on different data sources.
  4. LINQ enables queries as first class citizen in C# and Visual Studio.
The building Blocks of LINQ
There are two fundamental blocks in LINQ
  1. Sequence
  2. Element
A sequence is instance of class that implements IEnumerable<T> interface.A sequence is basically a list of items and each item is treated as element.
There are two types of sequences.
  1. Local
  2. Remote
  • Local Sequence implements IEnumerable <T> interface. 
  • Remote Sequence implements IQueryable<T> interface.
Example of Remote Sequence implements will be discussed later.

Example of Local Sequence:



  Out Put:





















The above example is about a local sequence .Now lets how we can manipulate it very easily with the help of LINQ.

Example:
Write a code that returns only those values which are greater than 2.
Out Put:




















You can see that how we can easily manipulate data and can get result according to our requirements.
Another important feature of LINQ is Deferred Execution.
Deferred Execution:
It means that the execution of LINQ query does not execute at the time of creation. Rather it is executed when it is used.
Actually the execution of LINQ query starts with the foreach loop.
Example:
Out Put:


















Notice that result 99 has been included even at that time the query was constructed.
There are numbers of operators that runs at the time of query creation like ToArray, ToDictionery etc.
Example:
Out Put:

















Notice that 99 is not included,because of additional ToArray().


Tuesday 12 January 2016

                 Multi-Threading and Asynchronous                                                                    (Part 2) 

 In this blog, we will discuss about Join method , foreground thread and background thread and ParameterizedThreadStart.                              
1. Join Method
Join is synchronous method that blocks the other thread until the thread which is on the CPU terminates.
Example:
Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace SimpleThread
{
    class Program
    {
        //Thread Method
        public static  void ThreadMethod()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 0");
                
            }
                
        }
        public static void ThreadMethod1()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 1");

            }


        }

        static void Main(string[] args)
        {
            
            //Thread Declartion and calling 
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();//Start Thread
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));  //thread for Method2
            thread1.Start();//Start Thread
            Console.ReadKey(); //For holding Screen
        }
    }

}

OutPut1:
OutPut2:
Note:Every time you compile the code,you might get the different answer.So do not worry about that.
Now lets look what happen with the use of Join method.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace SimpleThread
{
    class Program
    {
        //Thread Method
        public static  void ThreadMethod()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 0");
                
            }
                
        }
        public static void ThreadMethod1()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 1");

            }


        }

        static void Main(string[] args)
        {
            
            //Thread Declartion and calling 
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();//Start Thread
thread.Join();    //Join Method
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));  //thread for Method2
            thread1.Start();//Start Thread
            Console.ReadKey(); //For holding Screen
        }
    }

}

Explanation:
The only change is  the thread.Join() method. Now the second thread would not execute until first thread terminates.
Output:

Now after every compilation you would get this result.

2.Foreground and Background  Thread
Foreground thread keeps your application alive.Once foreground thread ends ,application ends and background threads also terminates.By default ,all threads are foreground.

Note:
To make a thread background just  make the isBackground property true. If this property is false of a thread, it means it is foreground.
e.g 
Thread t=new Thread();
t.IsBackground = true;

Code:
 class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Foreground Thread");
                Thread.Sleep(300);
            }
            Console.WriteLine("Foreground thread is terminated");
        }
        public static  void ThreadMethod1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Background thread");
                Thread.Sleep(200);
            }
        }




        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();
            thread.Join();       
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));
            thread1.IsBackground = true;     //to make a thread background
            thread1.Start();

        }
    }
Out Put:
Foreground thread will execute ten times and application will terminated.
Explanation:
 As I have used Join method ,with which foreground thread will execute until it terminate. As second thread is background and background thread executes till the execution of foreground thread.As foreground thread terminates ,background thread also terminates .So when the above code executes,the first thread will executes ten times and then application will end.
Note:
In Console Application ,if use Console.ReadKey() for screen .The background thread will also execute ten times because Console.Readkey() behave as foreground thread.And we know that background thread executes until foreground thread is alive.

3. ParameterizedThreadStart
We can pass data through start method of a thread. For this purpose ,we use ParameterizedThreadStart delegate instead of  simple ThreadStart  delegate.

Example:
class Program
    {
        public static void ThreadMethod(object o)
        {
            for (int i = 0; i <(int)o; i++)
            {
                Console.WriteLine("thread Proc{0}", i);
            }
            
        }
        static void Main(string[] args)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(ThreadMethod));
            thread.Start(5);
            Console.ReadKey();
        }
    }
OutPut:
thread proc0
thread proc1
thread proc2
thread proc3
thread proc4
Explanation:
In that case ,value is passed to threadMethod as object,You can cast it to any other type.















                      Multi-Threading and Asynchronous                                                                 (Part 1)            

The early computers were based on batch processing .In batch processing ,a central processing unit(CPU) was capable of doing one task at a time.If a CPU has to take long time to execute a task,the other processes would have paused. In that case the whole machine would freeze.The things can be more worse,if there is a bug in the running task.The only solution is to restart the machine. The solution of this problem is Thread. In modern Operating systems each application runs in its own process. If this application affects ,the other processes would remain unaffected. Each process has its own "Virtual Memory". Each process is allowed to run for a particular time period.When this time period overs,thread is paused, it's state is saved and operating system switches to another thread.It is called "Context Switching".Actually at one time ,only one process runs on CPU. But today,as computing is so much fast and powerful and context switching happens so fast that we feel that computer is executing many tasks at a time.In .NET,for threading we use Thread Class.It can be found in System.Threading name space.

Note:Always import System.Threading in your project before using Thread Class .

Example:This is a simple example of threading.Common Mistake:When you call a function in Thread class,people commonly call it parenthesis like ().Do not call it with parenthesis.Just write down the name of the method.

Output:

















The above example shows an example of using the Thread class to run a  method . The Console class synchronizes the use of the output stream for you so you can write to it from multiple threads. Synchronization is the mechanism of ensuring that two threads don’t execute a specific portion of your program at the same time. In the case of a console application, this means that no two threads can write data to the screen at the exact same time. If one thread is working with the output stream, other threads will have to wait before it’s finished.




Saturday 19 December 2015

Extension Methods


                               Extension Method

Extension methods allow you to add methods to existing types .And the interesting thing is that you can do it without adding this method  or updating the  original type.

To define and call extension methods consider the following points:

  1. Define a static class that contains the extension method
  2. Define the extension method as static method
  3. Add the first parameter with 'this keyword' upon which this extension method has to be operated on.
  4. If the calling class  and the class which contains the extension method then add 'using' directive to specify the namespace which contains the extension method's class.
  5. Now you can call the extension method as it is the instance method of this type.
Example:
string s="My name is Usman";
s.Display(10);     //Display this name ten times 
Now the point is "Is there any Display method in string class ?The answer is no." But with extension method you can do it without updating the string class and even you can call this method with the instance of string class.


1.This is Class which contains the extension methods .Both class and extension method are with static  and as we have to call this method on string so we would use 'this keyword for first parameter .



2.This  is the calling class which calls the extension  method .In this class you declare a string object 'name'. There is no Display method which can be called with the string object.But with the extension method you can do that.




Output:








Thursday 17 December 2015

Delegate Part 3

Delegate Part 3

 Decoupling

Delegates also promotes decoupling(It is an Object oriented concept ,I will write about that later).
For Example you have written a class of Calculator ,in which you have written the methods of Addition,Subtraction,Multiplication and Division. Another class is using your these methods.You add some more methods in your class ,in order to use these methods you also need to change your class.
Delegates provides solution to this problem .
Lets  go through in a example


This is  a calculator class which takes inputs and perform Addition,Subtraction,Multiplication and Division operations and return result .

  1. namespace Delegates
  2. {
  3.     delegate int Mathoperation(int num1,int num2);     //Delegate declaration
  4.     class Calculator
  5.     {
  6.         public Mathoperation GetOperation(int option)
  7.         {
  8.             Mathoperation mathOperation = null;             //Currently, delegate object has no reference  
  9.             if (option == 1)
  10.             {
  11.                 mathOperation = Add;
  12.             }
  13.             else if (option == 2)
  14.             {
  15.                 mathOperation =Sub;
  16.             }
  17.             else if (option == 3)
  18.             {
  19.                 mathOperation = Div;
  20.             }
  21.             else if(option==4)
  22.             {
  23.                 mathOperation = Mul;


  24.             }
  25.             else
  26.             {
  27.                 Console.WriteLine("You choose the wrong option");
  28.             }


  29.             return mathOperation;
  30.         }
  31. //Mathematical Operations  
  32.       private int Add(int num1, int num2)
  33.         {
  34.             return num1 + num2;
  35.         }
  36.         private int Sub(int num1, int num2)
  37.         {
  38.             return num1-num2;
  39.         }
  40.         private int Div(int num1, int num2)
  41.         {
  42.             return num1 / num2;
  43.         }
  44.         private int Mul(int num1, int num2)
  45.         {
  46.             return num1 * num2;
  47.         }


  48.     }
}


This is class which is using the above class methods.

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {


  1. This is a class which is using these methods.
  2. Console.WriteLine("Enter the Option");
  3.             Console.WriteLine("1.Addition");
  4.             Console.WriteLine("2.Subtraction");
  5.             Console.WriteLine("3.Division");
  6.            Console.WriteLine("4.Multiplication");
  7.            int option = int.Parse(Console.ReadLine());
  8.            Calculator Cal_obj=new Calculator();
  9.            int result = Cal_obj.GetOperation(option).Invoke(10, 20);
  10.             Console.WriteLine(result);
  11. }
  12. }
Now whatever changes you made in your Calculator class,It would not affect your Program Class which is using the methods of this class.
This is called decoupling .And Object Oriented Method encourages decoupling .





Delegate Part 2

                                 Delegate Part(2)


Contents:
 In this article following content would be covered
  1. Multi Cast Delegate

     1.Multi Cast Delegate
"A delegate that contains multiple methods are Multi Cast Delegate. 

We use multi cast delegate when there is need of invoking multiple events like we want to print a string and at the same time we want to write this string in the file or that purpose we use multi cast delegate.


Note: These events are invoked in which  sequence you called them. For example there are two events print and read .The order in which read and print would be invoked depends upon the order in which you would call them(events).


 Example1:


//Class 1

  1.  class  Name
  2.     {
  3.         public void Print()
  4.         {
  5.             Console.WriteLine("My Name is Usman Arshad");
  6.         }
  7.     }

  8. //Class 2

  9. class Country
  10.     {
  11.         public void Print()
  12.         {
  13.             Console.WriteLine("I am from Pakistan");
  14.         }

  15.     }

  16. //Main Class
  17. namespace
  18. {

  19. public delegate void Multicastdelegate();
  20.  class Program
  21.     {
  22.  Name obj = new Name();
  23.     Country obj1 = new Country();
  24.             Multicastdelegate delegate = new Multicastdelegate(obj.Print);  //Reference of the print method of class Name
  25.             delegate= delegate + new Multicastdelegate(obj1.Print);      //Just use '+'  sign to add more methods
  26.                 obj1.Invoke();
  27.            }
  28. }









OutPut
My Name is Usman Arshad
I am from Pakistan

You can also write the statement no 30 like this
delegate+=new Multicastdelegate(obj1.Print);

Common Error

A common error which mostly beginner do is that when you pass the reference the method to the delegate object just pass the method name ,do not use function syntax .For example
  Multicastdelegate delegate = new Multicastdelegate(obj.Print( ));
This is a syntax error.Because you only need the name of the method not the method itself

In the next article ,I will write about Call-Back Methods.











Delegates Part 1

Delegate(Part 1)


"A delegate is similar to a pointer function in C or C++  that holds reference of a method.It allows to encapsulate reference to a method inside a delegate object .The delegate object can be passed to a code which can call the reference method."
You often read such definitions about delegates ,this is true but incomplete .The real purpose of a Delegate is to communicate .As 'delegate' is a English language word and  the meaning of this word is to represent or communicate between/among communities ,classes etc.
So the delegate are for communication. We use delegate when one class want to communicate with other class. Of course there are several other ways of doing that,but we should adopt the best way to do any thing.

Why we use Delegate?
C# does not allow us passing method reference directly as arguments  to other methods ,rather it provides delegates.

For example you write a Class(of code) .In this Class you have written a method .A second person working in your team or else where needs this method which you have written in your class. You would provide delegate to that person so that he/she can call this method.

Delegates are especially useful in event driven environment such as Graphical User Interface(GUI) in which you want that code execute when user clicks the button.


Note:Delegates are classes that encapsulate set of references to method.

There are two types of delegate

  1. Single Cast Delegate
  2. Multi Cast Delegate 

(See the detail of both in later section)

Single Cast Delegate:A delegate that contains a single method is known as Single Cast delegate. And it is derived from the class Delegate.
Multi Cast Delegate:  A delegate that contains multiple methods are Multi Cast Delegate. 
Both Single Cast Delegate and Multi Cast Delegate belong to Name-space System.

Before using delegates following point must consider:

"The method header (Parameter & return value) of a delegate and the method whose reference will be within a delegate object must have same method header."

Lets proceed to some practical examples

There are following steps involved in using Delegates:
Declaration
Instantiation
Invocation
Example 1: A simple Delegate

using System;

namespace Simple.Delegate
{
    //  Step 1:Declaration
    public delegate void SimpleDelegate();

    class MyClass
    {
        public static void Print()
        {
            Console.WriteLine("Delegate was Printed");
        }

        public static void Main()
        {
            //  Step 2:Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(Print);

            // Step 3: Invocation
            simpleDelegate();
        }
    }
}

In the later section,I will write further examples of Delegates.