Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Tuesday, April 29, 2008

* Master Managed Threading and Synchronization Techniques

Check out my latest article on Devx.com.

It starts from the basics of Threading & Thread Management, and dives deep into various synchronization
techniques available in .NET framework which includes inter-thread and inter-process synchronization.
The synchronization techniques discussed are:
 Locks / Monitors
 Mutex
 Interlocked
 Read-Writer Locks
 Semaphores
 EventWaitHandle

Master Managed Threading and Synchronization Techniques

Wednesday, February 06, 2008

* Patterns : Iterator Behavioral Pattern

Iterator Behavioral Pattern provides an access interface to an aggregate or collection object for clients. The iterator abstracts the clients from how the collection has been structured and also provides sequential navigation capabilities over collection.

Consider the following class diagram :

Iterator

NodeCollection type holds objects of type Node and there are two Iterators provided for NodeCollection objects.

The client code looks like following :

public class Client
{
    NodeCollection nc = new NodeCollection();
    BaseIterator forwardIterator;
    public void Run()
    {
        nc.AddNode(new Node("Name 0"));
        nc.AddNode(new Node("Name 1"));
        nc.AddNode(new Node("Name 2"));
        nc.AddNode(new Node("Name 3"));
        nc.AddNode(new Node("Name 4"));
        nc.AddNode(new Node("Name 5"));
        nc.AddNode(new Node("Name 6"));
        nc.AddNode(new Node("Name 7"));

        forwardIterator = nc.GetForwardIterator();
        Node n = forwardIterator.FirstNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
    }
}

 

If iterators are not provided, client needs to know how to access each element using [index]. But with iterators the accessing code becomes much simpler & can be same for any type of collection structures.

Download Iterator Behavioral Pattern Source Code

Other Design Patterns

Monday, January 28, 2008

* Patterns : Interpreter Behavioral Pattern

Interpreter Behavioral Pattern as name suggests is used to interpret sentences in langauge provided represented in a particular form.

The langauge should be representable in form of abstract syntax tree. Two types of nodes are used for expressions : Terminal Expressions & Non-Terminal Expressions.

Let's take an example of a command line calculator which can take expressoins in form of a+b-c+d and return the output.

The class diagram representing such calculator can be following :

Interpreter

Calculator class is an example of an Interpreter which parses the input statement and creates tree using NumberExpression (Terminal) & OperatorExpression (Non-Terminal). Both Expression classes have an abstract base which is used by Calculator to evaluate the tree.

public class Calculator
{
    BaseExpression bTree; //not used.
    Context ctx;
    public void Calculate(string expr)
    {
        //expr = "5+1-3";
        ctx = new Context();
        List<BaseExpression> tree = new List<BaseExpression>();
        char[] elements = expr.ToCharArray();
        foreach (char c in elements)
        {
            if (c.ToString().Equals("+") || c.ToString().Equals("-"))
            {
                tree.Add(new OperatorExpression(c));
            }
            else
            {
                tree.Add(new NumberExpression((int)c-48));
            }
        }
        foreach (BaseExpression exp in tree)
        {
            exp.Evaluate(ctx);
        }
        Console.WriteLine(ctx.Total);
    }
}

Download Interpreter Behavioral Pattern Source code

Other Design Patterns

Tuesday, January 15, 2008

* Patterns : Command Behavioral Pattern

Command Patterns helps encapculating/mapping a request to object called command. All commands are derived from base command which has mainly two methods Execute & UnExecute. The commands forwards the request data to Receiver for further processing.

Either client can decide which Command and  Receiver to be invoked or it can be configuration based for loose coupling.

One of the popular places where Command Pattern is used : Model View Controller (MVC) pattern.

Consider the diagram below :

Command

Invoker is the class responsible for executing commands. Since all commands expose common interface, Inovker can be quite generic and appropiate place for logging details.

In the above implementation, client needs to be aware of all three objects Invoker, Command and Receiver. This can be alternately be config based and client just needs to pass request to Invoker.

public class Client
    {
        Receiver receiver;
        BaseCommand command;
        Invoker invoker;

        public void Run()
        {
            receiver = new Receiver();
            command = new ConcreteCommand();
            command.SetReceiver(receiver);
            invoker = new Invoker();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.Read();
        }
    }

