Wednesday, December 26, 2007

*Your life - your likes - you decide!!!*

A long time ago, there was an Emperor who told his horseman that if he could ride on his horse and cover as much land area as he likes, then the Emperor would give him the area of land he has covered.
Sure enough, the horseman quickly jumped onto his horse and rode as fast as possible to cover as much land area as he could. He kept on riding and riding, whipping the horse to go as fast as possible. When he was hungry or tired, he did not stop because he wanted to cover as much area as possible.
Came to a point when he had covered a substantial area and he was exhausted and was dying. Then he asked himself, "Why did I push myself so hard to cover so much land area? Now I am dying and I only need a very small area to bury myself."

The above story is similar with the journey of our Life. We push very hard everyday to make more money, to gain power and recognition. We neglect our health , time with our family and to appreciate the surrounding beauty and the hobbies we love.
One day when we look back , we will realize that we don't really need that much, but then we cannot turn back time for what we have missed.

Life is not about making money, acquiring power or recognition . Life is definitely not about work! Work is only necessary to keep us living so as to enjoy the beauty and pleasures of life. Life is a balance of Work and Play , Family and Personal time . You have to decide how you want to balance your Life.

Define your priorities, realize what you are able to compromise but always let some of your decisions be based on your instincts. Happiness is the meaning and the purpose of Life, the whole aim of human existence.So, take it easy, do what you want to do and appreciate nature. Life is fragile, Life is short. Do not take Life for granted. Live a balanced lifestyle and enjoy Life!

Adding the single quotes into sql server statements...

Hi,

Yesterday one of my junior came to me and ask a simple question :

How to add the single quotes into sql server statements ?????

lets say I want to update an existing record. The sql for it is below:
update sampletable set field='data' where id='#'
ok, very simple . Now what if the data includes a single quote in it? Something like “vishal’s store”.

the resulting sql query looks like this:
update tblLocation set Loc_Name='Vishal's Store' where id='Vishal25648'
this will generate errors in the sql statement, because after the single quote is encountered the sql parser looks for a where clause.

Any ideas of how to get around this? And special character codes in sql for single quote?

Although this is a simple issue but many of novices are still unaware and tried the backslashes and all to get it done.

But the answer is as simple as the question J

The answer is this:
update tblLocation set Loc_Name='Vishal''s Store' where id='Vishal25648'
All you need is to add 1 (one) extra single quote before the intended single quote. Sounds simple isn’t it.
Note: this answer is specific to sql server 2000. The syntax might be different for oracle, sybase, or others.

Friday, December 14, 2007

What is the Difference Between Build and Re-Build in visual Studio .Net?

Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.

Wednesday, December 12, 2007

Determine if a credit card number is valid using VB (Luhn Check)

If you support a Web site that accepts online payments, the first step in any process that accepts credit card numbers should be verifying the number. This tip shows how to do this using VB.

Credit card numbers are not assigned at random. Each number, usually 16 digits long, must adhere to certain mathematical conditions to be valid. This is called the Luhn Check, and it is used by almost all major cards. If you support a Web site that accepts online payments, the first step in any process that accepts credit card numbers should be verifying the number. This tip shows how you can do this using VB.

Using VB, the credit card number is passed, as a string, to the function CCNumberValid.
The string must contain only digits—no embedded spaces or dashes. The function returns
True if the number is valid and False if not.

Public Function CCNumberValid(ByValCCNumber As String) As Boolean
Dim Result As Long
Dim Total As Long
Dim idx As Integer
Dim i As Integer
Dim j As Integer
j = 1
For i = Len(CCNumber) To 1 Step -1
Result = (CInt(Mid$(CCNumber, i, 1)) * j)

If Result >= 10 Then
Total = Total + (CInt(Mid$(CStr(Result), 1, 1)) _
+ CInt(Mid$(CStr(Result), 2, 1)))
Else
Total = Total +
Result
End If

If j = 2 Then j = 1 Else j = 2
Next

If Total Mod 10 = 0 Then
CCNumberValid = True
Else
CCNumberValid = False
End If


End Function

The fact that a credit card number is valid does not mean that it is actually assigned to an account or that the account is in good standing. But checking the validity of a number is the best and fastest way to weed out errors in number entry.

C# Remoting with a simple example

