Popular Posts

Dec 25, 2012

Design Patterns


Creational Patterns

Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Prototype
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Singleton
Ensure a class only has one instance, and provide a global point of access to it.

Structural Patterns

Adapter
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Facade
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Flyweight
Use sharing to support large numbers of fine-grained objects efficiently.
Proxy
Provide a surrogate or placeholder for another object to control access to it.


Behavioral Patterns

Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Interpreter
Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Memento
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Observer
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
State
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.


Source: unknown

The S.O.L.I.D. Design Principles




The S.O.L.I.D. design principles are a collection of best practices for object-oriented design.



Single Responsibility Principle (SRP)

The principle of SRP is closely aligned with SoC. It states that every object should only have one
reason to change and a single focus of responsibility. By adhering to this principle, you avoid the
problem of monolithic class design that is the software equivalent of a Swiss army knife. By having concise objects, you again increase the readability and maintenance of a system.



Open-Closed Principle (OCP)

The OCP states that classes should be open for extension and closed for modification, in that you
should be able to add new features and extend a class without changing its internal behavior. The
principle strives to avoid breaking the existing class and other classes that depend on it, which
would create a ripple effect of bugs and errors throughout your application.



Liskov Substitution Principle (LSP)

The LSP dictates that you should be able to use any derived class in place of a parent class and have it behave in the same manner without modification. This principle is in line with OCP in that it ensures that a derived class does not affect the behavior of a parent class, or, put another way, derived classes must be substitutable for their base classes.



Interface Segregation Principle (ISP)

The ISP is all about splitting the methods of a contract into groups of responsibility and assigning interfaces to these groups to prevent a client from needing to implement one large interface and a host of methods that they do not use. The purpose behind this is so that classes wanting to use the same interfaces only need to implement a specific set of methods as opposed to a monolithic interface of methods.



Dependency Inversion Principle (DIP)

The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation.


Source: unknown


Dec 11, 2012

Object Serialization - C#


Writing data to the disk as text is always dangerous. Any user can open the text file and easily read the data. With Object Serialization.

Serialization is the process of converting complex objects into stream of bytes for storage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form. The namespace which is used to read and write files is System.IO. For Serialization we are going to look at the System.Runtime.Serializationnamespace. The ISerializable interface allows to make any class Serializable.

- Create a console project.add a class named it Employee
[Serializable()] //Set this attribute to all the classes that you define to be serialized
    public class Employee : ISerializable
    {
        public int EmpId;
        public string EmpName;

        //Default constructor
        public Employee()
        {
            EmpId = 0;
            EmpName = null;
        }

        //Deserialization constructor.
        public Employee(SerializationInfo info, StreamingContext ctxt)
        {
            //Get the values from info and assign them to the appropriate properties
            EmpId = (int)info.GetValue("EmployeeId", typeof(int));
            EmpName = (String)info.GetValue("EmployeeName", typeof(string));
        }

        //Serialization function.
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            //You can use any custom name for your name-value pair. But make sure you
            // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
            // then you should read the same with "EmployeeId"
            info.AddValue("EmployeeId", EmpId);
            info.AddValue("EmployeeName", EmpName);
        }

    }
 static void Main(string[] args)
        {
            //Create a new Employee object
            Employee mp = new Employee();
            mp.EmpId = 204;
            mp.EmpName = "Jubayer";

            // Open a file and serialize the object into it in binary format.
            // EmployeeInfo.osl is the file that we are creating. 
            // Note:- you can give any extension you want for your file
            // If you use custom extensions, then the user will now 
            //   that the file is associated with your program.
            Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();

            Console.WriteLine("Writing Employee Information");
            bformatter.Serialize(stream, mp);
            stream.Close();

            //Clear mp for further usage.
            mp = null;

            //Open the file written above and read values from it.
            stream = File.Open("EmployeeInfo.osl", FileMode.Open);
            bformatter = new BinaryFormatter();

            Console.WriteLine("Reading Employee Information");
            mp = (Employee)bformatter.Deserialize(stream);
            stream.Close();

            Console.WriteLine("Employee Id: {0}", mp.EmpId.ToString());
            Console.WriteLine("Employee Name: {0}", mp.EmpName);
            Console.ReadKey();

        } 
Download Code 

Nov 16, 2012

