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
[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        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
            ):base(binding,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"));
            Console.WriteLine(client.GetData(10));
            Console.ReadLine();
        }
    }



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
                MessageQueue.Create(@"mycomputer\private$\testQueue");

            }
           
            //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);
                Queue.Send(QueMessage);
                messageindex++;          
            }


            Console.ReadLine();

        }
    }
}

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
            queue.BeginReceive();
            Console.ReadLine(); 
        }

        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);
            Console.WriteLine("--------------------------------");

            //open the queue for recieving
            queue.BeginReceive();


        }
    }
}

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.








Sunday, October 30, 2011

Copying large collections without iteration

I had go through an  interesting  situation where I had to copy items from one collection to another.The problem was that the collection was very large and iterating through it was not a very good option . I solved the problem using the snippet below
This example is just a representation of the problem. In My situation the stack had 100 thousand integers  int .I had to copy it to a ordered list of integers

using System;
using System.Collections.Generic;
using System.Collections;

namespace testCollection
{
    class Program
    {
        static void Main(string[] args)
        {

            //Stack of integers
            Stack<int> stackCollection = new Stack<int>();
            stackCollection.Push(1);
            stackCollection.Push(2);
            stackCollection.Push(3);
            stackCollection.Push(4);
            stackCollection.Push(5);

            //copying the items of stack into the ordered list
            List<int> listCollection = new List<int>(stackCollection);
            Console.WriteLine(listCollection.Count);


   }

   }
}

Iterating through collections without For and Foreach using IEnumerable and IEnumerator


We were using a number of collections holding same type of data. Someone asked me if there is a way to handle these collections in a common way. In other words how do we iterate through different kinds of collection using a common function .I told them we could achieve the same using  a function with IEnumerable<T>  . I demonstrated the same using 3 collections Generic Stack, Queue, and Ordered List.
Following is the code snippet that demonstrates the same

using System;
using System.Collections.Generic;
using System.Collections;

namespace testCollection
{
    class Program
    {
        static void Main(string[] args)
        {

            //Stack of integers
            Stack<int> stackCollection = new Stack<int>();
            stackCollection.Push(1);
            stackCollection.Push(2);
            stackCollection.Push(3);
            stackCollection.Push(4);
            stackCollection.Push(5);

            //Queue of Integers
            Queue<int> queueCollection = new Queue<int>();
            queueCollection.Enqueue(1);
            queueCollection.Enqueue(2);
            queueCollection.Enqueue(3);
            queueCollection.Enqueue(4);
            queueCollection.Enqueue(5);

            //ordered list of integers
            List<int> listCollection = new List<int>();
            listCollection.Add(1);
            listCollection.Add(2);
            listCollection.Add(3);
            listCollection.Add(4);
            listCollection.Add(5);

            //iterates through the stack of items in last in first out manner
            GetItems(stackCollection);

            //iterates through the queue in a fist in first out  manner
            GetItems(queueCollection);

            //Iterates through an ordered list of integers
            GetItems(listCollection);

            Console.ReadLine();


        }

        /// <summary>
        /// generic iteration logic for a collection
        /// </summary >
        /// <param name="collection"> is decided at runtime and instance of a class implementing ienumerable</param>
        public static void GetItems(IEnumerable<int> collection)
        {

            //gets the enumerator
            IEnumerator<int> enumerator = collection.GetEnumerator();
            while (enumerator.MoveNext ())
            {

                //gets the items from the collection
                Console.WriteLine(enumerator.Current);  
            }


        }
    }
}








Thursday, October 20, 2011

Instrumenting code using #if DEBUG #endif Block


Its usually very difficult to debug  a software with large amount of code. People generally writelogs, write traces while debugging code and often forget to remove these .this will result in undesirable messages in production code.
A bad way of instrumenting  code is shown below
static void calleeFunc()
        {

            try
            {

                Trace.WriteLine("in callee func");
                Console.WriteLine("in callee func");

                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ;
            }


The problem with  this snippet is that it displays unnecessary messages when compiled in Release mode.This can also lead to security vulnerabilities
A way to solve the problem is the use of conditional compilation directives provided by c# compiler.
The  #if DEBUG end if block  enables the trace message and console messages in debug mode and strips it of in release mode

   static void calleeFunc()
        {

            try
            {
#if DEBUG

                Trace.WriteLine("in callee func");
                Console.WriteLine("in callee func");
#endif
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ;
            }

        }
The use of the #if debug  #endif block helps eliminate unnecessary debug messages in production(Release Mode code) This way you can stop spending large amount of time in removing code used for understanding or tracing.





Wednesday, October 19, 2011

Re-throwing exceptions Throw Vs Throw ex


Most of us use exception handling very frequently .we generally use try catch finally for handling exceptions.We are often mislead due to bad rethrow of exceptions.
The following snippet shows a bad rethrow
using System;

namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                callerFunc();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();

        }

        static void  callerFunc( )
        {

            try
            {
                calleeFunc();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        static void calleeFunc()
        {

            try
            {
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ex ;
            }


        }

    }

The result of this code is shown below


The information here is totally misleading as it only gives a partial idea of the total stacktrace of the program. The stacktrace is not preserved.

The Solution is to never use Throw ex, instead use only Throw. The following code preserves the stacktrace of the code.

using System;

namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                callerFunc();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();

        }

        static void  callerFunc( )
        {

            try
            {
                calleeFunc();

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        static void calleeFunc()
        {

            try
            {
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {
                throw ;
            }


        }

    }
}


The output of this code preserves the stackTrace totally to get the exact location of the exception.