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.


Saturday, October 8, 2011

Implementing a publisher and subscriber with Action Delegate with and without parameters


I usually used to declare a delegate and event as separate declarations to build a publisher and subscriber mechanism. I found an alternate mechanism to accomplish the same
The concept that came to my help was Action Delegate.

  I followed the steps below
1.  Create 2 classes publisher and Subscriber
2.  Declare the Action Delegate in the Publisher class
3.  Hook the action Delegate to the event handler in Subscriber
4.  Raise the event in any of the publisher functions

The example below demonstrates the use of Action delegate with no parameters and Parameterised Action delegates

class Publisher
    {

        /// <summary>
        /// Action delegate without parameter
        /// </summary>
        public Action Completed;

        /// <summary>
        /// Parameterised Action Delegate
        /// </summary>
        public Action<int, string, string> ParameterizedCompleted;

        public void PublishParameterisedAction()
        {

            string str1 = "Hello";
            string str2 = "World";
            StringBuilder builder = new StringBuilder();
            builder.Append(str1);
            builder.Append(str2);
            int length = builder.Length;

            //Raise an event with parameters
            ParameterizedCompleted(length, str1, str2);

        }


        public void PublishAction()
        {
            string str1 = "Hello";
            string str2 = "World";
            StringBuilder builder = new StringBuilder();
            builder.Append(str1);
            builder.Append(str2);
            int length = builder.Length;

            //Raise an event without parameters
           Completed();



        }





    class Subscriber
    {
        

        static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            publisher.Completed += new Action(handleCompleted);
            publisher.ParameterizedCompleted += new Action<int, string, string>(handleTemplateCompleted);
            publisher.PublishAction ();
            publisher.PublishParameterisedAction ();

            Console.ReadLine();
        }

       static  void handleTemplateCompleted(int length,string str1 ,string  str2)
        {
            Console.Write("Result from TemplateCompletedAction" + length + str1 + str2);
        }

      static  void handleCompleted()
       {

           Console.WriteLine("notification recieved");
       }

      
    }



Sunday, October 2, 2011

Use of MSMQ Binding provided by WCF.For Centralized Reliable logging Mechanism.




Msmq Binding is used to communicate to the Service using Microsoft Message Queuing. I have used this binding for transferring log messages. This way we can build a centralised logging system.
For this I followed the steps mentioned below

   1.   Installed Microsoft Message Queuing
   2.   Create a message Queue with Transaction Enabled
   3.   Create a Service


    [ServiceContract]
    public interface ILogService
    {


        [OperationContract(IsOneWay =true )]
        void Log(string Message);


    } 


  Note:if we use NetMsmqBinding we have to mark all operations with in the service contract as OneWay.


  4.Define the implementation


public class MathService:ILogService
    {


        public void Log(string message)
        {


            File.AppendAllText(@"C:\logFolder\AppMessages.txt", message +      Environment.NewLine);


           
        }


    }
  5.Host the Service I have used Self Hosting.




            //Address of the message Queue in the machine -
            // use public with active directory installation
            // in case of Active directory integration . other machines can also access
            // the Queue
            Uri uri = new Uri(@"net.msmq:\\mycomputer\private\testQueue");
         
            //Create Msmq binding with impersonate
            // you may need need to do some thing more if you desire security
            NetMsmqBinding messageQueueBinding = new NetMsmqBinding(NetMsmqSecurityMode .None);


            ServiceHost host = new ServiceHost(typeof(ILogService), uri);
            host.AddServiceEndpoint(typeof(ILogService), messageQueueBinding,uri .AbsoluteUri  );


            //host the WCF Service
            host.Open();




6.Design a Logging Client Application I have used Simple Console Application to demonstrate the same.


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


            Uri uri = new Uri ("net.msmq:\\mycomputer\private\testQueue");
            EndpointAddress  address = new EndpointAddress (uri.AbsoluteUri );
            NetMsmqBinding binding =new NetMsmqBinding (NetMsmqSecurityMode.None );
            ChannelFactory <ILogService> SerChannel = new ChannelFactory<ILogService> (binding ,address );
           
            ILogService client = SerChannel.CreateChannel ();
            client.Log (" This is a log message");
            Console.ReadLine ();
        }
    }