Download Source code : Command Behavioral Pattern

Other Design Patterns

Thursday, January 10, 2008

* Patterns : ChainOfResponsibility Behavioral Pattern

ChainOfResponsibility Behavioral Pattern helps achieving loose coupling between request sender and receiver object.

It helps in introducing a set of chained interceptor objects which can handle the request or pass it to next member in chain. The chaining can be pre-configured or can be done by client before invoking the chain.

Consider the below class diagram:

ChainOfResponsibility

Based on the base exception handler, a set of concrete exception handlers are created. Now client can chain them based on how specific handling of exception is required.

BaseExceptionHandler sqlHandler, securityHandler, allHandler;
public void Run()
{
    sqlHandler = new SqlExceptionHandler();
    securityHandler = new SecurityExceptionHandler();
    allHandler = new AllExceptionHandler();

    sqlHandler.SetSuccessor(securityHandler);
    securityHandler.SetSuccessor(allHandler);

    Exception ex = new Exception();
    sqlHandler.HandleException(ex);
}

Additional handlers can be configured in between or at the end.

It chains the receiving objects and pass the request along the chain until an object handles it.

Download code of ChainOfResponsibility Behavioral Pattern

Other Design Patterns

Monday, November 12, 2007

* Patterns : Proxy Structural Pattern

Proxy Structural Pattern or Proxy object can be used in multiple ways. Some of them could be following :

  • Act as a simpler interface to a complex object.
  • Can be used to transform call from one format to another.
  • can be used to load balance multiple objects.
  • can be used to track concurrency or object numbers.

Consider this example where a Proxy Calculator is acting as interface to Real Calculator. Client makes all calls to Proxy and proxy's responsibility is to route the calls both ways. This proxy template can be used to perform any of the above mentioned tasks with some modifications.

Proxy

Client is aware of only ProxyCalculator.

public class ProxyCalculator : ICalculator
{
    #region ICalculator Members

    RealCalculator rc;

    public ProxyCalculator()
    {
        rc = new RealCalculator();
    }

    public int Add(int firstNum, int secondNum)
    {
        return rc.Add(firstNum, secondNum);
    }

    public int Multiply(int firstNum, int secondNum)
    {
        return rc.Multiply(firstNum, secondNum);
    }

    #endregion
}

ProxyCalculator creates the reference of RealCalculator and forwards all client calls to RealCalculator.

Download Proxy Structural Pattern Source Code

* Free Book on .NET and CSharp

Check out this free book from Windows Programming Guru Charles Petzold.

What the C or C++ Programmer Needs to Know About C# and the .NET Framework

Supporting source code is also available for download.

Tuesday, November 06, 2007

* Patterns : Flyweight Structural Pattern

Flyweight Structural Pattern is used to manage large number of shared objects. They are maintained in a collection and same instances used whenever required. These objects have their own attributes/features but they can have a common feature also which can be externalized.

Consider a scenario where a picture has to be drawn which consists of large numbers of polygons of different colors. All polygons have number of sides property which is very specific to them but all of them have a common property called color which can be externalized. Also for same polygon type like 'Square',  number of sides remain same but color may change. Flyweight pattern helps in managing such kind of scenarios.

FlyWeight

Polygon factory manages the collection of polygons. Each concrete polygon stores number of sides but the color property is taken at runtime. Same instance of polygon can be used to draw any number of times with different color.

The client code is following :

namespace FlyWeight
{
    public class Client
    {
        PolygonFactory factory;
        public void Run()
        {
            factory = new PolygonFactory();
            Polygon square = factory.GetPolygon("SQUARE");
            square.Draw("RED");
            Polygon triangle = factory.GetPolygon("TRIANGLE");
            triangle.Draw("GREEN");
        }
    }
}

Download source code : Flyweight Structural Pattern Source Code

Thursday, October 18, 2007

* Patterns : Facade Structural Pattern

'Facade Structural Pattern' is primarily used to unify and simply a set of interfaces of subsystems. This helps the client in using the interface with less effort.

Consider the class diagram below :

Facade

Above shows a typical scenario of a Bank where a new Customer approaches the Bank to open new account and also deposit some initial amount.