Remoting is an infrastructure that allows the developer to use remote objects. Remote objects are objects that are based (or instantiated) outside of the caller's Application Domain or in other words we can say Remoting is a framework built into Common Language Runtime (CLR) in order to provide developers classes to build distributed applications and wide range of network services. Remoting provides various features such as Object Passing, Proxy Objects, Activation, Stateless and Stateful Object, Lease Based LifeTime and Hosting of Objects in IIS.
Here I’m presenting a simple client/server based application in order to provide you easy and fast hands on Remoting.
Problem statement:
TicketServer holds information about the ticket status of a movie theater. A client needs to know the status of a ticket. Establish a connection between the client and the server so that client gets the information needed.
Solution:
A method called GetTicketStatus is defined in the server space. This method returns the status of the ticket. The server publishes this method which can be used by any client. The server listens to port 9998 over TCP. The client invokes the published method and gets the ticket status.
Implementation:
An interface MovieTicketInterface is defined which contains the GetMovieTicket method signature. This interface is implemented by MovieTicket class. The method GetMovieTicket is also implemented.
The server TicketServer registers the MovieTicket class as a remoting service. It listens to the port 9998 and waits for communication from any client.
The client creates an object of type MovieTicketInterface as a remoting object. As a part of this step, the communication between the server and the client over TCP on port number 9998 is established. It then invokes the method GetTicketStatus and gets the status.
Source code:

Server part:
1. Create a Console Application named TicketServer.
2. Add System.Runtime.Remoting as a reference to the project.
3. Replace the existing code in Class.cs with the following code and build the project.

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
static void Main(string[] args)
{ TicketServer();
}
static void TicketServer()
{ Console.WriteLine("Ticket Server started...");
TcpChannel tcpChannel = new TcpChannel(9998); ChannelServices.RegisterChannel(tcpChannel); Type commonInterfaceType = Type.GetType("MovieTicket"); RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType, "MovieTicketBooking", WellKnownObjectMode.SingleCall); System.Console.WriteLine("Press ENTER for quiting"); System.Console.ReadLine();
}
}

public interface MovieTicketInterface
{
string GetTicketStatus(string stringToPrint);
}
public class MovieTicket : MarshalByRefObject, MovieTicketInterface
{
public string GetTicketStatus(string stringToPrint)
{
string returnStatus = "Ticket Confirmed"; Console.WriteLine("Enquiry for {0}", stringToPrint);
Console.WriteLine("Sending back status: {0}", returnStatus); return returnStatus;
}
}

Client side:

1. Create a Console Application named Client.

2. Add System.Runtime.Remoting and Server.exe [See Note 1] as references to the project.

3. Replace the existing code in Class.cs with the following code and build the project.

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
class MyClient
{
public static void Main()
{
TcpChannel tcpChannel = new TcpChannel();
ChannelServices.RegisterChannel(tcpChannel); Type requiredType = typeof(MovieTicketInterface); MovieTicketInterface remoteObject = (MovieTicketInterface)Activator.GetObject(requiredType, "tcp://localhost:9998/MovieTicketBooking");

Console.WriteLine(remoteObject.GetTicketStatus("Ticket No: 3344"));
}
}
Execution:

1. Execute Server.exe

2. Execute Client.exe

You will see the appropriate messages on the client side and the remote side.

Note 1: If you are using Visual Studio 2003, you cannot add a reference to an exe file. Make a copy of Server.exe, rename it to Server.dll and this can be added as a reference in your client project.

Note 2: If you are using Visual Studio 2003, and you are getting error The type or namespace name> 'Tcp' does not exist in the class or namespace 'System.Runtime.Remoting.Channels' (are you missing an assembly> reference) then do remember that the "using" statements are merely a convenience to eliminate typing long namespace strings, they do not pull in the requisite assemblies. You must add the assembly reference of System.Runtime.Remoting by going to the Project menu and choosing Add Reference.

Thursday, December 6, 2007

Chain of Responsbility design pattern

Hi all,

I got a good article on Chain of Responsbility design pattern from here. the extract of it as ::::::

Introduction
A powerful design pattern geared towards handling an event is the Chain of Responsbility design pattern. This pattern helps decouple related algorithms in C# ASP .NET and can help your software become more scalable and easier to control.

