Saturday, 11 January 2014

Download a Html from web using Async - Await C# 5

         In this article we are going to see how to use the Async and Await and what is the difference the Async -await and  old Asynchronus format.In Generally when we using the Async amd await keyword the method should have a Async along with Task Return type. then we can mention the await keyword wherever the async method is call. Why we have to mention the Await instead of just mention the Async as in the return type, it is because in the Async process the execution of method is invoked and then the object is get disposed by the next line of execution, to avoid this we have to make await.

What is the Difference between the Async-Await and Old format async programing ?

          Generally if we are writing a asynchronous programming developers thought is , the thread is running in the background and the UI responsive will be in good state. Then this is the same for Async-Await , If we really see deeply there is a big difference is present, Actually when we use the thread to run in background it will run ,but when the I/O bound operation comes the thread execution is sleep or pause and the I/O operation starts the process when the I/O operation ends a signal is sent to the thread to start the thread from interrupt.
          So there is a Wait and sleep is maintain once the I/O operation starts. but in the Async-Await the program is running in background and when the I/O operation reaches then the I/O operation is execution starts but the Thread starts executing the next line of code instead of wait and it will receive a signal from the I/O once operation completes.

         So I/O operation bound is a major difference between the Thread in Asynchronous and Async-Await.
Now let we see in programming 

Asynchronous programming in C# 4

private static void DownloadHtmlOldAsync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            httprequest.BeginGetResponse(ar =>
            {
                var httpresponse = httprequest.EndGetResponse(ar);
                using (var resp = httpresponse.GetResponseStream())
                {
                    var buffer = new byte[2048];
                    var manualreset = new ManualResetEvent(false);
                    AsyncCallback readCallback = null;
                    readCallback = rasync =>
                    {
                        var bytesread = resp.EndRead(rasync);
                        if (bytesread > 0)
                        {
                            Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                            resp.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                        }
                        else
                        {
                            manualreset.Set();
                        }
                    };

                    resp.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                    manualreset.WaitOne();
                }

            }, null);

        }

Async - Await C# 5

 private static async Task DownloadHtmlNewAsync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            var webresponse = await httprequest.GetResponseAsync();
            using (var responsestream = webresponse.GetResponseStream())
            {
                var buffer = new byte[2048];
                int bytesread =0;
               
                while((bytesread= await responsestream.ReadAsync(buffer, 0, buffer.Length))>0)
                {
                    Console.WriteLine(Encoding.UTF8.GetString(buffer,0,bytesread));
                }
            }

        }


Synchronous Program

  private static void DownlaodHtmlSync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            var webresponse = httprequest.GetResponse();
            using(var respstream = webresponse.GetResponseStream())
            {
                var buffer = new byte[2048];
                int bytesread = 0;
                while((bytesread=respstream.Read(buffer,0,buffer.Length))>0)
                {
                    Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesread));
                }
            }
        }

      

Program

        static void Main(string[] args)
        {
            /* Read Html Page*/
            DownlaodHtmlSync("http://www.dotnetvisio.blogspot.com");
            Console.ReadLine();

        }

I hope from this article you can learn what is the usage of async - await , and major difference the Asynchronous program in C# 4 and 5

Friday, 10 January 2014

Adapter design pattern - Implementation

In this article we are going to see the Adapter design pattern and there implementation, Adapter design pattern is  convert a interface of a class in to a client required interface, it is acts as a intermediate layer between the client and the target class.

Class View:
Client Code:

static void Main(string[] args)
{
          
            /*  Adapter Design Pattern */
            ICurrentAdapter two = new TwoPinAdapter();
            ICurrentAdapter three = new ThreePinAdapter();
            List<ICurrentAdapter> adapters = new List<ICurrentAdapter>();
            adapters.Add(two);
            adapters.Add(three);

            foreach(ICurrentAdapter adapter in adapters)
            {
                adapter.Plug();
                Console.WriteLine(" {0} , Power Consumption: {1} ", adapter.GetType().Name, adapter.CurrentConsumption);
            }

            Console.ReadLine();
}



