Friday, August 28, 2009

Chain of responsibility pattern in c# .Net

Intent
The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver.

Non-Software Example
A mechanical sorting used by banks is an example for chain of responsibility pattern. In a sorting machine there is single slot for all the coins. As each coin is dropped a chain of responsibility it determines which tube to accommodate each coin. If a tube cannot accommodate the coin, it is passed to next one until a tube can accept the coin. Here the coin corresponds to the requestor. Each tube corresponds to the chain of concrete handlers.




Benefits
Here if you observe the coupling between the coin slot and coin tube is reduced. Although there are four slots only one slot is used. The are no explicit receivers for the coin. It might happen that the coin is not accommodated in any of the tubes and the coin comes out. With chain of responsibility receipt is not guaranteed always.
As we discussed chain of responsibility promotes loose coupling by allowing a series of handlers to be created in a linked chain. The request is passed to the first handler in the chain, which will either process it or pass it on to its successor. This continues until the request is processed or the end of the chain is reached. The handler responsible for the final processing of the request and

UML

Let us look into the classes
Client: The client class is the one who generates the request. If you consider our previous example the coin is the client.

HandlerBase: the Handler base is an abstract base class for the concrete handler classes. It contains a member that that holds the next concrete handler (in the UML it is ConcreteHandlerA or ConcreteHandlerB) in the chain and an associated method to set its successor. It includes a abstract which has to implemented by the concrteHandler classes. The implementation of this method would be either handle the request or pass it to the next object in the chain.

ConcreteHandler Class: There can be many concrete handler classes that inherit from handle base class. This Handle request method in this class will handle request and if not will pass it to the next successor.

Software Example & Explanation of Code

Let us consider a most frequently used code where we can see the chain of responsibility pattern. Let us say you have a try… catch block in “MethodA”. Let us say your code looks like this

MethodA
{
Try
{
MethodB();
//Some other Code
}
catch(exception ex)
{

}

Here is MethodB code

MethodB
{
Try
{
MethodB();
//Some other Code
}
catch(exception ex)
{

}


Now let us say you have an error in MethodB. So here there is a chain of try..Catch block. So when an error in MethodB occurs it goes to exception of B and since the call was generated it goes to the successor i.e. MethodA catch block.

Let us consider another example. Let us say you are building an application for an organization. The key players in the organization are HR Managers who can add an employee, HR Director who can modify the employee details and HR Vice president who can delete an employee entry from the system. Definitely this can be achieved with an if ..else condition, but as the code grows this becomes unmanageable. Let us create the classes one by one. All the classes and methods are self explanatory so we will get into explanation of code. First the operation types.

public enum RequestType
{
ADD=1,
MODIFY=2,
DELETE=3
}

Next is the abstract class. This is the “HandlerBase” class of the above UML

Approver.cs
public abstract class Approver
{
string _Name;
Approver _NextApprover;

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


public Approver(string appName)
{
_Name = appName;
}

public Approver NextApprover
{
get { return _NextApprover;}
}
public void SetNextApprover(Approver nextApprover)
{
_NextApprover = nextApprover;
}

public abstract void Approve(ref EmployeeChangeRequest changeReq);

}

Next are the classes implementing the abstract class, the Manager, Director and VicePresident class.

Manager.cs
public class Manager:Approver
{
public Manager(string name)
: base(name)
{ }

public override void Approve(ref EmployeeChangeRequest changeReq)
{
if (changeReq.RequestType.Equals(RequestType.ADD))
{
changeReq.IsApproved = true;
}
else
{
if (NextApprover != null)
NextApprover.Approve(ref changeReq);
}
}
}

Director.cs
public class Director:Approver
{
public Director(string name)
: base(name)
{ }

public override void Approve(ref EmployeeChangeRequest changeReq)
{
if (changeReq.RequestType.Equals(RequestType.ADD) changeReq.RequestType.Equals(RequestType.MODIFY))
{
changeReq.IsApproved = true;
}
else
{
if (NextApprover != null)
{
NextApprover.Approve(ref changeReq);
}
}
}
}


VicePresident.cs
public class VicePresident:Approver
{
public VicePresident(string name)
: base(name)
{ }

public override void Approve(ref EmployeeChangeRequest changeReq)
{
if (changeReq.RequestType.Equals(RequestType.ADD) changeReq.RequestType.Equals(RequestType.MODIFY) changeReq.RequestType.Equals(RequestType.DELETE))
{
changeReq.IsApproved = true;
}
}
}


Now the employee class to which we want a change
public class EmployeeChangeRequest
{
int _requestID;
RequestType _requestType;
string _strRequestMessage;
bool _isApproved;

public EmployeeChangeRequest(int requestId, RequestType requestType, string RequestMessage)
{
_requestID = requestId;
_requestType = requestType;
_strRequestMessage = RequestMessage;
}

public int RequestID
{
get { return _requestID; }
set { _requestID = value; }
}

public RequestType RequestType
{
get { return _requestType; }
set { _requestType = value; }
}

public string StrRequestMessage
{
get { return _strRequestMessage; }
set { _strRequestMessage = value; }
}

public bool IsApproved
{
get { return _isApproved; }
set { _isApproved = value; }
}

}


Okay now we are all set to see the chain. Let us create a client for this set the values as shown. Please note the values are being passed as reference type in the abstract class

Manager objManager = new Manager("Manager1");
Director objDirector = new Director("Director1");
VicePresident objVp = new VicePresident("VP1");

objManager.SetNextApprover(objDirector);
objDirector.SetNextApprover(objVp);

//We are setting the delete type and calling the Manager class to approve
EmployeeChangeRequest objEmp = new EmployeeChangeRequest(123, RequestType.DELETE, "Employee with ID 123 is quiting, Please delete the data");

objManager.Approve(ref objEmp);


Now here in the client we are making a delete operation which only the Vice President has access to. But we are calling the approve method of manager class. So up on the call of approve method it will pass it to Approve method of director class and since director is also not authorized to delete it goes next to the Vice president class where it gets executed.

The entire source code is available @

http://www.csharppatterns.com/

Happy Coding.



Wednesday, August 26, 2009

WCF in VS 2005 , consuming wcf with VS 2003 or VS 2005, WCF in Sharepoint 2003

We may often come with situation where we want to use a WCF service with .Net framework 1.1 or 2.0. We know that with 2.0 we can add the WCF extenders and work with WCF, but what about VS 2003 and .net Framework. Lets say we have an existing application in .Net 1.1 framework and wants to use WCF. This article expains this situation. First let us create your WCF Service. To keep it simple create a WCF service with VS 2008 and host it in iis. Let say your service is having a method "GetWelcomeMessage" which takes a string as input parameter and retuns the same value by appending "Welcome to WCF" to it. Below is how the WCF code will look like

public string GetWelcomeMessage(string value)
{
return "Welcome to WCF " + value;
}

you may find the details of how to host a service in iis @
Hosting WCF in IIS

Make sure that you use "basicHttpBinding" and make the config file changes as



Now Open your VS 2003 application and add a web reference as shown below. Lets call the service reference as "localhost". Lets say you have hosted your service "http://localhost/HelloWorldService/HelloWorld.svc"



After adding the service it will look like this



Now go to you code where you want to make a call to the code

localhost.Service1 objService = new localhost.Service1();
Response.Write(objService.GetWelcomeMessage("Puru"));


The output of this would be "Welcome to WCF Puru".

Hope this helps....

You can also call the same service in Java client. Know more @ Consuming WCF in Java

Flyweight Pattern c#.Net

Intent
A high quantity of objects share a common properties object to save space. Flyweight can be used while working with large quantity of similar objects to save memory space.

Non-Software Example
Most telephone subscribers are unaware that the pool of Tone generators (such as dial tone, busy tone or reorder tone) is much smaller than the number of subscribers. The pool of Dial Tone generators is an example of a Flyweight.





Benefits
When we need to create a large amount of objects, each object requires an amount of storage. Even if the size of the objects is small when it comes to a large number of objects the overall required space becomes too high. Some times the creation of small objects reaches a stage that the program cannot execute at all.
This can be addressed with flyweight pattern. With flyweight pattern the object is being crated once and any subsequent request to the same, object is being shared from the earlier created object. Every new request points to the reference of the earlier created object.

UML



Below is the explanation to the UML of the flyweight pattern UML

FlyweightBase: This can be either an interface or an abstract class. When there is no implementation required in the base class we can choose to make it a interface otherwise an abstract class.

ConcreteFlyweight : This class inherits from the FlyweightBase class and holds the stateless information. Stateless information means the same object, so instead of creating a new object the same object can be shared.

UnsharedFlyweight : This class is inherited from FlyweightBase class and holds stateful information. Stateful object means every object will have a specific attribute and behavior.

FlyweightFactory : This class holds references to each of the flyweight objects that have already been created. When the “GetObject” method is called from client code, these references are checked to determine whether appropriate flyweight is already available or not. If one available, it is returned. If not, a new object is created, added to the collection and returned.

The objects in flyweight can be of either of intrinsic and extrinsic. Intrinsic objects are those flyweight objects which are shared. This information is stateless and generally remains unchanged, as any changes would be effectively replicated amongst all of the objects that reference the flyweight. Extrinsic data can be stateful as it is held outside of a flyweight object.

Software Example & Explanation of Code

Flyweight pattern is most useful while building simulation system. In our example let us say we are building a simulation program for a park. So we will be taking a virtual tour of a park. So obliviously when we take a tour it will have trees and cement posts in the park. This example will demonstrate how to apply flyweight pattern in this scenario. We can always say that flyweight uses a form of factory Method pattern.

The first class is the “DisplayUnit” class. This is an abstract class and both the “CementPost” and “Tree” class will inherit from it. Next is the factory which creates the class when not available and if available serves it from the existing objects. Below is the implementation details of each of these class

DisplayUnit.cs

namespace Flyweight
{
public abstract class DisplayUnit
{
public string Name
{
get;
set;
}
public int AboveGround
{
get;
set;
}

public abstract void IsRootVisible(ObjectType objType);
}
}

CementPost.cs

namespace Flyweight
{
class CementPost:DisplayUnit
{

public override void IsRootVisible(ObjectType objType)
{
Console.WriteLine("Root Of {0} Tree not Visible and is above {1} level of ground", objType.objDisplayUnit.Name, objType.objDisplayUnit.AboveGround.ToString());
}
}


}

Tree.cs

namespace Flyweight
{
public class Tree:DisplayUnit
{
public override void IsRootVisible(ObjectType objType)
{
Console.WriteLine("Root Of {0} Tree not Visible and is above {1} level of ground", objType.objDisplayUnit.Name, objType.objDisplayUnit.AboveGround.ToString());
}
}
}

ObjectType.cs

namespace Flyweight
{
public class ObjectType
{
public DisplayUnit objDisplayUnit;
}
}



Let us create a client for this. Let’s say that you are creating two stateless Tree objects. So according to flyweight instead of creating a new object on the second request it should server from the existing object itself.
static void Main(string[] args)
{
DisplayUnitFactory objFactory = new DisplayUnitFactory();

ObjectType objTreeType = new ObjectType();
objTreeType.objDisplayUnit = objFactory.GetObjectType("Tree");

ObjectType objCementPostType = new ObjectType();
objCementPostType.objDisplayUnit = objFactory.GetObjectType("Cement");

ObjectType objTree1 = new ObjectType();
objTree1.objDisplayUnit = objFactory.GetObjectType("Tree");

if (objTreeType.objDisplayUnit == objTree1.objDisplayUnit)
Console.WriteLine("Same object");
else
Console.WriteLine("Different Object");

Console.ReadLine();

}


The output would be the same object hence you will get the out put as “Same Object”. Hope this helps.

The entire source code is available @ http://www.csharppatterns.com/

Happy Coding.

Tuesday, August 25, 2009

Architecture of .Net

Software development industry today is full of incompatibilities. Modules written in different languages do not integrate easily with each other. Applications made on different operating systems use different API’s which makes the compatibility issues even more difficult. In addition, as the software industry focus shifts from stand-alone applications (Desktop applications) to client/server applications there are a new set of compatibility issues appears. Instead of compiled languages, we are using scripting languages for web applications. Instead of Rich User Interface we have HTML and instead of Object oriented concepts we have number of unrelated technologies like COM, XML, DHTML for internet application development.

The Microsoft .NET Framework

.Net comprises of two key components: the Common Language Runtime (CLR or simply “runtime”) and the .Net Framework Class Libraries (FCL). The CLR abstracts operating system services and provides an execution engine or environment to run applications. Application that runs completely under CLR is called as managed code. It is also possible to use COM or windows API objects as well in your .Net application. However, these codes will not be processed by CLR. Such codes are called as unmanaged code.


The Common Language Runtime (CLR)

If the .Net Framework were a leaving human being then CLR would be its heart and soul. Every byte of code that we write either runs in CLR or is given permission by CLR to run.

CLR extracts services of the operating system and provides an environment for execution of managed code. Every code before execution needs to be complied. As any code in JAVA after compilation is converted to byte codes, .Net framework complaint languages are converted to pseudo-machine language called Common Intermediate Language (CIL Or Microsoft Intermediate Language, MSIL or simply IL). Compilation occurs in two steps in .Net

1. Compilation of source code to IL.
2. Compilation of IL to platform specific code by CLR.

Apart from code compilation CLR does other important functions as well.

1. Memory Allocation
2. Thread Management
3. Garbage Collection
4. Maintains Type Safety (CTS)

CIL code is Just In Time compiled (JIT) in to machine code, It means that a piece of code will not be compiled to machine language till it is being called. Most of the cases JIT code compiled only once and thereafter cached in to Memory and subsequent request to the code will be served from cached memory. Say for example if my CIL code contains a method A(), method A() will not be compiled to machine language till its being called by some application or program. Once compiled it will be cached into Memory and subsequent calls to method A() will be served from the memory.

As the CLR converts the CIL to machine code it enforces code verification to make sure that the code is type safe. One of the biggest advantages of CIL is that CIL codes are strongly Type Safe. This means that all the variables belong to a specific data type. There is no scope of “Variant” data types as in Visual Basic (Variant data can be converted to any type at runtime).

Let us discuss a small example. The following code will compile in VB but will not compile in .Net because of type safety.

Dim Variable1 //Compiler treat this as variant as no data type is defined
Dim intVariable as Integer // Integer Variable
Dim strVariable as String //String Variable

Variable1 = intVariable
Variable1 = strVariable

Variable1 can be converted to a string or integer in Visual Basic, as it is a variant type but to run the same code in .Net we have to define two variables in .Net (one Integer type for intVariable and one string type for strVariable).

Windows isolate different applications by hosting them in different processes. If you are running two applications windows opens two different processes for this. Unfortunately one-process-per-one-application model consume more memory. One of the advantages of code verification technology is that it allows CLR to host multiple applications in a single process by isolating them in different compartments. Each compartment has its own set of boundaries and these compartments are known as “application domains”. CLR does not lunch a new process for each application rather it hosts all application in a single process keeping them in different application domains.

Another benefit of managed code is all memory allocated by the managed code is garbage collected. In other words, you allocate the memory by creating different objects but the CLR will free it for you. The process through which system does this is Garbage Collector.


Microsoft’s initiative in to answer all these issues is Microsoft .Net or simply .Net. .Net is a new way of building and deploying software that uses open standards like XML and HTTP to make the interoperability a reality. An important part of this initiative is “.Net Framework”. .Net Framework provides a platform for developing software and it makes the development process easy and less time consuming.

At this point, we have an idea that Microsoft has come up with something called .Net to provide an environment for fast development and which tackles the interoperability issues. Let us now focus on its key components.

Friday, August 21, 2009

Facade Pattern in c#

Intent
The Facade defines a unified, higher level interface to a subsystem, that makes it easier to use.

Non-Software Example
When ordering from a catalog (over phone), consumers do not have direct contact with the Order Fulfillment, Billing, and Shipping departments. The Customer Service Representative acts as a Facade, or unified interface, to each of the departments involved in the transaction.



Benefits:

Clients are shielded from individual departments. When ordering an item, it is not necessary to check the stock, generate an invoice, and arrange for shipping. All steps are accomplished through the customer service representative. The internal structure of the organization can be changed without affecting the client. For example, the shipping department can be contracted to another organization, without impacting the client’s interface with the company.


UML:



Let us understand the UML. The above Fig shows an implementation of Façade pattern and below is the classes involved.

Façade: The Façade contains simple methods that can be accessible by the users and easily understood by the users. The Façade hides the complexities of the sub systems.

Package A & Package B: These are the packages that the user needs to implement. They may not necessarily reside in a single assembly.

Class A1, A2, B1, B2: These are the classes whose functionality the user wants to use. The façade expose these complex functionalities. The end user may not need to know the implementation details of these classes.

Software Example & Explanation of Code:

Let us go ahead with our previous example. Let say you have a system (console application) which is being used in an organization. You have modules like “Order Fulfilling” where order details are entered, “Billing” where payment details are entered and “Shipping” where shipment details are entered. Each of these modules is complex by nature and they are interdependent like shipping can only happen if Billing is complete etc. Earlier each department use to enter these details once they get an order. Now the organization has grown and now they have a customer service desk that takes the order and makes the entry in the system. So you need to build an interface for the service desk. So using Façade pattern you can design a class which will process the order without know the complexities of the individual modules.

Note: This sample is only for better understanding of the concept only.
So as in previous case each department will use their own code to do the task. Like the Order fulfillment will take the order and do the needful. Similarly billing and shipping department will do the needful by taking the data. Remember all of them use the “Billing”, “Shipping” and “OrderFullfillment” classes as shown below.

OrderFullFillment.cs

namespace FacadePattern
{
public class OrderFullFillment
{
//Here the total items available is 100. if the
//total requested is more it will return false
private int _intStock = 100;

public bool IsAvailable(int intOrdered)
{
if (_intStock > intOrdered)
Console.WriteLine("Order Placed Successfully");
else
Console.WriteLine("Order Failed");

return _intStock > intOrdered;
}
}
}

Billing.cs

namespace FacadePattern
{
public class Billing
{
public string CardNo
{
get;
set;
}
public int Amount
{
get;
set;
}
public bool BookTicket()
{
//Insert details to relevant tables
//with CardNo and amound
Console.WriteLine("Billing Details Updated Sussessfully");
return true;
}
}
}

Shipping.cs

namespace FacadePattern
{
public class Shipping
{
public string Adress
{
get;
set;
}
public void LogShipping()
{
Console.WriteLine("Product Shipped to " + this.Adress);
}
}
}

Now with the new requirement the ordering proceess has been changed and it has gone to the customer service desk. Now we need to build a class which can consume all these functionalities by providing a simple interface to the user (here user is some one who is going to use the class). This class would be our Façade class and the code for the class would look like this

namespace FacadePattern
{
public class FacadeClass
{
public void CreateOrder(int intQuantities,string strCardNo, int intAmount,string strAddress)
{
OrderFullFillment objOrder = new OrderFullFillment();
Billing objBilling = new Billing(strCardNo,intAmount);
Shipping objShipping = new Shipping(strAddress);

objBilling.CardNo = strCardNo;
objBilling.Amount = intAmount;

objShipping.Address = strAddress;
//Check whether stock available
if(objOrder.IsAvailable(intQuantities))
{
//Check payment Details
if (objBilling.BookOrder())
{
objShipping.LogShipping();
}
}
}
}
}

Now let us create client for the class. And pass different parameters

namespace FacadePattern
{
class Program
{
static void Main(string[] args)
{
FacadeClass objFacade = new FacadeClass();
objFacade.CreateOrder(80, "8827728829", 2000, "MyAddress");
Console.ReadLine();
}
}
}
When the order is less then 100 it givs the following results
Order Placed Successfully
Card No—8827728829 Amount--2000
Billing Details Updated Sussessfully
Product Shipped to MyAddress

If you change the value and pass the first parameter as 120 (basically any value more than 100), you will receive the following messages
“Order Failed”.
Basically what we have achieved with this is that with the façade we were able to hide the complexities of all the code and provided just once interface fro the user to create the order.

Thursday, August 20, 2009

Information as a Service (IaaS)

What is Information as a Service (IaaS). We have heard of SaaS (Software as a Service), PaS (Product as a Service), what next?

IaaS is not a new concept. We all know about business intelligence Tools (BI tools like Business Objects, Cognos, Informatica, SAS, Teradata or some other software package).

I feel the best way to define IaaS is “exposing BI data through services”. You are increasing the reach of BI systems.

IBM defines IaaS as “Information as a service is an entry point to service oriented architecture (SOA) that offers information access to complex, heterogeneous data sources within your company as reusable services. These services may be available both within the enterprise and across your value chain.”

Source : http://www-01.ibm.com/software/solutions/soa/entrypoints/information.html

Let me give a quick brief of the BI systems we had. Earlier BI tools use to ship with ETL model . ETL (extract, transform and load) processing, data warehouses and data marts, and reporting systems. There was no option available for some one to get the data in any other place then the package components itself.

First The Web : We made little progress in late 90s where we had web browsers and we have portals. Portals offered portlets where there was a flexibility to insert a code snippet and get the BI data in the portals. The portlets offered it with variety of forms like charts, graphs etc. This give sign to developer world that they do not have to log into BI to get the data but they can get it through portlets.

Second the SOA : Next came the SOA (Service Oriented Architecture). This gave the flexibility for the developers world that they don’t have to code for every thing. They can get the data through services

Third Increased Connectivity : Earlier the restriction to SOA model was the connectivity. Although you may have a SOA platform but you still may not be able to use it because of the low connectivity. Now with the latest broadband service and virtual networks data reaches you in no point of time. With this platform the BI data can reach you in no point of time if you expose it as a service.

So what does it means to everyone?

IaaS means that you can deliver BI snippets to variety of applications and users. In other words you will increase the reach of BI.

Reference : http://www.information-management.com/news/1059873-1.html

Tuesday, August 18, 2009

Consuming WCF service in Java

This post explains consumption of a WCF service in Java client.
Let us first create a WCF service. Open your Visual studio 2008 and create a WCF service. Visual studio will create a default service for you and it would look like the below code.

To make it interop I will pick basicHttpBinding. Please note that to make it interoperable either we can choose "basicHttpBinding" or "wsHttpBinding".


Below is the service method.

public class Service1 : IService1
{
public string GetWelcomeMessage(string value)
{
return "Welcome to WCF " + value;
}
}

Note: You can use wsHttpBinding also, but wsHttpBinding is not supported by all Java IDEs. You have to use something like Axis2 IDE.

Once we are done with the development of the service. You can know about how to host in IIS @
Hosting WCF service in IIS.

Since I need to host it in IIS i need to make the changes in my web.config as app.config file. Below is the web.config file. It is the same as app.config file



Now we are done with our WCF Service. Now lets say that this service is hosted in "ABC123" machine (typicall on your machine "ABC123" would be "localhost").

Let us build the Java client for this. We will use Net Beans IDE 5.5 for this example. We will name the application as "javaapplication1". Below are the pre-requisite for the NetBeans application

• WCF service should be hosted in IIS
• NetBeans IDE for Java
• In-built Application server – SunOne/Apache Tomcat
• JDK 1.5 or higher
• JARs :- JAX-RPC packaged Jars

First step is to add a web service client. Right click on "Source Packages" of your appliation. Select "New" and then "Web Service Client". It would look like



Enter the WSDL location of the service in the "proxy host" text box. It would look something like this.This address would contain the host address "ABC123" in our case



Let say we have a simple Frame with a text box. The user has to enter some input value in the text box and click the Consume button. The click Invokes the WCF service hosted on "ABC123" machine, passes the input and receives the output, post execution of the service and displays the same in the output textbox. The Frame would look like this



The handler of the Button Click has to be coded like:-

String input = jTextField1.getText ();
try {
javaapplication1.Service1 service1 = new javaapplication1.Service1_Impl();
javaapplication1.IService1 basicHttpBinding_IService1 = service1.getBasicHttpBinding_IService1();
jTextField2.setText (basicHttpBinding_IService1.getWelcomeMessage (input));
} catch (javax.xml.rpc.ServiceException ex) {
} catch (java.rmi.RemoteException ex) {
} catch (Exception ex) {
// TODO handle custom exceptions here
}

The output would look like



I hope this help to some one who wants to consume WCF in JAVA.

Composite Design Pattern in C#

Intent:

The Composite composes objects into tree structures, and lets clients treat individual objects and compositions uniformly. The Composite pattern is useful when individual objects as well as aggregates of those objects are to be treated uniformly.

Non-Software Example:

An everyday example is enumerating the contents of a file folder. A folder may contain not only files, but subfolders as well. An application designed to recursively display the list of all files in some top-level folder can use a conditional statement to distinguish between files and directories, and traverse down the directory tree to display the names of files in the subfolders. The composite pattern is a design pattern that is used when creating hierarchical object models.

Benefits:

A better approach for the above issue can be answered by the Composite pattern. In this approach, every folder item, be it a file, a subfolder, a network printer for any directory element, is an instance of a class that conforms to an interface offering a method to display a user-friendly name of the element. In this case, the client application does not have to treat each element differently, thereby reducing the complexity of the application logic. Also incase there is a new type also added to the folder the composite pattern will automatically handle it. Let’s say tomorrow we have a new file type in the folder say “network connection” type. If the “network connection” implements the same interface as the files and folders we do not need to change any code.

UML:



The UML above describes the implementation details of composite pattern. Let us understand each of these block separately

Component: The component is an abstract class which acts as a base class for all the objects in the hierarchy. We can also use an interface to define this.

Composite: The composite block is most important in the composite pattern. This class contains methods to add and remove the child components and methods retrieve those children objects through a collection. Each of these objects can also be a composite containing its own children. The composite implements IEnumerable interface. This idea behind this implementation is that it helps in looping through the objects.

Leaf: These classes used to define tree with in the tree and cannot have their children.

Software Example & Explanation of Code:

Let us discuss the software example for the composite pattern. The most common place where you can find the hierarchy is a work place. Let us create fictitious organization where John is the CEO. Sam and Tina are the Vice president of the organization and both of then report to John. Rob and Andy are contract employees and they in turn report to Sam. Lucy is a normal employee reporting to Sam. Maria, Bill and Scott are general employees reporting to Tina.



Let us build the composite pattern one by one. First the interface which is the “component” block in the above UML

IEmployee.cs

namespace CompositePattern
{
public interface IEmployee
{
string Name{get;set;}
}
}
Next is the Employee class implementing the IEmployee and the interface IEnumerable

Employee.cs

namespace CompositePattern
{
public class Employee:IEmployee,IEnumerable
{
private List subordinates = new List();
private string _Name;

//Implemention of IEmployee
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
//Private method implementation
public void AddSubOrdinate(IEmployee reportee)
{
subordinates.Add(reportee);
}

public void GetSubOrdinate(IEmployee reportee)
{
subordinates.Remove(reportee);
}

public IEmployee GetSubOrdinateDetails(int intEmp)
{
return subordinates[intEmp];
}

//Implemention of IEnumerable
public IEnumerator GetEnumerator()
{
foreach (IEmployee empobj in subordinates)
{
yield return empobj;
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

}
}
Since we have Rob and Andy as contract employees let us create a contract class for them implementing the same IEmployee interface. Below is the code for the contract class

Contract.cs
namespace CompositePattern
{
public class Contract:IEmployee
{
private string _Name;

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

}
}
Finally the client which will demonstrate the composite pattern. Create an aspx page and add the following code.

Default.aspx.cs

namespace CompositePattern
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Add CEO Details
Employee john = new Employee();
john.Name = "CEO--John";

//ADD VP Details
Employee Sam = new Employee();
Sam.Name = "VP--Sam";
john.AddSubOrdinate(Sam);

Employee Tina = new Employee();
Tina.Name = "VP--Tina";
john.AddSubOrdinate(Tina);

//Add subordinate Details for Sam
Contract Rob = new Contract();
Rob.Name = "Employee --Rob";
Sam.AddSubOrdinate(Rob);

Contract Andy = new Contract();
Andy.Name = "Employee --Andy";
Sam.AddSubOrdinate(Andy);

Employee Lucy = new Employee();
Lucy.Name = "Employee --Lucy";
Sam.AddSubOrdinate(Lucy);

//Add subordinate Details for Tina
Employee Maria = new Employee();
Maria.Name = "Employee --Maria";
Tina.AddSubOrdinate(Maria);

Employee Bill = new Employee();
Bill.Name = "Employee --Bill";
Tina.AddSubOrdinate(Bill);

Employee Scott = new Employee();
Scott.Name = "Employee Scott";
Tina.AddSubOrdinate(Scott);

//Here is the real implementation

Response.Write(john.Name + "
");
foreach (Employee vp in john)
{
Response.Write(vp.Name+"
");
foreach (IEmployee emp in vp)
{
Response.Write(emp.Name + "
");
}
}
}
}
}
Here is the output
CEO--John
VP--Sam
Employee --Rob
Employee --Andy
Employee --Lucy
VP--Tina
Employee --Maria
Employee --Bill
Employee Scott

The code is self explanatory. The entire source code is available @ http://www.csharppatterns.com/.

Reference http://msdn.microsoft.com/en-us/magazine/cc301852.aspx

Adapter Pattern in C# ( Wrapper Pattern in C# )

Intent:
The adapter pattern is used to allow two incompatible types to communicate, where one class relies upon a specific interface that is not implemented by another class, the adapter acts as a translator between the two classes.

Non-Software Example:
The cell phone adapter can be an example for adapter pattern. Cell phones are normally designed to take 9 Volts of DC (Direct Current).The normal power supply at home (in India) is 220 Volts of AC (Alternate Current). So if we say the cell phone is one class and power supply at home is another class then power supply can not be used directly for the cell phone. Hence we need an adapter for the cell phone to get the cell phone charged by the normal power supply at home.



Benefits:
The adapter design pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

UML


The UML class diagram above describes an implementation of the adapter design pattern. The items in the diagram are described below:

 Client. The client class requires to use an incompatible class. It expects to interact with a type that implements the ITarget interface. However, the class that we wish it to use is the incompatible Adaptee.
 ITarget. This is the expected interface for the client class. Although shown in the diagram as an interface, it may be a class that the adapter inherits. If a class is used, the adapter must override its members.
 Adaptee. This class contains the functionality that is required by the client. However, its interface is not compatible with that which is expected.
 Adapter. This class provides the link between the incompatible Client and Adaptee classes. The adapter implements the ITarget interface and contains a private instance of the Adaptee class. When the client executes MethodA on the ITarget interface, MethodA in the adapter translates this request to a call to MethodB on the internal Adaptee instance.

Software Example & Explanation of Code:

Let us assume that we are building a web application for a school. One of the requirements is to display all the teacher’s details along with the school information. We already have a class (TeachersClass.cs) which stores the teacher information. The other school information course offered, current student strength, Fees etc is stored in the “SchoolDetails.cs” class. The client (Default.aspx) wants all the inform stored in both “TeachersClass.cs” and “SchoolDetails.cs” class. Since these two classes are not compatible to each other we have build the “SchoolAdapter.cs” class which will make the communication between these two classes. Let us take each of the classes at a time,

Note : The example illustrated here is to make the concept clear and understandable. This code cannot be directly used on production system to apply adapter pattern.


TeachersDetails.cs

The teachersDetails class has all the teachers information.

public class TeachersDetails
{
public string[][] GetTeachers()
{
string[][] teachers = new string[4][];

teachers[0] = new string[] { "1221","Shyam","Science Teacher" };
teachers[1] = new string[] { "3233","Ram", "Computer Teacher" };
teachers[2] = new string[] { "4322","Laxman","History Teacher" };
teachers[3] = new string[] { "1234","Mohan","Biology Teacher" };

return teachers;
}

}

SchoolDetails.cs

The SchoolDetails class has all the required information about the school, but not the teachers information.

public class SchoolDetails
{
ITeacherDetails _objTeacherDetails;

public SchoolDetails(ITeacherDetails objTeacherDetails)
{
_objTeacherDetails = objTeacherDetails;
}

public string getTeacherString()
{
return _objTeacherDetails.GetTeachers();
}
public string GetStudentStrenght()
{
return "Class 1 = 50 studernt
Class 2 = 50
";
}
public string GetCourseOffered()
{
return "Package with Maths
Package with Biology
";
}
public string GetCourseFee()
{
return "Package with Maths : $400
Package with Biology : $500
";
}
}
public interface ITeacherDetails
{
string GetTeachers();
}

SchoolAdapter.cs

The SchoolAdapter.cs class is the adapter class which does the communication between the SchoolDetails class and the TeacherDetails class.

public class SchoolAdapter:ITeacherDetails
{
TeachersDetails _objTeacherDetails;
public SchoolAdapter(TeachersDetails objTeacherDetails)
{
_objTeacherDetails = objTeacherDetails;
}
public string GetTeachers()
{
string[][] objTeacher = _objTeacherDetails.GetTeachers();
StringBuilder objString = new StringBuilder();

foreach(string[] Teacher in objTeacher)
{
objString.Append("Name of Teacher :" + Teacher[1]+"--");
objString.Append("Subject :" + Teacher[2] + "--");
objString.Append("Extn" + Teacher[0] + "--");
objString.Append("==============================" + "--");
}
return objString.ToString();
}

}

The entire code for download is available at http://www.csharppatterns.com/


Singleton pattern in C#



Intent: The Singleton pattern ensures that a class has only one instance, and provides a global point of reference to that instance.

Non-Software Example:
The United States (In that matter any country’s President’s Office) can be example of Singleton Pattern. At the most at any point of time there can be only one President to hold the position, which means that there is only one instance at any point of time.



Benefits:

The president title controlled access to the sole instance. Since the president office encapsulates the president there is much control over the single instance.

Software Example & Explanation of Code:

Let us assume that we are building an ASP.Net application for a school, where we have to display information about the school in most of the pages of the application. Of course I understand this may not be a very good example in the real time scenario, but from understanding a concept perspective this gives a good understanding.
In the example we have two pages “Default.aspx” and “Page2.aspx” which needs to display the school information. Although both the pages will make the request to the “SchoolMaster” class for the school information, but both the requested will be served from the same instance once it is instantiated.

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable “objSingleTon” in “SchoolMaster” Class is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses an “objRoot” instance to lock on, rather than locking on the type itself, to avoid deadlocks.

The double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient. Below is the code snippet

SchoolMaster.cs

public class SchoolMaster
{
private static volatile SchoolMaster objSingleTon;
private static object objRoot = new Object();

private string _SchoolName;

public string SchoolName
{
get { return _SchoolName; }
set { _SchoolName = value; }
}
private string _SchoolStandards;

public string SchoolStandards
{
get { return _SchoolStandards; }
set { _SchoolStandards = value; }
}

//Declare a private constructor so that no one can create the object from outside
private SchoolMaster()
{
_SchoolName = "ABC SCHOOL LTD";
_SchoolStandards = "High Standard School";
}

public static SchoolMaster GetSchoolDetails()
{
if (objSingleTon == null)
{
lock (objRoot)
{
//Double check again
if (objSingleTon == null)
{
objSingleTon = new SchoolMaster();
}
}
}
return objSingleTon;
}
}

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strName = SchoolMaster.GetSchoolDetails().SchoolName;
string strStandards = SchoolMaster.GetSchoolDetails().SchoolStandards;

Response.Write("Welcome To : " + strName +"--");
Response.Write("Standards are : " + strStandards);
}

protected void btnMove_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
}

Page2.aspx.cs

public partial class Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strName = SchoolMaster.GetSchoolDetails().SchoolName;
string strStandards = SchoolMaster.GetSchoolDetails().SchoolStandards;

Response.Write("Welcome To : " + strName + "--");
Response.Write("Standards are : " + strStandards);

}
}


The entire code for download is available at http://www.csharppatterns.com/


Prototype Design Pattern in C#



Intent: The intent of Prototype pattern is to specify the kind of objects to create using a prototypical instance and create new objects by copying this prototype.

Non-Software Example:
The mitotic cell division of a cell results in two cells of identical genotype. This cell cloning is an example of prototype pattern. The cell itself takes an active role of creating a new instance itself.

The cell here corresponds to the Prototype, as it has an interface to clone itself.
The specific instance represents the concrete prototype.
The DNA or the genetic blue print corresponds to the client as it instructs the cell to divide or clone itself.



Benefits:

Prototype pattern is used when creating an instance of a class, which is complex and time consuming. Instead of creating a new instance of the object, it is possible to make copy of the original object in some way.

Software Example & Explanation of Code:

Let us assume that we are building an ASP.Net page where we have a requirement to update the employee address. As a part of this requirement we have to update the existing record at the same time we have to keep the track of the existing record also.

With C# prototype pattern can be very easily implemented by using the “ICloneable” interface. Any class that wants to support cloning should implement “ICloneable” interface. So here in our code we have an “Employee” class which implements the “ICloneable” interface. The clone method copies the existing data and returns a new cloned object. The implementation contains the “Employee” class which implements the ICloneable interface. The default.aspx.cs page implements the prototype pattern.

Employee.cs

using System;

namespace PrototypePattern
{
public class Employee:ICloneable
{
private string _FirstName;

public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;

public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private int _EmployeeId;

public int EmployeeId
{
get { return _EmployeeId; }
set { _EmployeeId = value; }
}
private string _Address1;

public string Address1
{
get { return _Address1; }
set { _Address1 = value; }
}
private string _Address2;

public string Address2
{
get { return _Address2; }
set { _Address2 = value; }
}

public Employee()
{

}



#region ICloneable Members

public object Clone()
{
Employee objEmployee = new Employee();
objEmployee.FirstName = _FirstName;
objEmployee.LastName = _LastName;
objEmployee.Address1 = _Address1;
objEmployee.Address2 = _Address2;
objEmployee.EmployeeId = _EmployeeId;

return objEmployee;
}

#endregion
}
}

Default.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace PrototypePattern
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee objEmployee = new Employee();
objEmployee.FirstName = "FirstName-ABC";
objEmployee.LastName = "LastName-ABC";
objEmployee.EmployeeId = 1001;
objEmployee.Address1 = "Address1- Old Address1";
objEmployee.Address2 = "Address2 - Old Address2";

//Clone the object , Implimentation of Prototype Pattern
Employee objEmp = (Employee)objEmployee.Clone();

//In real time implementation the database table containing History record
//Should take the data from objEmployee object and current data should use
//the objEmp object to pass the data

objEmp.Address1 = "Address- New Address1";
objEmp.Address2 = "Address- New Address2";

Response.Write("=================================================--");
Response.Write("------------Employee Address Details-------------"+"--");
Response.Write("=================================================--");

Response.Write("Employee ID-->" + objEmployee.EmployeeId.ToString() + "----");
Response.Write("First Name-->" + objEmployee.FirstName + "----");
Response.Write("Last Name-->" + objEmployee.LastName + "----");

//This should go to Main Table
Response.Write("Latest Address1-->" + objEmp.Address1 + "----");
Response.Write("Latest Address2-->" + objEmp.Address2 + "----");

//This should go to History Table
Response.Write("Old Address1-->" + objEmployee.Address1 + "----");
Response.Write("Old Address2-->" + objEmployee.Address2 + "----");

}
}
}

The entire code is available at http://www.csharppatterns.com/

Object Pool Design Pattern in C#




Intent: The intent of object pool is to create a pool object to reduce the load of creating objects.

Object pooling is nothing but creation of limited amount of objects in memory and reuse then instead of creating a new one. This can be achieved with the help of a pool manager. The pool manager knows the number of maximum instances to be created for an object type. Once the maximum number is reached pool manager puts them in to an object container and all new objects requests are being served from the object container.

Like Lazy Initialization object pooling can be achieved be either using Singleton or Factory Method.

Benefits:

The main advantage of using the Lazy initialization is that it will not consume unnecessary expansive resources for creating the object until it is required for the first time. Also if the object is already created the request is being served from the object created instead of creating a new object.

Software Example & Explanation of Code:

Let us assume that one of our code requirements is to create Employee objects. We have maximum restriction of two objects and anything more than two requests has to be served from the queue. For our example we will use Factory Method. We will be using the “Queue” class of “System.Collections” namespace for pooling our objects.

Note: Employee may not be good example when you think from software prospective, but this definitely helps you in understanding the concept.

EmployeeFactory.cs

using System;
using System.Collections;

namespace ObjectPooling
{
public class EmployeeFactory
{
//Defining Max pool size of Objects as two
static int _intMaxPoolSize = 2;

//Collection class to hold objects
static readonly Queue objPool = new Queue(_intMaxPoolSize);

//Creates new employee only when the count of objects is more than two
//Otherwise served from pool
public Employee GetEmployee()
{
Employee objEmployee;
if (Employee._intCounter >= 2 && objPool.Count > 1)
{
objEmployee = GetEmployeeFromPool();
}
else
{
objEmployee = CreateNewEmployee();
}
return objEmployee;
}

private Employee GetEmployeeFromPool()
{
Employee objEmp;
if (objPool.Count > 1)
{
objEmp = (Employee)objPool.Dequeue();
Employee._intCounter--;
}
else
{
objEmp = new Employee();
}
return objEmp;
}
private Employee CreateNewEmployee()
{
Employee objEmp = new Employee();
objPool.Enqueue(objEmp);
return objEmp;
}
}
}



Employee.cs

using System;

namespace ObjectPooling
{
public class Employee
{
public static int _intCounter = 0;

public Employee()
{
_intCounter = _intCounter + 1;
_FirstName = "FirstName" + _intCounter.ToString();
_LastName = "LastName" + _intCounter.ToString();
}

private string _FirstName;

public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;

public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
}
}

Default.aspx.cs

protected void btnCreate_Click(object sender, EventArgs e)
{
EmployeeFactory objEFact = new EmployeeFactory();

Employee obj1 = objEFact.GetEmployee();
Employee obj2 = objEFact.GetEmployee();
Employee obj3 = objEFact.GetEmployee();
Employee obj4 = objEFact.GetEmployee();

Response.Write("Object 1 Values are-----" + obj1.FirstName +"--"+obj1.LastName+"--");
Response.Write("Object 2 Values are-----" + obj2.FirstName +"--"+obj2.LastName+"--");
Response.Write("Object 3 Values are-----" + obj3.FirstName +"--"+obj3.LastName+"--");
Response.Write("Object 4 Values are-----" + obj4.FirstName + "--" + obj4.LastName + "--");
}


Here in the above code in the button click we are trying to create four object of employee class. When the code runs it initially creates two objects and other two create request are being served from the queue.

The entire code for download is available at http://www.csharppatterns.com/

Monday, August 17, 2009

Preventative steps for H1N1



Most N95 respirators are designed to filter 95% particulates of 0.3µ, while the size of H1N1 virus is about 0.1µ. Hence, dependence on N95 to protect against H1N1 is like protecting against rain with an umbrella made of mosquito net.

Tamiflu does not kill but prevents H1N1 from further proliferation till the virus limits itself in about 1-2 weeks (its natural cycle). H1N1, like other Influenza A viruses, only infects the upper respiratory tract and proliferates (only) there. The only portals of entry are the nostrils and mouth/ throat. In a global epidemic of this nature, it's almost impossible not coming into contact with H1N1 in spite of all precautions. Contact with H1N1 is not so much of a problem as proliferation is.

While you are still healthy and not showing any symptoms of H1N1 infection, in order to prevent proliferation, aggravation of symptoms and development of secondary infections, some very simple steps - not fully highlighted in most official communications - can be practiced (instead of focusing on how to stock N95 or Tamiflu):

1. Frequent hand-washing (well highlighted in all official communications).

2. "Hands-off-the-face" approach. Resist all temptations to touch any part of face (unless you want to eat, bathe or slap).

3. Gargle twice a day with warm salt water (use Listerine if you don't trust salt). H1N1 takes 2-3 days after initial infection in the throat/ nasal cavity to proliferate and show characteristic symptoms. Simple gargling prevents proliferation. In a way, gargling with salt water has the same effect on a healthy individual that Tamiflu has on an infected one. Don't underestimate this simple, inexpensive and powerful preventative method.

4. Similar to 3 above, clean your nostrils at least once every day with warm salt water. Not everybody may be good at Jala Neti or Sutra Neti (very good Yoga asanas to clean nasal cavities), but blowing the nose hard once a day and swabbing both nostrils with cotton buds dipped in warm salt water is very effective in bringing down viral population.

5. Boost your natural immunity with foods that are rich in Vitamin C (Amla and other citrus fruits). If you have to supplement with Vitamin C tablets, make sure that it also has Zinc to boost absorption.

6. Drink as much of warm liquids as you can. Drinking warm liquids has the same effect as gargling, but in the reverse direction. They wash off proliferating viruses from the throat into the stomach where they cannot survive, proliferate or do any harm.

All these are simple ways to prevent, within means of most households, and certainly much less painful than to wait in long queues outside public hospitals.

Friday, August 14, 2009

What is AppDomain and Storing and Retriving data from App Domain




We all know that with the launch of .Net framework there has been lot many new things. One of the new features is “AppDomain”. What are appdomins (application domains)? Before that let us first understand what processes are. Processes are physically isolated memory and resources are needed to maintain themselves. Also every process has at least one thread. With .Net Microsoft has introduced another extra layer of abstraction or isolation with in the processes called as AppDomain. The AppDomain is not a physical isolation but rather a logical isolation with in the process. This means that we can have a single process hosting multiple appdomains.

Why You Should Use AppDomains?

AppDomain can be use to load and Assembly dynamically, and the entire AppDomain can be destroyed, without affecting the Process. I think this illustrates the abtraction/isolation that an AppDomain gives us.

How to store and retrieve data from app domain. Here is the code

class Program
{
static void Main(string[] args)
{
AppDomain objDomain = System.AppDomain.CurrentDomain;
string Name = "MyApp";
string Value = "My Application Domain";
objDomain.SetData(Name, Value);
Console.WriteLine(objDomain.GetData(Name));
Console.ReadLine();
}
}

Wednesday, August 12, 2009

Bridge pattern in C#



Intent


The Bridge pattern is used for decoupling an abstraction from its implementation so that both of them can vary independently.

Non-Software Example:

A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, simple two-position switch, or a variety of dimmer switches



Benefits:

With bridge pattern the interface and implementation details are decoupled, which means that the implementation of the abstraction (Switches in our example) is often done at run time. So with the given scenario the selection of type of switch whether “pull chain switch” , “two position switch” can be delayed until the switch is actually wired.




The above diagram shows the UML of the Bridge pattern. Below is the explanation of for the UML

Abstraction: The abstraction class acts as a base class for redefined abstractions. Objects of this type hold a reference to the particular implementation that they are using for platform-specific functions. You may find this little difficult to understand, but as you move on you relate the example to this it will be clear.

RefinedAbstraction: Many redefined abstraction may inherit from the abstraction. Each of these inherited classes will have their own very specific implementation.

ImplementationBase: This is the base class for the concrete implementation. This class can be an interface. This class does will not be having Implementation and also shares a relation with Abstraction class.

ConcreteImplementation: The concrete Implementation inherits from the Implementation base. This can be different for different clients.

Once we relate the above diagram with the software example below thing will be clearer.

Software Example & Explanation of Code:

A software example for Bridge pattern would be a system sending messages. The system has an option to either send the messages through email, web service or through MSMQ. When we are asked to design a system like we can think of one base class “MessageSenderBase” and three other classes like “EmailSender”, “MSMQSender” and “WebServiceSender” classes. Like factory pattern we can give the option to the client (lets say a windows client) to instantiate an object of any of the derived classes and instantiate the derive class accordingly. This will work fine.

Let us say that the requirement changed and we need to support the mail sending components for UNIX also. Now with the above implementation we will have to add new classes and make all the changes in the client, derived classes etc. Now let us look at the implementing the same with bridge pattern. Below is the UML for this




Let us define the above classes one by one. Let us start with the “MessageSenderBase” Class. If you compare the pervious UML this would be the Abstract class. Below is the cod for “MessageSenderBase”

MessageSenderBase.cs

namespace BridgePatternConsole
{
public abstract class MessageSenderBase
{
public abstract void SendMessage(string title, string details, string importance);
}
}

The classes which implements the “MessageSenderBase” are “EmailSender”, “WerserviceSender” and the “MSMQSender”. If you compare these classes it will become equivalent to “RefinedAbstraction” of above previous UML. Below are the code snippet for all the


EmailSender.cs

namespace BridgePatternConsole
{
public class EmailSender : MessageSenderBase
{
public override void SendMessage(string title, string details, string importance)
{
Console.WriteLine("Webservice Message " + "Title-->" + title + " Details-->" + details + " Importance-->" + importance); }
}
}

MSMQSender.cs

namespace BridgePatternConsole
{
public class MSMQSender : MessageSenderBase
{
public override void SendMessage(string title, string details, string importance)
{
Console.WriteLine("Webservice Message " + "Title-->" + title + " Details-->" + details + " Importance-->" + importance);
}
}
}

WebserviceSender.cs

namespace BridgePatternConsole
{
public class WebserviceSender : MessageSenderBase
{
public override void SendMessage(string title, string details, string importance)
{
Console.WriteLine("Webservice Message " + "Title-->" + title + " Details-->" + details + " Importance-->" + importance);
}
}
}


Next is the Message Class. This is equivalent to “ImplementationBase” class of the previous UML. This class does not have any implementation. This has three properties “title”, ”Details” and “Importance”. This also has a fourth property which holds a reference to an implementation object. The class will also include a “Send” Method that calls “SendMessage” of the referenced class. Below is the code for the class

Message.cs

namespace BridgePatternConsole
{
public class Message
{
public string Title
{get; set;}

public string Body
{ get; set; }

public string Importance
{ get; set; }

public MessageSenderBase MessageSender
{ get; set; }

public virtual void Send()
{
MessageSender.SendMessage(Title, Body, Importance);
}
}
}


Finally the subclass for the Message that has an additional property. The equivalent class for this in the previous UML is “ConcreteImplementation” This property can be use to provide additional information to the user. The class is specific to windows message sender. The benefit is that when there is a change where we want the UNIX client to speak to the same that also can be achieved here. Below is the code for the

WindowsMessager.CS

namespace BridgePatternConsole
{
public class WindowsMessager : Message
{
public string WindowsComments { get; set;}
public override void Send()
{
string strCustomString = "This is from Windows" + WindowsComments;
MessageSender.SendMessage(Title, strCustomString, Importance);
}
}
}

Now we need a client to run the application. Create a console class and put the below code

MessageSenderBase objEmail = new EmailSender();
MessageSenderBase objMSMQ = new MSMQSender();
MessageSenderBase objWebService = new WebserviceSender();

Message objMessage = new Message();
objMessage.Title = "Message Title";
objMessage.Body = "Message Body";
objMessage.Importance = "Low";

objMessage.MessageSender = objEmail;
objMessage.Send();

objMessage.MessageSender = objMSMQ;
objMessage.Send();

objMessage.MessageSender = objWebService;
objMessage.Send();


WindowsMessager objWindows = new WindowsMessager();
objWindows.Title = "New Message";
objWindows.Body = "Message Body";
objWindows.Importance = "high";
objWindows.WindowsComments = "Test Comments";

objWindows.MessageSender = objEmail;
objWindows.WindowsComments = "Additional Windows Comments";
objWindows.Send();
Console.ReadLine();




Output of the class would look like

Webservice Message
Title-->Message Title Details-->Message Body Importance-->Low
Webservice Message
Title-->Message Title Details-->Message Body Importance-->Low
Webservice Message
Title-->Message Title Details-->Message Body Importance-->Low
Webservice Message
Title-->New Message Details-->This is from Windows Additional Windows Comments
Importance-->high

Tuesday, August 11, 2009

Perseid Meteor Shower Peaks August 12th, 2009



Every year in early August, we can observe the Perseid meteor shower (“the Perseids”). And it’s a fascinating sky event.

Here’s a beginners’ guide to what it is and how best to enjoy it. (Perhaps, impress your friends with these astronomy questions and answers!)

What are the Perseids and what is a meteor?


Every year in August, the Earth passes through rock and dust fragments left behind by the comet Swift-Tuttle, last time it came near the Sun. As these small particles collide with the Earth’s atmosphere, they burn-up, often creating a startling streak of light across the sky.

You can easily observe this and it can be a wonderous spectacle.



Above: A Perseid fireball photographed August 12, 2006, by Pierre Martin of Arnprior, Ontario, Canada

Why is it called the Perseid meteor shower?

The term “Perseid”, refers to the star constellation of Perseus.

The meteors actually have nothing to do with the stars we see from Earth, as being part of Perseus. It just appears as though the meteors originate from Perseus.

In fact, the rock fragments are close to the Earth – that’s why they burn in our atmosphere.

They are very close, just a few hundred miles – not many, many light years distant like the stars.

But, if you trace-back the bright trails of meteors we see, they appear to originate from the stars of Perseus.

When can you see them?

The Perseid meteor shower actually starts in late July and runs to late August. However, the best time to view is around the peak.

It’s not precise, but the 2009 peak is expected on August 12th at around 15.00 hours UT. There is some uncertainty, so it’s very worthwhile to observe either side of this.

In particular for European observers, the hours of darkness either side the peak hours, may well prove more fruitful! So try the previous Tuesday night, as well as the night of Wednesday 12th.

And there is also a potentially prominent Moon to contend with. It will not set below the horizon until the early hours of the morning.

What equipment do you need to observe the meteor shower?

The good news is none! Just use your eyes.

It will help your observation if you give your eyes some time (say 15 minutes), to become adapted to the darkness.

Binoculars my also help, but on the other hand, they may restrict your view to a small part of the sky.

The meteors originate in the region of Perseus, but they may appear in view just about anywhere in the sky. Although, if you were to track-back their trails, you would get to Perseus.

Can they be measured, at all?

Yes. Keen astronomers count how many appear in a fixed period of time, in a certain area of the sky. This is expressed as a Zenithal Hourly Rate (ZHR).

We may expect around 100 streaks of meteor light across the sky per hour, at or near the shower peak.

Do watch out for them on Wednesday 12th August and during hours of darkness, before and after.

googlec6743be8951630b1

googlec6743be8951630b1

The contract name could not be found in the list of contracts implemented by the service



Problem Description

Recently while on WCF and adding a new service I have received the below error

The contract name could not be found in the list of contracts implemented by the service

Resolution that worked

Missed the [ServiceContract] attribute on the Interface. After adding up that it started working.

Cipla has launched a new drug against Swine Flu



Cipla has launched a new drug against Swine Flu (Virenza), as an alternative option to Osetalmavir drug. Please find attached herewith the availability centers.

Monday, August 10, 2009

Configuring SQL Server Reporting Services 2005 & 2008 in same machine




When opening the Reporting Services Configuration Manager attempting to connect to a local instance, no instances are available in the Report Server Instance drop down list, and on click of the Find button i have received the below message

"No report servers were found.Details:Invalid Namespace"

Have tried using the server name (with and without domain), localhost and . in the server name field and all return the same error.

The report server is operational as I am able to deploy and run reports and connect to both the report server and manager.

The old 2005 reporting services configuration tool (I have 2005 and 2008 installed side by side, 2005 is the default instance) can connect quite happily to the 2008 reporting services instance, but obviously cannot configure from there. When you open the SQL Server Configuration Manager, select the reporting services service / properties and click the configure button it opens the 2005 tool instead of the 2008 one.

Can connect to the instance using Management studio

More feedback can be found here http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3741006&SiteID=1

Comments
This is a known problem that occurs in certain scenarios with RS 2008 named instance when it coexists with SQL RS 2005 side by side and Microsoft are working on fixing this issue.

The workaround to fix this is

1. Open the ReportingServices.mof file and remove "RS_" from the namespaces.
For ex: If your instance name for RS 2008 is "SQL2008", replace

#pragma namespace ("\\\\.\\root\\Microsoft\\SqlServer\\ReportServer\\RS_SQL2008")

With

#pragma namespace ("\\\\.\\root\\Microsoft\\SqlServer\\ReportServer\\SQL2008")

2. Run command "MOFCOMP" from the command prompt by supplying the reportingservices.mof file name as parameter
Note that the above workaround will not solve your problem if the instance name contains any special characters. For those scenarios you need to recreate a RS 2008 instance without using special characters.

Source Link: http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=362738

Sunday, August 9, 2009

Precautions to keep away swine flu at Work Place



The deadly Swine Flu has reached the Indian shores following the global outbreak and now, claimed four lives. However, Swine Flu is certainly one of those diseases where an ounce of prevention is worth a pound of cure. Here are ten tips for you to keep away from the pandemic.

1. Wash your hands frequently

Use the antibacterial soaps to cleanse your hands. Wash them often, at least 15 seconds and rinse with running water.

2. Get enough sleep

Try to get 8 hours of good sleep every night to keep your immune system in top flu-fighting shape.

3. Drink sufficient water

Drink 8 to10 glasses of water each day to flush toxins from your system and maintain good moisture and mucous production in your sinuses.

4. Boost your immune system

Keeping your body strong, nourished, and ready to fight infection is important in flu prevention. So stick with whole grains, colorful vegetables, and vitamin-rich fruits.

5. Keep informed

The government is taking necessary steps to prevent the pandemic and periodically release guidelines to keep the pandemic away. Please make sure to keep up to date on the information and act in a calm manner.

6. Avoid alcohol

Apart from being a mood depressant, alcohol is an immune suppressant that can actually decrease your resistance to viral infections like swine flu. So stay away from alcoholic drinks so that your immune system may be strong.

7. Be physically active

Moderate exercise can support the immune system by increasing circulation and oxygenating the body. For example brisk walking for 30-40 minutes 3-4 times a week will significantly perk up your immunity.

8. Keep away from sick people

Flu virus spreads when particles dispersed into the air through a cough or sneeze reach someone else nose. So if you have to be around someone who is sick, try to stay a few feet away from them and especially, avoid physical contact.

9. Know when to get help

Consult your doctor if you have a cough and fever and follow their instructions, including taking medicine as prescribed.

10. Avoid crowded areas

Try to avoid unnecessary trips outside.