In general, the Chain of Responsbility design pattern allows you to link together a serious of classes or algorithms in a hierarchy and pass a command (preferably a Command pattern object) into the mix to get handled by one of the members of the chain. One of the benefits of this design pattern is, not having to know the details of the members in the chain. You simply pass the command into the chain. Each class will attempt to handle the request until all classes have been used. While it is possible for a request to go unhandled, this is a powerful design pattern when used appropriately.

Two Ways to Make a Chain
As with all first programming examples, the Hello World example is a good introduction to an implementation of the Chain of Responsbility design pattern in C# ASP .NET. However, first let's take a look at the standard way of handling a request without using the Chain of Responsbility.

Standard Method of Handling a Request

void main()
{
Command MyRequest = new Command();
if (Handler1(MyRequest) == true)
{
return;
}
else if (Handler2(MyRequest) == true)
{
return;
}
else if (Handler3(MyRequest) == true)
{
return;
}
}

As you can see in the above example, to handle MyRequest we pass it to each Handler function that we've defined. There are several drawbacks to this simplistic method, especially in an object oriented language such as C# .NET. Foremost, there are many conditionals which create confusion when reading the code. This can especially become a problem when performing team development and debugging. More importantly, detailed knowledge of the handler implementations are required since they are listed within the conditional.
The above example can be enhanced with a Chain of Responsbility as shown in the following example:

void main()
{
Command MyRequest = new Command();
Handler MyHandler1 = new Handler1();
Handler MyHandler2 = new Handler2();
Handler MyHandler3 = new Handler3();

MyHandler1.SetSuccessor(MyHandler2);
MyHandler2.SetSuccessor(MyHandler3);

MyHandler1.HandleRequest(MyRequest);
}

In this example, we have implemented a Chain of Responsiblity design pattern with C# ASP .NET which handles the request. After setting up the initial chain, we only need to pass MyRequest to the first handler (which is of the generic type 'Handler'). Knowledge of which handler gets called next is preserved within the chain itself.

Say Hello to the Chain
By following the above example for implementing a Chain of Responsibility, we can apply it to create a simple Hello World example as shown in the following code.

static void Main(string[] args)
{
Handler MyEnglishHandler = new EnglishHandler();
Handler MyFrenchHandler = new FrenchHandler();
Handler MySpanishHandler = new SpanishHandler();
// Setup the chain of responsibility.
MyEnglishHandler.SetSuccessor(MyFrenchHandler);
MyFrenchHandler.SetSuccessor(MySpanishHandler);
// Throw the first handler a request and then throw two more for fun.
MyEnglishHandler.HandleRequest("en-US Hello World");
MyEnglishHandler.HandleRequest("es-US Hola Mundo");
MyEnglishHandler.HandleRequest("fr-FR Bonjour Monde");
Console.ReadKey();
}

Output:
Handled by EnglishHandler: Hello World
Dirigido por SpanishHandler: Hola Mundo
Manipule pres FrenchHandler: Bonjour Monde

Notice that there will be three handlers, an English, a French, and a Spanish handler. The command request will consist of two parts: a culture indicator and the text to display. For this example, a simple string was used in place of a Command design pattern. The culture indicator is just the first 5 characters of the string. Each handler will look at the culture indicator to determine whether it should handle the printing of the text to the console. If the handler can not handle the command, it passes it to the next handler in the chain, until all handlers have been ran.

To get to the meat of the Chain of Responsibility, we need to define the generic class that our Handlers will inherit from.
The Handler Class
We have chosen to use an abstract class in place of an interface for implementing the generic Handler class. This is due to the fact that our Handler class will implement the body of one of the functions as well as define a protected member. Also note that abstract classes, in general, perform faster than interfaces due to less memory lookups.

abstract class Handler
{
protected Handler successor;
public Handler()
{
}

public void SetSuccessor(Handler aSuccessor)
{
successor = aSuccessor;
}
public abstract void HandleRequest(string strRequest);
}

This Handler definition is fairly simple. The most important part is the inclusion of a protected successor object, of type Handler. This allows a form of a linked list to implement our chain. We also implement a SetSuccessor function to assign the successor. The HandleRequest function will be required by all handlers to initiate a possible action.

Creating a Concrete Handler
Now that we have the abstract class Handler defined, we can now create some concrete handlers to create a complete Chain of Responsibility in C# ASP .NET. Our first handler will handle English strings by looking in the command for the culture identifier "en-us".