Adapter Design:

 class Current
    {
        private int Amps;

        public Current(int amps)
        {
            Amps = amps;
        }

        public int CurrentConsumption()
        {
            return Amps * 3;
        }

    }


    interface ICurrentAdapter
    {       
        int CurrentConsumption { get; }
       
        void Plug();
    }


    class ThreePinAdapter:ICurrentAdapter
    {
        Current curr;

        public int CurrentConsumption
        {
            get { return curr.CurrentConsumption(); }
        }

        public void Plug()
        {
            curr = new Current(40);
        }
    }

    class TwoPinAdapter:ICurrentAdapter
    {
        Current curr;

        int ICurrentAdapter.CurrentConsumption
        {
            get { return curr.CurrentConsumption(); }
        }

        public void Plug()
        {
            curr = new Current(20);           
        }
       

    }

Output

TwoPinAdapter , Power Consumption: 60
ThreePinAdapter , Power Consumption: 120




From this article we can learn how to implement the Adapter design pattern.

Abstract Factory design pattern - implementation

In this article we are going to see the how to implement the Abstract Factory design pattern in code, Abstract Factory design is creating a abstract class and a abstract method  which will return the required instance based on the input parameter type and create a Factory by the static method.

Sample Code:

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

namespace AbstractFactoryDesign
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Abstract Factory Design ...");

            AnimalFactory landAnimalfactory = AnimalFactory.GetAnimalFactory(FactoryType.LandAnimalFactory);
            Console.WriteLine();
            Console.WriteLine("***** Land Animal *****");           
            Console.WriteLine(landAnimalfactory.GetAnimal(AnimalType.Lion).Speak());
            Console.WriteLine(landAnimalfactory.GetAnimal(AnimalType.Dog).Speak());           
            Console.WriteLine();
            AnimalFactory seaAnimalfactory = AnimalFactory.GetAnimalFactory(FactoryType.SeaAnimalFactory);
           
            Console.WriteLine("***** Sea Animal ******");           
            Console.WriteLine(seaAnimalfactory.GetAnimal(AnimalType.Octopus).Speak());
            Console.WriteLine(seaAnimalfactory.GetAnimal(AnimalType.Whale).Speak());
            Console.WriteLine();
            Console.WriteLine(".......");
            Console.Read();

        }
    }
}


Output:
Abstract Factory Design ...

***** Land Animal *****
Roar
Bark

***** Sea Animal ******
Whack
No Voice

.......


Now in this sample we take a Interface IAnimal which have a method speak, now this is imlpement for many animals cow, dog, lion, shark, octopus.
  
    public interface IAnimal
    {
        string Speak();
    }


    class Dog:IAnimal
    {
        public string Speak()
        {
            return "Bark";
        }
    }

    class Lion:IAnimal
    {
        public string Speak()
        {
            return "Roar";
        }
    }

    class Cat:IAnimal
    {
        public string Speak()
        {
            return "Meow";
        }
    }

    class Octopus:IAnimal
    {
        public string Speak()
        {
            return "Whack";
        }
    }

    class Whale:IAnimal
    {
        public string Speak()
        {
            return "No Voice";
        }
    }


Declare the Enum Types


    public enum AnimalType
    {
        Lion,
        Dog,
        Cat,
        Whale,
        Octopus,

    }

    public enum FactoryType
    {
        LandAnimalFactory,
        SeaAnimalFactory
   
    }



Now Let we create a Abstract Factory class with static method return the child instance type ,based on the input. Create a Two derived class from the abstract factory as LandAnimalFactory and SeaAnimalFactory

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

namespace AbstractFactoryDesign
{
    public abstract class AnimalFactory
    {
        public abstract IAnimal GetAnimal(AnimalType animalType);

        public static AnimalFactory GetAnimalFactory(FactoryType factoryType)
        {
            switch(factoryType)
            {
                case FactoryType.LandAnimalFactory:
                    return new LandAnimalFactory();
                case FactoryType.SeaAnimalFactory:
                    return new SeaAnimalFactory();
                default :
                    return null;
            }
        }

    }
         }


   class LandAnimalFactory:AnimalFactory
    {
        public override IAnimal GetAnimal(AnimalType animalType)
        {
            switch(animalType)
            {
                case AnimalType.Cat:
                    return new Cat();
                case AnimalType.Dog:
                    return new Dog();
                case AnimalType.Lion:
                    return new Lion();
                default :
                    return null;
            }
        }
    
}



class SeaAnimalFactory:AnimalFactory
    {
        public override IAnimal GetAnimal(AnimalType animalType)
        {
           switch(animalType)
           {
               case AnimalType.Octopus:
                   return new Octopus();
               case AnimalType.Whale:
                   return new Whale();
               default :
                   return null;

           }
        }
    }


I hope from this article you can learn how to implement the abstract factory design pattern in code.