Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for January, 2012

eBook on Design Patterns

Posted by JP on January 27, 2012

I am very much happy to compile my second eBook: Design Patterns in C#. It was a dedicated learning effort of past 1 year and I very much enjoyed the patterns. I believe Design Patterns will give good designing edges to the developers and enhance their Object Oriented skills.

Download eBook
You can download the eBook from Amazon here. (Formatted for Kindle, you can read it on your computer without Kindle Device)

Download Source Code (Visual Studio 2010)
You can download the source code for the examples here

Download Source Code (Visual Studio 2012)
You can download the source code for the examples here

Feedback
Please feel free to provide me comments or suggestions on improvements about this ebook.

Advertisements

Posted in C#, Design Patterns | Tagged: | 30 Comments »

Composite Pattern

Posted by JP on January 26, 2012

This is my last article on the 23 Design Patterns series.  I would like to thank all readers for their support and encouragements that made learn all the design patterns.

In this article we can explore the Composite Design Pattern. It provides a better approach in addressing communication with individual and group of objects. As usual we can start with the Challenge – Solution approach.

Challenge

You are working on a distributed application containing Head Office and Branch Offices. Each office will be having 2 Clock Controls which needed to be updated globally during Daylight Saving times.

clip_image002

The above diagram shows the current structure. There will be only 1 Head Office and multiple branches under it. The head office and each branch will be having 2 clock controls. The time changing process starts from the head office and in the current approach, the head office has to remember all branches and all clocks inside each branch. This is very tedious and will break when there is consolidation of branches under one branch group.

How to provide a better solution?

Definition

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly

Implementation

We can use the Composite Design Pattern in the above scenario. Once our solution is implemented the Head Office needs to think about only the Branches. The Branches will think about their respective Clocks.

There are 2 classes in our solution: Office and Clock. The Office class can represent Head Office and Branches. The Clock class manages the clock control for changing time.

We need to introduce one interface which will be implemented by the Office and Clock classes.

interface IComponent

{

void Add (IComponent notifier);

void SetTime(DateTime time);

}

The Add() method ensures adding a component of type IComponent. It can be used to add an Office or Clock instance.

The SetTime() method can be used to change the current time.

Class Implementations

Following are the implementations of the Office and Clock classes:

class Office : IComponent

{

private IList<IComponent> _list = new List<IComponent>();

public void Add(IComponent notifier)

{

_list.Add(notifier);

}

public void SetTime(DateTime time)

{

foreach (IComponent n in _list)

n.SetTime(time);

}

}

class Clock : IComponent

{

public ClockControl ClockControl;

public void Add(IComponent notifier)

{

throw new ApplicationException(“You cannot add IClock!”);

}

public void SetTime(DateTime time)

{

ClockControl.CurrentTime = time;

}

}

Please note that the SetTime() implementation of Office class takes care of informing all the added IComponent instances. Thus the Head Office can notify all the branches. The branches will notify all the clock instances.

Creating Instances

Following is the code of instance creation for Head Office and Branches.

_headOffice = new Office();

_headOffice.Add(new Clock() { ClockControl = hForm.clock1 });

_headOffice.Add(new Clock() { ClockControl = hForm.clock2 });

Office branch1 = new Office();

branch1.Add(new Clock() { ClockControl = b1Form.clock1 });

branch1.Add(new Clock() { ClockControl = b1Form.clock2 });

_headOffice.Add(branch1);

Office branch2 = new Office();

branch2.Add(new Clock() { ClockControl = b2Form.clock1 });

branch2.Add(new Clock() { ClockControl = b2Form.clock2 });

_headOffice.Add(branch2);

Please note that the branch instances are added to the head office.

Running the Application

On clicking the Set Time button you can see all the clocks are reset to 10:00 AM.

clip_image004

Here the Head Office does not need to think about all the clock instances of branches. Here the individual objects (clocks) and composite objects (branches) are treated uniformly satisfying the pattern definition.

Summary

In this article we have explored the Composite Pattern. It provides a centralized approach in talking with individual and combined objects. The attachment contains the example application including the clock control we have discussed.

Posted in C# | Tagged: | 1 Comment »

Bridge Pattern

Posted by JP on January 25, 2012

In this article we can explore the Bridge pattern which is commonly used in applications.

Challenge

You are working on an abstract business class. The class needs to log information to by writing to a file, email to user etc. We need to avoid tightly coupling of the business class and logger as in future newer versions of logger might appear.

clip_image002

How to achieve a decoupled solution?

Definition