The EnglishHandler Class
class EnglishHandler : Handler
{
private const string LANGUAGE_TAG = "en-us";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
Console.WriteLine("Handled by EnglishHandler:" + strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Notice our handler inherits from our abstract base class Handler and defines the required HandleRequest function. The body of the function simply checks the first 5 characters of the command string to see if it contains "en-us". If it does, the payload portion of the string is printed to the console, the command is deemed handled, and execution of the chain stops. If "en-us" is not found, the handler passes the command to the next handler in line. Of course, if no other handler exists, the command remains unhandled. Unhandled commands could be managed as well by including additional detection code.

We can create two more handlers to make the example more interesting, as follows.

The FrenchHandler Class

class FrenchHandler : Handler
{
private const string LANGUAGE_TAG = "fr-fr";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
strResponse = "Manipulé près FrenchHandler:" + strResponse;
Console.WriteLine(strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Note, the FrenchHandler differs only by the culture identifier that it is looking for and by the action performed on the payload. Just like the EnglishHandler, the FrenchHandler passes the command to the next in line if it fails to handle it. The FrenchHandler doesn't need to know the details about its successor, only that it's of type Handler.

The SpanishHandler Class

class SpanishHandler : Handler
{
private const string LANGUAGE_TAG = "es-us";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
Console.WriteLine("Dirigido por SpanishHandler:" + strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Now that we have created 3 handlers, our original main code can be executed. We begin by defining three handlers of each concrete handler type. We then setup the chain in our desired order. Typically, order doesn't matter since each handler will have a chance at the request. However, speed issues may arise where order becomes critical. Finally, we send a request to the first member of the chain and the Chain of Responsibility handles the rest. Notice in the main program above that we execute 3 requests. Each one will be handled by one of the concrete handlers.

// Throw the first one a request.
MyEnglishHandler.HandleRequest("en-US Hello World");
MyEnglishHandler.HandleRequest("es-US Hola Mundo");
MyEnglishHandler.HandleRequest("fr-FR Bonjour Monde");

Since the concrete handlers inherit from the generic Handler class, they have no need to know the concrete details about their successors. This allows us to implement new concrete handlers (for other languages, for example), and insert them anywhere in the chain.

What about C# Multicast Delegates?
C# delegates can be a form of a chain of responsiblity in themselves. By creating a delegate and assigning it multiple functions for execution, a multicast delgate is created and may be used in a similar fashion to a chain of responsibility design pattern. When the delegate is invoked, each function added to the multicast delgate's chain is executed. Where a typical chain of responsiblity pattern will only continue executing handlers until one succeeds, the multicast delegate will always execute each handler. For example:

delegate void MyMulticastDelegate(int x, int y);
void main()
{
MyMulticastDelegate MyFunction = new MyMulticastDelegate(MyFunc1);
MyFunction += new MyMulticastDelegate(MyFucn2);
// Calling MyFunction will execute MyFunc1 and MyFunc2 in a chain.
MyFunction(10, 20);
}
static public void MyFunc1(int x, int y)
{
Console.WriteLine("MyFunc1");
}

static public void MyFunc2(int x, int y)
{
Console.WriteLine("MyFunc2");
}
Conclusion

The Chain of Responsibility design pattern helps you create more scalable and reusable code in C# ASP .NET. By defining concrete handlers inidividually, you help decouple algorithms into separate and reusable classes. A request can be passed to the first handler and executed by any member of the chain, regardless of whether those handlers, or their concrete types, are known beforehand. C# .NET provides mutlicast delegates which may be considered a form of a chain of responsibility. Developers can take advantage of multicast delegates to perform event and callback functionality or design their own chain of responsiblity pattern with C# ASP .NET.

PROTOTYPE PATTERN

The PROTOTYPE PATTERN comes under the classification of Creational Patterns. The creational patterns deals with the best way to create objects. This helps to copy or clone the existing objects to create new ones rather than creating from the scratch.

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. -- "Design Patterns" Gamma et al., Addison-Wesley, ISBN:0-201-63361-2"

The prototype pattern is used when creating an instance of a class is very time consuming or complex in some way. Then rather than creating more instances, it is possible to make copies of the original instances and modifying them as appropriate.

When we are not in a position to call a constructor for an object directly, we could alternatively clone a pre-existing object (a prototype) of the same class. When there are many subclasses that differ only in the kind of objects they create a Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype. Prototype Design Pattern helps in reducing number of classes.

For example suppose we have to do say Sales Analysis on a set of data in the database. Normally we will create an object encapsulating this data and do the Sales Analysis. Suppose now we have to do another type of analysis say Promotion Analysis on the same data. Now instead of creating another object corresponds to the data from the scratch, we can clone the existing object and do the analysis. This is one of the classical use of prototype pattern.

Remember that in C#, this pattern can be implemented easily by using the clone(). Any class, which wants to support cloning, should inherit from the ICloneable interface in C#. ICloneable interface contains a Clone() method which we can override in our class. Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.
The resulting clone must be of the same type as or a compatible type to the original instance.

sample code in C#

This real-world code demonstrates the Prototype pattern in which new Color objects are created by copying pre-existing, user-defined Colors of the same type.

using System;
using System.Collections;
namespace PrototypePattern
{
// MainApp test application
class MainApp
{
static void Main()
{
ColorManager colormanager = new ColorManager();
// Initialize with standard colors
colormanager["red" ] = new Color(255, 0, 0);
colormanager["green"] = new Color( 0, 255, 0);
colormanager["blue" ] = new Color( 0, 0, 255);
// User adds personalized colors
colormanager["angry"] = new Color(255, 54, 0);
colormanager["peace"] = new Color(128, 211, 128);
colormanager["flame"] = new Color(211, 34, 20);
Color color;
// User uses selected colors
string name = "red";
color = colormanager[name].Clone() as Color;
name = "peace";
color = colormanager[name].Clone() as Color;
name = "flame";
color = colormanager[name].Clone() as Color;
// Wait for user
Console.Read();
}
}
// "Prototype"
abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
// "ConcretePrototype"
class Color : ColorPrototype
{
private int red;
private int green;
private int blue;
// Constructor
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
// Create a shallow copy
public override
ColorPrototype Clone()
{
Console.WriteLine("Cloning color RGB: {0,3},{1,3},{2,3}",red, green, blue);
return this.MemberwiseClone() as ColorPrototype;
}
}
// Prototype manager
class ColorManager
{
Hashtable colors = new Hashtable();
// Indexer
public ColorPrototype this[string name]
{
get
{
return colors[name] as ColorPrototype;
}

set
{
colors.Add(name, value);
}
}
}
}


Output




Builder Pattern

Suppose you had a series of objects that needed constructed, but your application needs to specialize how they are built. This is where the builder pattern comes into play. It handles performing the building of the necessary objects (also referred as the "product"); the builder class has that sole responsibility. The builder class also supports inheritance, which the product that the builder creates is usually involved in the inheritance scheme, meaning that the derived builder objects are actually building their related product object.

The builder pattern has a director that oversees the build process. The director has a reference to the builder(s) available and is responsible for invoking the correct method(s) in the builder. The builder has a common interface that all builders derive from and that the director knows about, and because of this, it can easily do its job. Inheritance plays a key, as the builder's interface is abstract, and the derived builder classes actually do the work of building an object. The resulting class that it builds can make use of inheritance to provide a more specific implementation. The builder class would be responsible for invoking the correct object.

It is possible that the builder/director relationship be dynamically created through the use of a configuration file, though that adds a lot of work to the software development process. More simplistically and realistically, this relationship is statically created through a constructor or an initialization method.

Non-software Example
Fast food restaurants to construct children's meals use this pattern. Children's meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy car). Note that there can be variation in the content of the children's meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

Another example for Builder pattern is a Computer Assembly. A computer is nothing but the bundling of various components like FDD, HDD, Monitor etc. But when an user buys a computer someone assemble all these components and given to us. Remember that here the building process is completely hidden from the client or user.

Remember that a project can contain one or more builders and each builder is independent of others. This will improves the modularity and makes the addition of other builders relatively simple. Since each builder constructs the final product step by step, we have more control over the final product that a builder constructs.

C# implementation
This real-world code demonstates the Builder pattern in which different vehicles are assembled in a step-by-step fashion. The Shop uses VehicleBuilders to construct a variety of Vehicles in a series of sequential steps.

using System;
using System.Collections;

namespace BuilderPattern{
// MainApp test application
public class MainApp
{
public static void Main()
{
// Create shop with vehicle builders
Shop shop = new Shop();
VehicleBuilder b1 =
new ScooterBuilder();
VehicleBuilder b2 =
new CarBuilder();
VehicleBuilder b3 =
new MotorCycleBuilder();
// Construct and display vehicles
shop.Construct(b1);
b1.Vehicle.Show();

shop.Construct(b2);
b2.Vehicle.Show();

shop.Construct(b3);
b3.Vehicle.Show();
// Wait for user
Console.Read();
}
}
// "Director"

class Shop
{
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
vehicleBuilder.BuildFrame();
vehicleBuilder.BuildEngine();
vehicleBuilder.BuildWheels();
vehicleBuilder.BuildDoors();
}
}

// "Builder"

abstract class VehicleBuilder
{
protected Vehicle vehicle;

// Property
public Vehicle Vehicle
{
get{ return vehicle; }
}

public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}

// "ConcreteBuilder1"

class MotorCycleBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("MotorCycle");
vehicle["frame"] = "MotorCycle Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "500 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "2";
}

public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}

// "ConcreteBuilder2"

class CarBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("Car");
vehicle["frame"] = "Car Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "2500 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "4";
}

public override void BuildDoors()
{
vehicle["doors"] = "4";
}
}

// "ConcreteBuilder3"

class ScooterBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("Scooter");
vehicle["frame"] = "Scooter Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "50 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "2";
}