Generics Classes - C#




Generic classes have type parameters. Several separate classes in a C# program, each with a different field type in them, can be replaced with a single generic class. The generic class introduces a type parameter. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.This becomes part of the class definition itself.

In this example, the letter T denotes a type that is only known based on the calling location. The program can act upon the instance of T like it is a real type, but it is not.



Create a console project then create a class  MyGenericClass.cs


public class MyGenericClass
    {
        //Generic variables 
        private T d1;
        private T d2;


        public MyGenericClass() { }

        //Generic constructor    
        public MyGenericClass(T a1, T a2)
        {
            d1 = a1;
            d2 = a2;
        }
        //Generic properties 
        public T D1
        {
            get { return d1; }
            set { d1 = value; }
        }

        public T D2
        {
            get { return d2; }
            set { d2 = value; }
        }

        public void ResetValues()
        {
            d1 = default(T);
            d2 = default(T);
           
        }

    }



In Program.cs file type the following CODE:

//contain int values 
MyGenericClass c1 = new MyGenericClass(5, 10); 
           // reset values to 0 
             c1.ResetValues();
          // Console.WriteLine();
            //contain  string values
MyGenericClass c2 = new MyGenericClass("a", "b");
            //reset values to null 
            c2.ResetValues();








For more visit http://msdn.microsoft.com/en-us/library/sz6zd40f.aspx

Generics- C#




- Generics are used to help make the code in the software components much more
reusable.
- They are a type of data structure that contains code that remains the same. 
- The data type of the parameters can change with each use.
- The usage within the data structure adapts to the different data type of the passed
variables. 


Create a console project then create a class Person.
public class Person
    {
       private string _Name;
       private int _Age;
      

      
      public string Name
       {
          get{return _Name;}
          set{_Name = value;}
       }

       public int Age
       {
          get{return _Age;}
          set{_Age = value;}
       }

    }



In Programs.cs file write the code:
System.Collections.Generic.List employees = new System.Collections.Generic.List();


// now add a couple of generic person objects to the generic collection 
             Person p1 = new Person();
             p1.Name = "John";
             p1.Age = 23;
             employees.Add(p1);

             Person p2 = new Person();
             p2.Name = "James";
             p2.Age = 34;
             employees.Add(p2);

            // now we have a type-safe collection of objects with the 
            // richness of Intellisense built in 
            // print out the contents of the collection 
            foreach (Person p in employees) 
            { 
               Console.WriteLine(String.Format("{0} - {1}", p.Name, p.Age)); 
            }

            Console.ReadKey();







Oct 18, 2012

Agile Thinking



- Analyse root causes of problems
- Plot the course to a better future
- Plan quickly and thoroughly
- Resolve conflicts without compromise

http://flyinglogic.com

Oct 6, 2012

Using Anonymous Method in C#




Implementing an Anonymous Method:

-Open windows form application

public Form1()
        {
            InitializeComponent();

            Button btnHello = new Button();
            btnHello.Text = "Hello";

            btnHello.Click +=
                delegate
                {
                    MessageBox.Show("Hello");
                };

            Controls.Add(btnHello);
        }



Using Parameters with Anonymous Methods

Button btnHello = new Button();
            //Button btnGoodBye = new Button();
            btnHello.Text = "Hello";

            btnHello.Click +=
                delegate(object sender, EventArgs e)
                {
                    string message = (sender as Button).Text;
                    MessageBox.Show(message);
                };

            Controls.Add(btnHello);


Why should we use Anonymous method?

We can reduce the code by preventing delegate instantiation and registering it with methods. It increases the
readability and maintainability of our code by keeping the caller of the method and the method itself as close to one another as possible

Call Anonymous Method using event programming In C#


Anonymous Method

- An anonymous method is a method without a name - which is why it is called anonymous. You
don't declare anonymous methods like regular methods. Instead they get hooked up directly to
events. You'll see a code example shortly.
-  To see the benefit of anonymous methods, you need to look at how they improve your
development experience over using delegates. Think about all of the moving pieces there are with
using delegates: you declare the delegate, write a method with a signature defined by the delegate
interface, delcare the event based on that delegate, and then write code to hook the handler method
up to the delegate. With all this work to do, no wonder programmers, who are new to C#
delegates, have to do a double-take to understand how they work. Because you can hook an
anonymous method up to an event directly, a couple of the steps of working with delegates can be
removed.
-  The code in Listing below is a Windows Forms application. It instantiates a Button control and
sets its Text to "Hello". Notice the  combine,  +=, syntax being used to hook up the anonymous
method. You can tell that it is an anonymous  method because it uses the delegate keyword,
followed by the method body in curly braces. Remember to terminate anonymous methods with a
semi-colon.


