Pages

Wednesday, September 16, 2015

SignalR with Client, Server modal

SignalR is a new developer's API provided for ASP.NET web applications, used to add "real time" web functionality to ASP.NET applications. "Real Time" web functionality is the ability to have server code to push contents to connected clients


SignalR supports "server push" or "broadcasting" functionality. It handles connection management automatically. In classic HTTP connections for client-server communication connection is re-established for each request, but SignalR provides persistent connection between the client and the server. In SignalR the server code calls out to a client code in the browser using Remote Procedure Calls (RPC), rather than request-response model today. SignalR is an open-source API, and is accessible through GitHub.

Where to use:
  1. Chat room applications
  2. Real-time monitoring applications
  3. Job progress updates
  4. Real time forms
Web Client

    Server end
     class Program
        {
            static void Main(string[] args)
            {
                // This will *ONLY* bind to localhost, if you want to bind to all addresses
                // use http://*:8080 to bind to all addresses. 
                // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx 
                // for more information.
                string url = "http://localhost:8080";
                WebApp.Start(url);
                Console.WriteLine("Server running on {0} \n", url);
                string command;
                Boolean quitNow = false;
                while (!quitNow)
                {
                    Console.WriteLine("Enter message for clients: ");
                    command = Console.ReadLine();
                    switch (command)
                    {
                        case "/quit":
                            quitNow = true;
                            break;
    
                        default:
                            var context = GlobalHost.ConnectionManager.GetHubContext();
                            context.Clients.All.NotifyMsg("server notifcation", command);
                            break;
                    }
                }
    
            }
        }
    
    
        class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);
                app.MapSignalR();
            }
        }
        public class MyHub : Hub
        {
            public void Send(string name, string message)
            {
                Clients.All.NotifyMsg(name, message);
            }
        }
    

    Monday, September 14, 2015

    Behavioral Pattern - Command Pattern

    Command pattern encapsulates a request as an object and gives it a known public interface. Command Pattern ensures that every object receives its own commands and provides a decoupling between sender and receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request and acts on it.


    Command Pattern

      public class GarageDoor
        {
            public string Up()
            {
                return "Garage Door Is Open";
            }
    
            public string Down()
            {
                return "Garage Door Is Closed";
            }
    
            public string Stop()
            {
                return "Stop door";
            }
    
            public string LightOn()
            {
                return "light On";
            }
    
            public string LightOff()
            {
                return "light Off";
            }
        }
    
        public class Light
        {
            public string On()
            {
                return "Light is on";
            }
        }
    
        public interface Command
        {
            string execute();
        }
    
        public class GarageDoorOpenCommand : Command
        {
            GarageDoor objGarageDoor = new GarageDoor();
            public GarageDoorOpenCommand(GarageDoor tmpGarageDoor)
            {
                this.objGarageDoor = tmpGarageDoor;
            }
    
            public string execute()
            {
                return this.objGarageDoor.Up();
            }
        }
    
        public class GarageDoorClosedCommand : Command
        {
            GarageDoor garagedoor;
            public GarageDoorClosedCommand(GarageDoor tempGarageDoor)
            {
                this.garagedoor = tempGarageDoor;
            }
    
            public string execute()
            {
                return this.garagedoor.Down();
            }
        }
    
        public class LightOnCommand : Command
        {
            Light light;
            public LightOnCommand(Light argLight)
            {
                this.light = argLight;
            }
    
            public string execute()
            {
                return this.light.On();
            }
        }
    
        public class SimpleRemoteControl
        {
            Command slot;
    
            public void SetCommand(Command command)
            {
                this.slot = command;
            }
    
            public string ButtonPressed()
            {
                return this.slot.execute();
            }
        }
    
    //************Client end************************************//
    SimpleRemoteControl remotecontrol = new SimpleRemoteControl();
    GarageDoor garagedoor = new GarageDoor();
    
    //encapsulates a request as an object
    GarageDoorOpenCommand objGarageDoorOpenCommand = new GarageDoorOpenCommand(garagedoor);
    //Loaded the button slot with a "Garage Door Open Command"
    remotecontrol.SetCommand(objGarageDoorOpenCommand);
    //From the outside,no other objects really know what actions get performed on what recevier
    Console.Write(remotecontrol.ButtonPressed() + "\n");
    
                
    //encapsulates a request as an object
    GarageDoorClosedCommand objGarageDoorClosedCommand = new GarageDoorClosedCommand(garagedoor);
    //Loaded the button slot with a "Garage Door Closed Command"
    remotecontrol.SetCommand(objGarageDoorClosedCommand);
    //From the outside,no other objects really know what actions get performed on what recevier
    Console.Write(remotecontrol.ButtonPressed() + "\n");
    
                
    //encapsulates a request as an object
    LightOnCommand objLight = new LightOnCommand(new Light());
    //Loaded the button slot with a "Light On"
    remotecontrol.SetCommand(objLight);
    //From the outside,no other objects really know what actions get performed on what recevier
    Console.Write(remotecontrol.ButtonPressed() + "\n");
                           
    //Remote slot didn't care what command object it had, as long as it implemented the command interface
    Console.ReadKey();
    
    

    Monday, August 24, 2015

    Implement callback routines CallBack using OOP

    Developers conversant in the event-driven programming model of MS-Windows and the X Window System are accustomed to passing function pointers that are invoked (that is, "called back") when something happens. object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism

    Interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked.

     
    
     public interface InterestingEvent
        {
            // This is just a regular method so it can return something or
            // take arguments if you like.
            void interestingEvent();
        }
    
        public class EventNotifier
        {
            private InterestingEvent ie;
            //private bool somethingHappened;
            public EventNotifier(InterestingEvent e)
            {
                Console.Write("EventNotifier called\n");
                // Save the event object for later use.
                ie = e;
                // Nothing to report yet.
                e.interestingEvent();
            }
        }
    
    
       public class CallMe : InterestingEvent
        {
            private EventNotifier en;
            public CallMe()
            {
                // Create the event notifier and pass ourself to it.
                en = new EventNotifier(this);
            }
            // Define the actual handler for the event.
            public void interestingEvent()
            {
                Console.Write("Call Me function called");
            }
            //...
        }
    
         //*****Client Side**************
         CallMe obj = new CallMe();
         Console.ReadKey();
         //******End***************
    
    

    Wednesday, July 22, 2015

    Creational Pattern - Factory Pattern With Abstract Factory Pattern

    Factory pattern is creational design pattern that suppose to create an object for client at runtime.In other words, responsibility of creating objects with same type delegate to some other class which is known as factory class.
     
    
       public interface Pizza
        {
             void prepare();
             void bake();
             void cut();
             void box();
        }
    
        public class CheesePizza : Pizza
        {
            public void prepare()
            {
                Console.Write("\n CheesePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("CheesePizza: bake \n");
            }
    
            public void cut()
            {
                Console.Write("CheesePizza: cut \n");
            }
    
            public void box()
            {
                Console.Write("CheesePizza: box \n");
            }
        }
    
        public class VeggiePizza : Pizza
        {
    
            public void prepare()
            {
                Console.Write("\n VeggiePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("VeggiePizza: bake\n");
            }
    
            public void cut()
            {
                Console.Write("VeggiePizza: cut\n");
            }
    
            public void box()
            {
                Console.Write("VeggiePizza: box\n");
            }
        }
    
        //SimplePizzaFactory class suppose to create object for client
        public class SimplePizzaFactory
        {
            public Pizza CreatePizza(string type)
            {
                Pizza pizza = null;
                switch (type)
                {
                    case "cheese":
                        pizza = new CheesePizza();
                        break;
                    case "veggie":
                        pizza = new VeggiePizza();
                        break;
                    default:
                        break;
                }
                return pizza;
            }
        }
    
        public class PizzaStore
        {
            SimplePizzaFactory factory;
    
            public PizzaStore(SimplePizzaFactory factory)
            {
                this.factory = factory;
            }
    
            public Pizza OrderPizza(string type)
            {
                Pizza pizza;
    
                //uses the factory to create pizza
                pizza = factory.CreatePizza(type);
    
                pizza.prepare();
                pizza.bake();
                pizza.cut();
                pizza.box();
    
                return pizza;
            }
        }
    
    
        //************HeadDesign: simple factory pattern*********************
    
            PizzaStore pizzStore = new PizzaStore(new SimplePizzaFactory());
            pizzStore.OrderPizza("cheese");
            pizzStore.OrderPizza("veggie");
            Console.ReadKey();
    
        //******************************************************************* 
    Abstract factory pattern: extended to existing simple factory and creating the related class for object creation.
    public interface Pizza
        {
            void prepare();
            void bake();
            void cut();
            void box();
        }
    
        public class NYSyleCheesePizza : Pizza
        {
            public void prepare()
            {
                Console.Write("\n NYSyleCheesePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("NYSyleCheesePizza: bake \n");
            }
    
            public void cut()
            {
                Console.Write("NYSyleCheesePizza: cut \n");
            }
    
            public void box()
            {
                Console.Write("NYSyleCheesePizza: box \n");
            }
        }
    
        public class NYVeggiePizza : Pizza
        {
    
            public void prepare()
            {
                Console.Write("\n NYVeggiePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("NYVeggiePizza: bake \n");
            }
    
            public void cut()
            {
                Console.Write("NYVeggiePizza: cut \n");
            }
    
            public void box()
            {
                Console.Write("NYVeggiePizza: box \n");
            }
        }
    
        public class ChSyleCheesePizza : Pizza
        {
            public void prepare()
            {
                Console.Write("\n ChSyleCheesePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("ChSyleCheesePizza: bake \n");
            }
    
            public void cut()
            {
                Console.Write("ChSyleCheesePizza: cut \n");
            }
    
            public void box()
            {
                Console.Write("ChSyleCheesePizza: box \n");
            }
        }
    
        public class ChVeggiePizza : Pizza
        {
    
            public void prepare()
            {
                Console.Write("\n ChVeggiePizza: prepare \n");
            }
    
            public void bake()
            {
                Console.Write("ChVeggiePizza: bake \n");
            }
    
            public void cut()
            {
                Console.Write("ChVeggiePizza: cut \n");
            }
    
            public void box()
            {
                Console.Write("ChVeggiePizza: box \n");
            }
        }
    
        public abstract class PizzaStore
        {
            public Pizza OrderPizza(string type)
            {
                Pizza pizza;
    
                //uses the factory to create pizza
                pizza = CreatePizza(type);
    
                pizza.prepare();
                pizza.bake();
                pizza.cut();
                pizza.box();
    
                return pizza;
            }
    
            public abstract Pizza CreatePizza(string type);
        }
    
        public class NYPizzaStore : PizzaStore
        {
            public override Pizza CreatePizza(string type)
            {
                switch (type)
                {
                    case "cheese":
                        return new NYSyleCheesePizza();
                        break;
                    case "veggie":
                        return new NYVeggiePizza();
                        break;
                    default:
                        break;
                }
                return null;
            }
        }
    
        public class ChPizzaStore : PizzaStore
        {
            public override Pizza CreatePizza(string type)
            {
                switch (type)
                {
                    case "cheese":
                        return new ChSyleCheesePizza();
                        break;
                    case "veggie":
                        return new ChVeggiePizza();
                        break;
                    default:
                        break;
                }
                return null;
            }
        }
    
    
    
     //************HeadDesign: abstract factory pattern*******************
         PizzaStore  NYPizzaStore= new NYPizzaStore();
         NYPizzaStore.OrderPizza("cheese");
             
         PizzaStore ChPizzaStore = new ChPizzaStore();
         ChPizzaStore.OrderPizza("veggie");
         Console.ReadKey();
    
    //********************************************************************
    
    
    

    Tuesday, July 21, 2015

    Structural Patterns - Decorator Pattern

    ~Add responsibilities to objects dynamically~

    The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

    By definition, in a solution designed in the Decorator pattern, there is a component class and then there is the decorator class. The decorator class holds a reference to an object of the component's type and itself is derived from the component class.
    Say what?
    Yes, and theoretically the decorator classes are chained together around the component class and use delegation to give the component class new responsibilities.


    UML - Decorator Pattern
    UML - Decorator Pattern


    Let have a look in practical example:-

       //Beverage is an abstract class with the two methods getDescription() and cost().
    
        public abstract class Beverage
        {
            protected string m_description = "UnKnown Beverage";
            //get a description of the beverage
            public virtual String Description { get { return m_description; } }
            public abstract double cost();
        }
    
        //we extend the Beverage class, since this is a beverage.
        public class Espresso : Beverage
        {
            public Espresso()
            {
                m_description = "Espresso";
            }
    
            public override double cost()
            {
                return 0.99;
            }
        }
    
    
        //here’s another Beverage.
        public class HouseBlend : Beverage
        {
            public HouseBlend()
            {
                m_description = "HouseBlend";
            }
    
            public override double cost()
            {
                return .89;
            }
        }
    
    
        //here’s another Beverage.
        public class DarkRoast : Beverage
        {
            public DarkRoast()
            {
                m_description = "DarkRoast";
            }
    
            public override double cost()
            {
                return .33;
            }
        }
    
    
        //we need to be interchangeable with a Beverage, so we extend the Beverage class.
        public abstract class CondimentDecorator : Beverage { }
    
        //here’s another Beverage.
        public class Decaf : Beverage
        {
            public Decaf()
            {
                m_description = "Decaf";
            }
    
            public override double cost()
            {
                return .43;
            }
        }
    
        //Mocha is a decorator, so we extend CondimentDecorator
        public class Mocha : CondimentDecorator
        {
            Beverage beverageInternal;
    
            public Mocha(Beverage beverage)
            {
                this.beverageInternal = beverage;
            }
    
            // getter implements abstract class Description
            public override String Description
            {
                get
                {
                    return beverageInternal.Description + ", Mocha";
                }
            }
    
            public override double cost()
            {
                return .20 + beverageInternal.cost();
            }
        }
    
    
        //Whip is a decorator, so we extend CondimentDecorator
        public class Whip : CondimentDecorator
        {
            Beverage beverageInternal;
    
            public Whip(Beverage beverage)
            {
                this.beverageInternal = beverage;
            }
    
            // getter implements abstract class Description
            public override String Description
            {
                get
                {
                    return beverageInternal.Description + ", Whip";
                }
            }
    
            public override double cost()
            {
                return 1.20 + beverageInternal.cost();
            }
    
        }
    
        //Soy is a decorator, so we extend CondimentDecorator
        public class Soy : CondimentDecorator
        {
            Beverage beverageInternal;
    
            public Soy(Beverage beverage)
            {
                this.beverageInternal = beverage;
            }
    
            // getter implements abstract class Description
            public override String Description
            {
                get
                {
                    return beverageInternal.Description + ", Soy";
                }
            }
    
            public override double cost()
            {
                return 2.20 + beverageInternal.cost();
            }
        }
    
     
    //Calling at client end as follow:-
    //************Decorator Pattern*******************************************
                //Order up an espresso, no condiments and print its description and cost.
                Beverage beverage = new Espresso();
                Console.Write("\n" + beverage.Description + " $ " + beverage.cost() + "\n");
    
                Beverage beverage2 = new DarkRoast();//Make a DarkRoast object.Finally,
                beverage2 = new Mocha(beverage2);//Wrap it with a Mocha
                beverage2 = new Mocha(beverage2);//Wrap it with second Mocha
                beverage2 = new Mocha(beverage2);//Wrap it with third Mocha
                beverage2 = new Whip(beverage2);//Wrap it in a Whip.
                beverage2 = new Soy(beverage2);//Wrap it in a Soy.
                beverage2 = new Soy(beverage2);//Wrap it in a Soy.
                beverage2 = new Soy(beverage2);//Wrap it in a Soy.
                beverage2 = new Soy(beverage2);//Wrap it in a Soy.
                Console.Write("\n" + beverage2.Description + " $ " + beverage2.cost() + "\n");
    
                Beverage beverage3 = new HouseBlend();
                beverage3 = new Soy(beverage3);
                beverage3 = new Mocha(beverage3);
                beverage3 = new Whip(beverage3);
                Console.Write("\n" + beverage3.Description + " $ " + beverage3.cost() + "\n");
                Console.ReadKey();
                //************************************************************************
    


    Here is the bullet points for decorator pattern:-
    1. Inheritance is one form of extension, but not necessarily the best way to achieve flexibility
    2. in our designs.
    3. In our designs we should allow behavior to be extended without the need to modify existing code.
    4. Composition and delegation can often be used to add new behaviors at runtime.
    5. The Decorator Pattern provides an alternative to subclassing for extending behavior.
    6. The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
    7. Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
    8. Decorators change the behavior of their components by adding new functionality before and/or
    9. after (or even in place of) method calls to the component.
    10. You can wrap a component with any number of decorators.
    11. Decorators are typically transparent to the client of the component; that is, unless the client is relying on the component’s concrete type.
    12. Decorators can result in many small objects in our design, and overuse can be complex.
    I have taken help from 'Head first design pattern' for above. Thanks to Head First Design Patterns and Team.