The Core Banking subsystems provide two different interfaces for Customer and Account and two different calls are required for Account opening and deposit of amount.

The Bank Facade shown above simplifies the new Customer creation, new Account Creation and deposit amount by providing a single interface/call to perform the required actions.

The Bank facade has following code :

// Acts as Facade
public class Bank
{
    Customer cust;
    Account acct;
    public void CreateCustomer(string name, string address, double initalDeposit)
    {
        cust = new Customer(name, address);
        acct = new Account(name, 1234);
        acct.Deposit(initalDeposit);
    }
}

Download Full source code : Facade Structural Pattern Source Code

Monday, October 15, 2007

* Patterns : Decorator Structural Pattern

The primary use of 'Decorator Structural Pattern' is to add behaviors to object at runtime. It generally involves wrapping the original object with the decorator object which adds the new behaviors but keep the structure of original object intact. Multiple behaviors can be added out of given options based on decision criteria.

Consider the class diagram below :

Decorator

There is a BookBase class which is extended based on subjects of books and types of books. FictionBook subclasses BookBase based on subject/category while VideoBookBase subclasses BookBase based on type of book.

Now BookBase has a method called DisplayInfo() which is used to display about book. If DisplayInfo is called on FictionBook object it will display only the properties which are common to all display books, but suppose the fiction book is a video book and the DispayInfo should also display the duration, we use the above pattern as below :

The client code looks like following :

public class Client
{
    FictionBook bookFiction;
    VideoBookBase videoBookFiction;
    public void Run()
    {
        bookFiction = new FictionBook();
        //NonFictionBook bookNonFiction = new NonFictionBook();
        videoBookFiction = new VideoBook(bookFiction);
        //VideoBookBase videoBookNonFiction = new VideoBook(bookNonFiction);

        bookFiction.DisplayInfo();
        videoBookFiction.DisplayInfo();
        //videoBookNonFiction.DisplayInfo();
    }
}

FictionBook object is wrapped by VideoBook at runtime.

Download full source code : Decorator Structural Pattern

 

Tuesday, October 09, 2007

* Patterns : Composite Structural Pattern

Composite Structural Pattern is applicable when you need to deal with whole-part kind of relationships or tree kind of structures. It helps client to deal with individual or composite objects in a uniform manner and thus abstracts the client from complexities of internal structure.

Consider the following class diagram :

Composite

In the above diagram Book is a simple type but LibrarySection is a complex type and is composed of Book type instances. But both have same base which is BookBase and so both the simple type and composite type have same methods exposed to client.

The client code will look like following :

public class Client
{
    Book cSharpBook,vbBook,historyBook,religion;
    LibrarySection techBooks, nonTechBooks, library;
    public void Run()
    {
        cSharpBook = new Book("CSharp Book");
        vbBook = new Book("Visual Basic Book");
        techBooks = new LibrarySection("Technical Books");
        techBooks.Add(cSharpBook);
        techBooks.Add(vbBook);
        techBooks.List();

        Console.WriteLine("----------------------------------------------------------");

        historyBook = new Book("History Book");
        religion = new Book("Religion Book");
        nonTechBooks = new LibrarySection("Non Technical Books");
        nonTechBooks.Add(historyBook);
        nonTechBooks.Add(religion);
        nonTechBooks.List();

        Console.WriteLine("----------------------------------------------------------");

        library = new LibrarySection("Library");
        library.Add(techBooks);
        library.Add(nonTechBooks);
        library.List();
    }
}

By using this pattern a more complex type could also be created by adding the instances of LibrarySection to the same type.

You can download the complete source code from here : Composite Structural Pattern Source Code

Friday, October 05, 2007

* Patterns : Bridge Structural Pattern

Bridge Structural Pattern decouples an abstraction from its implementation so that the two can vary independently. Multiple variants of abstraction can be created provided they implement the common interface. Similarly, multiple variants of implementations can be created provided they implement the common interface. Given the option of multiple abstraction variants and multiple implementation variants, clients have the flexibility of using any abstraction class with any implementation.

Consider the class diagram below :

 

Bridge

There is one variant of abstraction called AbstractionX and two variants of implementation ImplementationA and ImplementationB.

The client code looks like following :