Implementing an Anonymous Method:

-Open windows form application

public Form1()
        {
            InitializeComponent();

            Button btnHello = new Button();
            btnHello.Text = "Hello";

            btnHello.Click +=
                delegate
                {
                    MessageBox.Show("Hello");
                };

            Controls.Add(btnHello);
        }

Events Programming in C#


Events
- An event is an automatic notification that some action  has occurred.
-  An event might be a button push, a menu selection, and so forth. In short, something
happens and you must respond to it with an event handler. 
-  Event is a member of a class and are declared using the event keyword which has the
form-


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

namespace Final_events
{
    // Declare a delegate for an event.  
    delegate void MyEventHandler();

    // Declare an event class. 
    class MyEvent
    {
        public event MyEventHandler SomeEvent; 
 
          // This is called to fire the event. 
          public void OnSomeEvent() { 
            if(SomeEvent != null) 
              SomeEvent(); 
          } 
        }
   

    

    class Program
    {
        // An event handler. 
        static void handler()
        {
            Console.WriteLine("Event occurred");
        }

        static void Main(string[] args)
        {
            MyEvent evt = new MyEvent(); 
 
            // Add handler() to the event list. 
            evt.SomeEvent += handler; 
         
            // Fire the event. 
            evt.OnSomeEvent();

            Console.ReadKey();

        }
    }
}

Purpose of Delegate And Captured variable in C#.




Demonstrate a captured variable.


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

namespace DemoCapture
{
    // This delegate returns int and takes an int argument. 
    delegate int CountIt(int end);
    class VarCapture
    {
        static CountIt counter()
        {
            int sum = 0;

            // Here, a summation of the count is stored 
            // in the captured variable sum. 
            CountIt ctObj = delegate(int end)
            {
                for (int i = 0; i <= end; i++)
                {
                    Console.WriteLine(i);
                    sum += i;
                }
                return sum;
            };
            return ctObj;
        }

        class Program
        {
            static void Main(string[] args)
            {
                // Get a counter 
                CountIt count = counter();

                int result;

                result = count(3);
                Console.WriteLine("Summation of 3 is " + result);
                Console.WriteLine();

                result = count(5);
                Console.WriteLine("Summation of 5 is " + result);
                Console.ReadKey();
            }
        }
    }
}



Purpose of Delegate

- It supports event programming
- It gives the program a way to execute a method at runtime without having to know
precisely what that method is at compile time.





An anonymous method that returns a value(C#)



Demonstrate an anonymous method that returns a value



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

namespace AnoynRetnValue
{

    // This delegate returns a value. 
    delegate int CountIt(int end);


    class Program
    {
        static void Main(string[] args)
        {
            int result;

            // Here, the ending value for the count 
            // is passed to the anonymous method.   
            // A summation of the count is returned. 
            CountIt count = delegate(int end)
            {
                int sum = 0;

                for (int i = 0; i <= end; i++)
                {
                    Console.WriteLine(i);
                    sum += i;
                }
                return sum; // return a value from an anonymous method 
            };

            result = count(3);
            Console.WriteLine("Summation of 3 is " + result);
            Console.WriteLine();

            result = count(5);
            Console.WriteLine("Summation of 5 is " + result);

            Console.ReadKey();
        }
    }
}

Anonymous method that takes an argument(C#)



An anonymous method that takes an argument



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

namespace DemonsAnoynmous
{
    // Notice that CountIt now has a parameter. 
    delegate void CountIt(int end); 

    class Program
    {
        static void Main(string[] args)
        {
            // Here, the ending value for the count 
            // is passed to the anonymous method. 
            CountIt count = delegate(int end)
            {
                for (int i = 0; i <= end; i++)
                    Console.WriteLine(i);
            };

            count(3);
            Console.WriteLine();
            count(5);
            Console.ReadKey();
        }
    }
}