Decouple an abstraction from its implementation so that the two can vary independently

Implementation

We can create an abstract class for representing the Logger. Let the abstract business class hold reference to the new abstract Logger. In the runtime we can specify the actual implementation instance of Logger class. (File writer or Emailer)

Following is the snapshot of the class diagram after using the Bridge Pattern:

clip_image004

Here the concrete Logger implementations derive from AbstractLogger class.

The concreate TransactionBL derives from AbstractBL class. The AbstractBL class is holding reference to Logger (abstract Logger).

Using the Bridge Pattern as shown above, there is decoupling of the implementation from its abstraction. It allows future extensibility to the Logger classes without modifying the BL class.

Code

Following is the code that invokes above Transaction and Logger classes.

AbstractBL bl = new TransactionBL();

bl.Logger = new TextFileLogger();

bl.ProcessPayment();

bl.Logger = new EmailLogger();

bl.ProcessPayment();

Console.ReadKey(false);

On running the application we can see the following output.

clip_image006

Following is the coupling snapshot after using the Bridge Pattern.

clip_image008

Note

We can see that this pattern is a simple implementation using an abstract class and interface. The Bridge Pattern is having some similarity with Strategy Pattern as both involve changing the implementation in the runtime. Here the class is abstract when compared with Strategy pattern.

Summary

In this article we have explored the Bridge design pattern. It provides convenient way for separating the abstraction from implementation through a bridge of abstract class or interface. The attached source code contains the example we discussed.

Posted in C# | Tagged: | Leave a Comment »

Interpreter Pattern

Posted by JP on January 20, 2012

In this article I would like to demonstrate the usage of Interpreter pattern. This is not a widely used pattern but reveals a good way of programming. It says about creating a language along with an interpreter for the language. The language can be used to represent states, actions, loops etc. depending on the programming requirement. Here we are using the pattern to resolve a persistence problem.

Challenge

You are working on a Drawing application which allows creating lines and circles on a canvas. The classes Line and Circle do the job for you. You need to communicate the drawing with multiple users who have their own copy of the application. The current persistence of drawing using serialization of the above classes is creating large sized files and does not allow sending the message over a chat window.

How to provide a better solution for persistence with smaller size and easier communication?

Definition

“Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language”

Implementation

We can use the Interpreter pattern to approach the problem. We need to construct a language to include the commands and an interpreter to execute the actions.

clip_image002

Following are the classes involved for our drawing application:

  • A Line Class
  • A Circle Class
  • An Interpreter Class

The Line and Circle class includes the drawing functionality. The Interpreter class takes care of converting the commands to invoking of appropriate line or circle classes.

The Language

The language part could be constituted by a series of sentences. The sentence could be as following:

line,10,10,10,10

Line command stating x, y, width, height

circle,10,10,50

Circle command stating x, y, radius

Please note that the arguments are separated using comma (,).

The sentence could be separated using semicolon (;) as shown below.

line,60,60,50,0;line,110,110,50,0;

Executing the Application

We can enter the series of commands separated by semicolon (;). The commands are entered in the application.

clip_image004

Clicking Execute you can see the above drawings of lines and circles.

The body of the Interpreter Execute() method is given below:

public void Execute(string commands, Graphics graphics)

{

graphics.Clear(Color.FromArgb(237, 253, 200));

int i = 0;

foreach (string rawCommand in commands.Split(‘;’))

{

string command = rawCommand.Replace(Environment.NewLine, string.Empty).Trim();

if (command.StartsWith(“line”))

{

i = 0;

int x = 0, y = 0, width = 0, height = 0;

foreach (string argument in command.Split(‘,’))

{

if (i == 1)

x = int.Parse(argument);

else if (i == 2)

y = int.Parse(argument);

else if (i == 3)

width = int.Parse(argument);

else if (i == 4)

height = int.Parse(argument);

i++;

}

new Line(graphics).Draw(x, y, width, height);

}

else if (command.StartsWith(“circle”))

{

i = 0;

int x = 0, y = 0, radius = 0;

foreach (string argument in command.Split(‘,’))

{

if (i == 1)

x = int.Parse(argument);

else if (i == 2)

y = int.Parse(argument);

else if (i == 3)

radius = int.Parse(argument);

i++;

}

new Circle(graphics).Draw(x, y, radius);

}

}

}

Following is the class diagram:

clip_image006

This concludes our application using the Interpreter Pattern. Now the actions could be converted to a language for interpreting later.

Comparison of Command Pattern and Interpreter Pattern

You can find some similarities between the Command and Interpreter patterns. The command pattern says about converting the actions into command for logging or undo purposes. Here the commands are objects but for the Interpreter pattern the commands are sentences.

The Command pattern can be used for persisting objects by serializing the command list and results in large sized files compared with Interpreter pattern.

The Interpreter pattern provides an easier approach in the runtime but comes at the cost of developing and interpreter.

Applications of Interpreter Pattern

You are creating your own Photoshop application.  The objects drawn on the layer can be converted to a series of commands.  Later the entire drawing could be represented using the command file which will be small in size compared to the entire canvas serialized.  You will get the advantage of sending the file to another person where he/she can:

· Regenerate the Drawing

· View all the Draw Actions

· Modify the Draw Action Items

· Undo the last draw actions

References

http://www.dofactory.com/Patterns/PatternInterpreter.aspx#_self1

Summary

In this article we have seen about the Interpreter pattern with a small application using it. The above application shows only a simple usage for learning purpose but in the real world scenarios the language may include loops, conditions etc. The attachment contains the source code of application we have discussed.

Posted in C# | Tagged: | Leave a Comment »

Prototype Pattern

Posted by JP on January 13, 2012

In this article I would like to explain the Prototype Pattern and C# support for it. The prototype pattern provides an alternative to instantiating new objects by copying the prototype of an existing one.

Challenge

You are working on an application having setting stored in class Settings. The properties of the class are assignedinside the constructor. It involves calling the configuration file, security database, user profile database etc.

You need to pass the above instance to a component inside a library. The component could play around with the properties so we need to send only another instance of Settings. As the instance creation is expensive we need to create a copy of the above instance.

What would be the best approach?

Definition

“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype”

Solution

We can use the Prototype pattern to address this scenario. This pattern allows us to create a new instance by prototyping an existing instance with required properties.

clip_image002

The System.object class includes new method named MemberwiseClone() which provides a shallow copy of the current object. Shallow copy involves copying only the value types. Coupled with ICloneable interface we can provide a Clone() method that invokes MemberwiseClone() for the Settings class.

publicclassSettings : ICloneable

{

public Settings()

{

// Load ApplicationSettings from Configuration

// Load ThemeSettings from Database

// Load UserSettings from Database

Thread.Sleep(3000); // Simulate a delay for the above operations

ApplicationSettings = “ApplicationSettings1”;

ThemeSettings = “ThemeSettings1”;

UserSettings = “UserSettings1”;

}

publicstringApplicationSettings

{

get;

set;

}

publicstringThemeSettings

{

get;

set;

}

publicstringUserSettings

{

get;

set;

}

publicobject Clone()

{

returnthis.MemberwiseClone();

}

publicoverridestringToString()

{

returnthis.ApplicationSettings + ” ” +

this.ThemeSettings + ” ” +

this.UserSettings;

}

}

Executing the Application

Now we can try playing with the class instances. First we create an instance of Settings (which is a 3 second delay process). Later we take a clone of the Settings instance and modify the properties. We can see that the new instance was created using Clone() method.

staticvoid Main(string[] args)

{

Settingssettings = newSettings();

SettingssettingsClone = (Settings)settings.Clone();

settingsClone.ApplicationSettings = “NewSettings”; // Change property

Console.WriteLine(“INSTANCE 1: ” + settings.ToString());

Console.WriteLine(“INSTANCE 2: ” + settingsClone.ToString());

Console.ReadKey(false);

}

On executing the application we can see the following results.

clip_image004

We can see from the above code that:

1. Instance 1 was created using new keyword

2. Instance 2 was created using Clone() method

3. Changing of Instance 2 does not affect Instance 1

So this concludes our experiment with the Prototype pattern.

References

http://sourcemaking.com/design_patterns/prototype

Summary

In this article we have explored the Prototype pattern. The usage of Prototype pattern can be summarized as:

· Faster instance creation with required properties

· The new keyword can be avoided in instance creation

· Provides an alternative to Abstract Factory pattern

· Runtime specification of instance properties

· Reference of concrete class can be avoided

The associated source code contains the example we discussed.

Posted in C# | Tagged: | 2 Comments »

Running out of space in C Drive?

Posted by JP on January 8, 2012

Don’t Worry…… Partition it to increase the space.

Often we will be running into problems of low disk space in system drive .. even though you allocated 30 GB for it.

Some Free Partition Tools

1. Aoemei

http://www.extend-partition.com/download.html

image

2. EaseUS

http://www.partition-tool.com/

image

My Experience

I have used Aomei Partition Assistant on my Windows 7 PC to increase drive space by 30 GB.  It reallocated space from another drive towards the C drive.  The entire operation took around 1 hour and no problems were faced.

The tool applies for Windows 7, 2003, 2008 etc.

Posted in C# | Tagged: , , | Leave a Comment »

Windows Azure – WCF in Web Role

Posted by JP on January 4, 2012

In this article I would like to demonstrate the creation and deployment of WCF service in a Web Role.

The attributes of WCF service on Web role are:

  • IIS Hosted
  • IIS features like pooling and caching availability
  • Less Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it as WCFInWebRole as shown below

clip_image002[4]

In the appearing dialog add one Web Role project as shown below.

clip_image004[4]

Add a new WCF Service into the project. Name it as MessengerService.

clip_image006[4]

Now the Solution Explore will look like below with the newly added contracts and service files.

clip_image008[4]

Modify the DoWork() method in the interface IMessengerService as given below.

string SendMessage(string name);

Modify the DoWork() method in the interface IMessengerService as given below.

public string SendMessage(string name)

{

return “Hello ” + name;

}

Step 2: Test the application

Make the MessengerService.svc file as the start page as shown below.

clip_image010[4]

Press F5 to execute the application and you can see the service opened in the browser as shown below.

clip_image012[4]

Now are have tested the application and it is ready to be deployed to the cloud.

Step 3: Deploy to the cloud

Right click on the Web Role project and click package menu item as shown below.

clip_image014[4]

In the appearing dialog select the default option and click the Package button.

clip_image016[4]

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

clip_image018[4]

In the appearing dialog box enter the details as shown below.

clip_image020[4]

Choose the option “Deploy to production environment”

Locate the package and configuration files from your application bin folder.

(Eg: ..\WCFInWebRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

clip_image022[4]

Select the Deployment 1 row and from the properties window you can get the url of the web role.

clip_image024[4]

Click on the url and your application will get opened in the browser. Add the suffix MessengerService.svc to get the messenger service.

clip_image026[4]

Step 3: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the service url as shown below.

clip_image028[4]

Click Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)

{

ServiceReference1.MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();

string result = client.SendMessage(“Ian”);

Console.WriteLine(string.Format(“Invoking WCF Service Result: {0}”, result));

Console.ReadKey(false);

}

Now set the console application as the start project and execute the application.

You can see the following results.

You can see the result Hello Ian from the WCF service.

This concludes our article on WCF service deployment as web role and the testing.

Summary

In this article we have seen how to deploy a WCF service to cloud platform. The WCF service inside the Web role will be hosted in IIS. The source code is attached and the application name in the url has to be changed according to your application name.

Posted in C# | Tagged: | 3 Comments »

Memento Pattern

Posted by JP on January 3, 2012

In this article I would like to experiment with the Memento pattern. Memento pattern provides an Object Oriented way of saving the state of an object. The state called as Memento can be used to restore the object later.

The English meaning of Memento is Reminder of Past Events.

Challenge

You are working on a Drawing application which allows the user to draw lines on a Canvas. The user should be able to Save the state on particular intervals so any further mistakes could be undone. You need to provide a solution for the problem.

Definition

“Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later”

Implementation

The above problem can be solved using the Memento Pattern. This pattern as said in the definition saves the internal state of the object for restoring later. The object state is saved without violating Encapsulation.

clip_image002

Following is the Drawing class definition:

clip_image004

The AddLine() method allows to add line on the graphics. These information are stored inside the _list object as state.

The CreateMemento() allows to get a copy of the internal state without violating Encapsulation.

The RestoreMemento() allows to restore the state to the given memento.

Following is the Memento class definition:

clip_image006

It contains the State property to hold the State of Drawing class.

Executing the Application

You can try executing the attached application. After executing draw a series of lines in the Canvas and use the Save button to save the memento.

clip_image008

Now try to add some unwanted lines:

clip_image010

Use the Restore State to get the old valid state.

clip_image012

So this concludes our application implementing Memento pattern.

Comparing Command and Memento Patterns

The Command pattern also provides the Undo / Redo functionality by converting actions to commands. The difference would be that the Command pattern stores each action but the Memento pattern saves the state only on request.

Additionally, the Command pattern has Undo and Redo operations for each action, but the Memento does not need that.

Depending on the scenario, Command / Memento pattern could be used.

Summary

In this article we have explore the Memento pattern. The attached source code contains the example we discussed.

Posted in C# | Tagged: | Leave a Comment »