public class Client
{
    AbstractionBase absBase;
    public void Run()
    {
        ImplementationA implA = new ImplementationA();
        ImplementationB implB = new ImplementationB();

        absBase = new AbstractionBase(implA);
        absBase.PrintString("Hello\n\r");
        absBase = new AbstractionBase(implB);
        absBase.PrintString("Hello\n\r");

        AbstractionX absX = new AbstractionX(implB);
        absX.PrintString("Hello\n\r");
    }
}

Client code shows that same abstraction can be used with multiple implementations and similarly same implementation can be used with multiple abstractions.

Download complete source code : Bridge Structural Pattern source code

Wednesday, October 03, 2007

* Patterns : Adapter Structural Pattern

Adapter pattern also called as Wrapper pattern lets client adapt a framework/service with different call definitions than what client has been designed for. Clients continue using the original definitions and adapter takes care of transformation.

Consider the class diagram below :

Adapter

Client calls the ClientBase class which is client's default framework. Now Client is supposed to use FrameworkBase which has Print method instead of PrintString method. Now instead of changing the client, an Adapter class is created which take care of transforming the method calls.

Provided the methods in ClientBase are virtual, Adapter class can use ClientBase class as base class to provide the transformation functionality.

public class Adapter : ClientBase
{
    private FrameworkBase frmkBase;

    public Adapter()
    {
        frmkBase = new FrameworkBase();
    }

    public override void PrintString(string str)
    {
        frmkBase.Print(str);
    }
}

The client can make calls in same way just by making sure that instance of Adapter class is used.

public class Client
{
    ClientBase cb1, cb2;
    public void Run()
    {
        cb1 = new ClientBase();
        cb2 = new Adapter();
        cb1.PrintString("Hello");
        cb2.PrintString("Hello");
    }
}

Download full source code from here : Adapter Structural Pattern

Friday, September 28, 2007

* Singleton Creational Pattern

One of the most popular creational pattern. It is used to restrict the number of instances of a type to one and so all clients use the same instance.

Consider the following class diagram :

Client creates two variables of type Singleton, s1 and s2. 

The client code looks like following :

    public class Client
{
Singleton s1,s2;
public void Run()
{
// s1 = new Singleton(); // new cannot be called.
s1 = Singleton.GetInstance();
s1.ID = 999;
s2 = Singleton.GetInstance();
Console.WriteLine("ID = " + s2.ID);
}
}

The output of s2.ID is '999' which shows that both s1 and s2 are referring to same instance of Singleton. Also note that default constructor has been protected.


The code for actual 'Singleton' class looks like following :

    public class Singleton
{
public int ID;
private static Singleton Instance;

// Constructor is protected so that new cannot be called.
protected Singleton()
{
}

/// <returns>Singleton</returns>
public static Singleton GetInstance()
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}
Download full source code from here : Singleton Creational Pattern Source Code

Monday, September 24, 2007

* Patterns : Prototype Creational Pattern

Prototype Creational Pattern provides an interface which can be used by client to get access to already existing instance of a type which can be used as prototype by client to create new instance. Client can clone the existing object using deep or shallow copy and use it. It is used mainly when inherent cost of creating a new object is high.

Consider the following class diagram :

Above scenario goes like this :

Client needs the updated list of managers. ListAdmin can provide the list but its not latest. Now, client instead of creating the list from scratch which can be very resource consuming, picks the list from ListAdmin, creates a shallow copy of it and updates it for further use.

    public class Client
{
public static void Run()
{
ManagersList managersList = ListAdmin.getManagersList();
Console.WriteLine("Printing managersList ....");
DisplayList(managersList);
ManagersList list = (ManagersList)managersList.Clone(); // Creates a shallow copy
list.managers.Add("D_Manager1");
list.id = 2;
Console.WriteLine("Printing list ....");
DisplayList(list);
Console.WriteLine("Printing managersList again....");
DisplayList(managersList);
}

private static void DisplayList(ManagersList list)
{
Console.WriteLine("ID = " + list.id);
for(int i=0;i<list.managers.Count;i++)
{
Console.WriteLine(list.managers[i]);
}

}
}

The above client code output will be following :