public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}

// "Product"

class Vehicle
{
private string type;
private Hashtable parts = new Hashtable();

// Constructor
public Vehicle(string type)
{
this.type = type;
}

// Indexer (i.e. smart array)
public object this[string key]
{
get{ return parts[key]; }
set{ parts[key] = value; }
}

public void Show()
{
Console.WriteLine("\n---------------------------");
Console.WriteLine("Vehicle Type: {0}", type);
Console.WriteLine(" Frame : {0}", parts["frame"]);
Console.WriteLine(" Engine : {0}", parts["engine"]);
Console.WriteLine(" #Wheels: {0}", parts["wheels"]);
Console.WriteLine(" #Doors : {0}", parts["doors"]);
}
}
Output

Non-Software Examples of Software Design Patterns

Hi all,

Today while browsing on the net Guess what I Got :::::
Something that let you grasp an idea of Software Design Patterns in a really simple and close to real world manner.

Follow the link and enjoy …………………

Non-Software Examples of Software Design Patterns by Michael Duell

Isn’t it really simple ..

Wednesday, December 5, 2007

The adapter pattern

The adapter pattern is easy to implement and makes it easier to connect to external data stores of varying types. It does not matter how the interfaces vary; you can easily create a common interface using the adapter pattern.
Using the adapter pattern makes interfacing with a variety of differing applications much easier. This pattern is especially useful when an application must connect to multiple external applications that differ in their requirements.
With a myriad of API's available in business systems, programs (like Microsoft Word), web services, etc., there are many different interfaces a developer has to understand to tie them all together into one business solution that he or she may be developing. For instance, maybe an application needs to connect to credit card service gateways to verify a customer's credit limit or to run a debit against the account. An application could connect to a health insurance provider to bill them for services provided. An application could display maps from varying map providers.

One thing that is certain with tying in various business systems is that the API's a developer uses will be different. There is not any standard interface across the industry for implementing a certain type of system, but there is good reason for you to want to do so. Uniformity in application development makes maintenance and documentation easier and makes the application design better.
However, with these varying systems, how can one tie together all of these interfaces into one common one? This is where the adapter pattern comes into play.


A very nice example I found here

Monday, December 3, 2007

Further Reading - Singleton Pattern

Further Reading

Please refer to the following links for more related information:

http://www.dofactory.com/Patterns/PatternSingleton.aspx
http://www.yoda.arachsys.com/csharp/singleton.html
http://aspalliance.com/810_Implementing_a_Singleton_Pattern_in_C

Implementing the Singleton Pattern in C#

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.
All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.
First version - not thread-safe
// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.

· One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.

The content was originally posted at http://www.yoda.arachsys.com/csharp/singleton.html I copied it here just in case i the post disappears. My due regards to the original writers.

The Singleton pattern has several benefits:
1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, itcan have strict control over how and when clients access it.
2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.
3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.
5. More flexible than class operations. Another way to package a singleton's functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically.