Saturday, February 11, 2012

Factory Method implementation in C#

 Factory Method

Factory Method is a widely used mechanism for creating instances of classes in any object oriented programming language. The Factory Method abstracts the Creation of objects from the consumer.It also provides a single place where objects can be created.I supplies the desired objects hiding the complexity of creation for the consumers

Advantages of Factory Method

1. Hides the Complexity of Creation from the Consumer.

2. Ensures The object creation logic to be in single place

3. Helps customise creation without disturbing the Consumer logic

4.brings in logical Seperation between creation and usage

I have used a simple CarFactory example to demonstrate the same .The Factory manufactures swift cars of 2 types basic and Featured with 3 different colors black,blue and Red.

Steps for implementing the Factory Method

1.Create an abstract class Swift Car with an attribute color and a method CaliculatePrice as the price differs for different models

2. Create 2 derived classes For Basic Swift Car and Featured Swift Car

3. Define Enumerations which describe the Car types and Car Colors

4. Create a Static Class with a Static Method which Returns the Car of Desired Type
it is very important to keep the abstract base class Swift car as a Return Type.

5. Design a Client to Consume the Car from the Swift Car Factory.

Finally it can be observed that creation logic is unknown to the client and Since the factory takes care of the creation .the Factory logic can be further customised or changed easily.

Tuesday, January 24, 2012

Reading and Updating WCF Configuration file

It had been very long since I had blogged. I had a peculiar requirement where I needed to parse the configuration of a WCF Service. that is the <System.ServiceModel> tag in the configuration file.
I finally came to know that there was a dedicated  namespace System.ServiceModel.Configuration,
Following is code that helps read and update the configuration file

 using system.ServiceModel;
 using system.ServiceModel.Configuration;

Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

//Read the Service Model Tag
ServiceModelSectionGroup SvCGroup =      System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(c);

//get the count of the number of Services and the service Model
Console.WriteLine("Number of Services: " + SvCGroup.Services.Services.Count);
Console.WriteLine("Number of ServiceBehaviours: " + SvCGroup.Behaviors.ServiceBehaviors.Count);

//iterate through the services in the config file
foreach (ServiceElement ele in SvCGroup.Services.Services)

       //Name of the Service
    Console.WriteLine("Service Name -" + ele.Name);

     //The Host Tag
     HostElement hele = ele.Host;
        //iterate through the list of base addresses
     foreach (BaseAddressElement belement in hele.BaseAddresses)
       Console.WriteLine(" Base Address -" + belement.BaseAddress);

       //get the endpoint details
  foreach (ServiceEndpointElement sep in ele.Endpoints)
     Console.WriteLine("------Endpoint -----------");
     Console.WriteLine("Address -" + sep.Address.ToString());
     Console.WriteLine("Binding -" + sep.Binding.ToString());
     Console.WriteLine("Contract -" + sep.Contract);
     Console.WriteLine("Changing Contract to IService2");
     sep.Contract = "IService2";
     Console.WriteLine("DNS -: " + sep.Identity.Dns.Value);

      // get the list of ServiceBehaviour elements
foreach (ServiceBehaviorElement behavelement in SvCGroup.Behaviors.ServiceBehaviors)

       foreach (BehaviorExtensionElement extele in behavelement)

                 //get the service metadata element
        if (extele is ServiceMetadataPublishingElement)

     Console.WriteLine("---------------------------MetaData Behaviour------------------");
    ServiceMetadataPublishingElement behaviour1 = extele as ServiceMetadataPublishingElement;
    Console.WriteLine("Behaviour Name: " + behaviour1.ConfigurationElementName);
    Console.WriteLine("Property HttpGetEnabled: " + behaviour1.HttpGetEnabled);



you can also set back the properties and call the configuration.Save(); to change the config file
 c.SaveAs("ConsoleApplication1.exe.config", ConfigurationSaveMode.Modified);
 this saves on the modified parts of the configuration class. how ever 2 other overloads are    provided.


Sunday, November 27, 2011

Extending ClientBase to Create a WCF Service Proxy

I was trying to explore different ways of creating a proxy to use the service. I knew 3 ways to doing it
1.using SVCUtil.exe
2.using Add Service Reference
3.using ChannelFactory<T> and DuplexChannelFactory<T> classes
As and when I explored that we could also create a proxy by using a wonderful class ClientBase<T>
Here are the steps I followed to create a Proxy using ClientBase<T>
1.Created a Sample service and Hosted in IIS
2.Copy the Service Interface to Client Code
3.Extend the ClientBase<T>
4. Create the proxy in the client and use

1.The Service Interface is as follows
    public interface IService1

        string GetData(int value);

        // TODO: Add your service operations here

The Implementation is as follows
  public class Service1 : IService1
        public string GetData(int value)
            return string.Format("You entered: {0}", value);


2. I copied the Service interface  to the Client Code
3. Extended the ClientBase<T> as Follow
    class ServiceClient:ClientBase<IService1>,IService1

        public ServiceClient(BasicHttpBinding binding, EndpointAddress address

        protected override IService1  CreateChannel()
        return base.CreateChannel();
public string  GetData(int value)
       return base.Channel.GetData(value); 

4.We can Invoke the custom handcoded proxy as follows
class Program
        static void Main(string[] args)
            ServiceClient client = new ServiceClient(new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress("http://mycomputer:61468/Service1.svc"));

Saturday, November 5, 2011

using Microsoft Message Queuing and System.Messaging

Microsoft has provided a wonderful Queuing framework .It is known as Microsoft message Queuing .This can used for data storage during failure at the same time send message between two processes in the same machine or  2 different machine

In case of 2 processes in a local machine we use Private Queue
In case of 2 processes in  2 remote machines we use public  Queues

The message Queue Installation is available in Add remove Windows Components Message Queuing

After installing the same .you will able to  create an use Message Queues
The Queues can be created by following  the steps

1.       Start CompMgmt.msc
2.       You get MessageQueing Sub menu
3.       You can Select  Private and Public Queues and Select  New
4.       Enter the Queue Name
5.       Select  Transactional and Non-Transactional 

6.       The public queue name format is  machine-name\public$\Queue-Name
7.       The private queue name format is machine-name\private$\Queue-Name

I have written an article in this blog that demonstrates a QueueServer and a QueueClient.
The Queue Server pushes the message to a private Queue with name test Queue
The Queue Client Recieves the message and displays it on the console

The Queue stores the messages that is Enqueued and Dequeued in the first in first out order

Messages contain 3  important parts  which I have used
Label –unique id for the message

Formatter – the way in which message is stored it may be binary,text,xml or custom .

Body – The field which stores the message .
The message can be retrieved by the client in Synchronous and Asynchronous fashion
I have used asynchronous mechanism to retrieve the messages in the message queue client side
Following is the example 

Queue Server

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

namespace MessageQueueServer
    class Program
        static void Main(string[] args)
            //create a Queue if it doesnot exists
            if (!MessageQueue.Exists(@"mycomputer\private$\testQueue"))
                //create a message queue

            //instance representing the Queue
            MessageQueue Queue = new MessageQueue(@"mycomputer\private$\testQueue");
            int messagecount = int.MaxValue;
            int messageindex = 0;

            while (messageindex < messagecount)
                //create messages
                Message QueMessage = new Message();
                //unique id for the message
                QueMessage.Label = messageindex.ToString();

                //can be any information
                QueMessage.Body ="m"+ messageindex;

                QueMessage.Formatter = new BinaryMessageFormatter();

                //send the message to the Queue
                Console.WriteLine("pushing message no " + messageindex + "to " + Queue.QueueName);



The code above pushes the messages to the Queue

Queue Client

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

namespace MessageQueueClient
    class Program
        static MessageQueue queue;
        static void Main(string[] args)
            //access the queue
             queue = new MessageQueue(@"mycomputer\private$\testQueue");
            queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);
            //start recieving the message

        static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
            //recieve the message from the Queue and close it until one message is processed
            Message message = queue.EndReceive (e.AsyncResult);
            Console.WriteLine("Message recieved with id:" + e.Message.Label);
            //format the message to retrieve the data
            e.Message.Formatter = new BinaryMessageFormatter();
            Console.WriteLine("Content in the Queue:" + e.Message.Body);

            //open the queue for recieving


The code above is a Queue Client  and receives the messages from the Queue Server      
Run the Queue Server and then the Queue Client and enjoy the example.