Printing managersList ....
ID = 1
B_Manager1
A_Manager1
C_Manager1
Printing list ....
ID = 2
B_Manager1
A_Manager1
C_Manager1
D_Manager1
Printing managersList again....
ID = 1
B_Manager1
A_Manager1
C_Manager1
D_Manager1

Download full source code from here : Prototype Creational Pattern

* Patterns : Factory Method Creational Pattern

It provides an interface for creating an object but lets subclass decide which class to instantiates. So, it can also be called as virtual constructor.

Consider the following class diagram :

ShapeCreator class provides an factory method to create objects of BaseShape. Client always uses ShapeCreator and BaseShape type variables to work on instances of derives classes.

The client looks like following :

    public class Client
{
ShapeCreator createsShape;
public void Run()
{
BaseShape shape;
createsShape = new CircleCreator();
shape = createsShape.CreateShape();
shape.WhoAmI();
}
}

The code of CircleCreator looks like following :

    public class CircleCreator : ShapeCreator
{
public override BaseShape CreateShape()
{
return new CircleShape();
}
}

The CircleCreator decides which class to instantiate in response to CreateShape() method.


Download full source code from here : Factory Method Creational Pattern

Friday, September 21, 2007

* Patterns : Builder Creational Pattern

Builder Creational Pattern separates the process of construction of a complex object from its actual representation. This means that the same process can create different representations of same object.

Consider the following diagram :

The main class here is ShapeCreator which is called Director and controls the process of construction of object. 

    // Director
public class ShapeCreator
{
public void CreateSquare(SquareBuilder sb)
{
sb.Create();
sb.SetColor();
}
}

While Square is the actual object. RedSquareBuilder controls the actual representation of the object.


Consider the following client code :

    public class Client
{
ShapeCreator d;
public void Run()
{
d = new ShapeCreator(); //Director
SquareBuilder sb = new RedSquareBuilder();
d.CreateSquare(sb);
Square sq;
sq = sb.GetSquare();
Console.WriteLine(sq.Color + " Color Square created");
}
}

Just by changing the instance value of SquareBuilder, another representation of Square can be created by ShapeCreator.


Download full source code from here : Builder Creational Pattern source code

Thursday, September 20, 2007

* Pattern : Abstract Factory Creational Pattern

Provides a single interface for creating families of related or dependent objects without using the concrete type name.

Consider the following class diagram :

In above diagram, CreateShapes acts as an single interface for creating various families of products. The diagram shows only Red shapes but it can be extended to create more color shapes.

The client code will look like this :

    public class Client
{
CreateShapes redShapes;

public void Run()
{
redShapes = new CreateRedShapes();
redShapes.CreateCircle();
redShapes.CreateSquare();
}
}

Once the current instance has been assigned to variable of type CreateShapes, the remaining code remains same for every family.


A practical use can be creating shapes for a particular theme.


The complete source code can be downloaded from following location : Abstract Factory Creational Pattern Source Code

Tuesday, August 21, 2007

* CSharp 3.0 Language Specification released

CSharp Team @ Microsoft has released the specification document of CSharp 3.0. Its a comprehensive document and covers all earlier versions also.

It includes LINQ too.

Download CSharp 3.0 Spec doc

What's new in CSharp 3.0

Thursday, May 17, 2007

* C# 3.0 New Features : All LINQ(K)ED in one

In my previous post i attended the summary of new csharp 3.0 features.

Although all the new CSharp 3.0  can be used independently of LINQ but it seems most of them have been introduced to support LINQ and make it simpler.

Here is LINQ sample which demonstrates the use of most important of them :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AllCsharp3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> words = new List<string> { "Word1", "World", "Word2", "Word3", "World4" }; //Collection Initializer
            var wordQuery =  // Implicitly Typed Local Variables
            from word in words
            where word == "World"
            select new{word};  //Anonymous Types
            foreach (var name in wordQuery)
            {
                Console.WriteLine("-> Hello " + name.word);
                Console.WriteLine("-> Hello " + name.word.ToString().GetFirst3Chars());
            }
        }
    }

    public static class MyExtensions  
    {
        public static string GetFirst3Chars(this System.String str)  //Extension Methods
        {
            return str.Substring(0, 3);
        }
    }
}

Other Posts