Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, January 10, 2012

Descriptive Text for Enums

While working on an windows application, I came to across an interesting problem, which is of trivial in nature. I had a drop-down (combo box) control which was populated with field names from an Enum, which is acting as a container for designation values. The problem with Enums were, the field names can't contains spaces, where as the actual designations did contain spaces. This made the end users feel a bit odd, the way which values were listed in the drop-down control. So putting some thoughts on this, I came up with a solution, which did hit the bulls eye. So here's how I did it.


First I need a container to hold this descriptive text, for this an attribute class called "EnumDescription" was defined to hold the string
[AttributeUsage(AttributeTargets.Field)]
public class EnumDescription : Attribute
{
    public EnumDescription(string Value)
    {
        if (!string.IsNullOrEmpty(Value))
            Description = Value;
        else
            throw new NullReferenceException("EnumDescription not provided");
    }

    public string Description { get; set; }
}

Next I started decorating the enum fields with the previously created attribute class "EnumDescription"; this allowed me to pass descriptive text to the enum fields, which helped me get past the .NET enum field naming contsraint.
enum Designations
{
 [EnumDescription("General Manager")]
 GeneralManager = 1,

 [EnumDescription("Project Manager")]
 ProjectManager,

 [EnumDescription("Technical Manager")]
 TechnicalManager,

 [EnumDescription("Group Project Manager")]
 GroupProjectManager,

 [EnumDescription("QA Manager")]
 QAManager,

 [EnumDescription("Accounts Manager")]
 AccountsManager,

 Designer
}
Next step of the puzzle is to read the string contained in the custom attributes. For this a simple custom attributes reader was implemented, but when I ran a unit test against the code snippet, it failed. The reason being, some enum fields doesn't require custom attributes as the designation names they represent didn't contain spaces. The code snippet I had written, now need to deal with enum fields with and without custom attributes, i.e; the catch here is to return the value contained in the EnumDescription, if the attribute is defined, else the field name itself should be returned.

public static string GetText(Enum e)
{
 string ReturnVal = string.Empty;
 EnumDescription oEnumDescription = null;

 if (e != null)
 {
  FieldInfo oFieldInfo = null;
  oFieldInfo = e.GetType().GetField(e.ToString());

  if (oFieldInfo != null)
  {
   object[] CustomAttribs = oFieldInfo.GetCustomAttributes(typeof(EnumDescription), false);

   if (CustomAttribs != null && CustomAttribs.Length >= 1)
   {
    oEnumDescription = (EnumDescription)CustomAttribs[0];
   }
  }

  if (oEnumDescription != null)
   ReturnVal = oEnumDescription.Description;
  else
   ReturnVal = e.ToString();
 }

 return ReturnVal;
}


Now the problem of getting descriptive text is sorted out. The next piece of the puzzle is how to set enum value based on the custom attribute text value? for this a SetText method was written, which will accept the value to be set, either based on the description or on the field name.

public static T SetText<T>(string Value) where T : struct
{
 T ReturnVal = default(T);
 EnumDescription oEnumDescription = null;
 bool DescriptionFound = false;

 if (!string.IsNullOrEmpty(Value))
 {
  //iterate through all the enum fields and check for the given Value in the EnumDescription
  foreach (FieldInfo fld in typeof(T).GetFields())
  {
   object[] CustomAttribs = fld.GetCustomAttributes(typeof(EnumDescription), false);

   if (CustomAttribs != null && CustomAttribs.Length >= 1)
   {
    oEnumDescription = (EnumDescription)CustomAttribs[0];

    if (oEnumDescription != null &&
     oEnumDescription.Description.ToLower() == Value.ToLower())
    {
     DescriptionFound = true;
     ReturnVal = (T)Enum.Parse(typeof(T), fld.Name);
     break; //we found the matching field so exit the foreach loop
    }
   }
  }

  //If no attribute with the given text was found, look for field names
  if (!DescriptionFound)
  {
   foreach (FieldInfo fld in typeof(T).GetFields())
   {
    if (fld != null &&
     fld.Name.ToLower() == Value.ToLower())
    {
     DescriptionFound = true;
     ReturnVal = (T)Enum.Parse(typeof(T), fld.Name);
     break; //we found the matching field so exit the foreach loop
    }
   }
  }
    
 }

 if (!DescriptionFound)
  throw new ApplicationException("Invalid description or field name: " + Value);

 return ReturnVal;
}

with these two methods in place I can now access and assign Enum descriptive text to Enums.
Here's a the code snippet which I used to test my two methods.
class Program
{
 static void Main(string[] args)
 {
  Designations SelectedDesig;
  string Value;

  SelectedDesig = Designations.GeneralManager;
  Value = EnumStringReader.GetText(SelectedDesig);
  Console.WriteLine("GetDescription: " + Value);

  SelectedDesig = EnumStringReader.SetText<Designations>("Designer");
  Console.WriteLine("SetEnum from Description: " + SelectedDesig);
 }
}
You can download the sample C# project from this link.

Tuesday, July 5, 2011

Good News for .NET Reflector Users

The good news is that, Red-Gate had bowed down to the developer community request by making .NET Reflector v6 available free of cost. It was a sigh of relief, when I came to read about this in their forum

If you have ever used this tool for debugging applications, I would say this is something which any ace .NET developer couldn't live without. It is that crucial from a developers point of view, especially while trying to pin point the root cause of hard to find bugs.

While the bad news is that, Red-Gate has released .NET Reflector v7 with lot of enhancements and bug fixes. For those sticking with the v6 is going to miss all those goodies packed with the new commercial version. 

I was thinking, if the productivity gain from using .NET Reflection is that good, then why not shell out some bucks to get a copy for myself as its only 30$ per dev box. Seems like marketing guys had priced it appropriately to get us hooked. 

Anyhow lets hope, one day Red-Gate is going to make .NET Reflector available as free download, once they recover the expenses incurred in acquiring the tool from Lutz Roeder'sTill then happy debugging...

Thursday, January 6, 2011

C# Snippets - Get CLR Version Info

While having a chit chat with my friend, our discussion got on with, the different versions of C# and CLR and how do they stack up. For me its was something new to hear that the CLR version 3 actually didn't exist at all, instead Microsoft had released service packs for CLR, to contain the changes that came in .NET Framework v3.0 and above. Here is a list of C# and CLR version mapping details which I had collected from other sources.


Framework  CLR and Assemblies            Release
----------------------------------------------------------
1.0 RTM    1.0.3705.0                    Visual Studio .NET (aka VS.NET 2002)
1.0 SP1    1.0.3705.209
1.0 SP2    1.0.3705.288
1.0 SP3    1.0.3705.6018

1.1 RTM    1.1.4322.573                  VS.NET 2003
1.1 SP1    1.1.4322.2032
1.1 SP1    1.1.4322.2300                 Windows Server 2003

2.0 RTM    2.0.50727.42                  VS2005 RTM
2.0 RTM    2.0.50727.312                 Windows Vista
2.0 SP1    2.0.50727.1433                VS2008 RTM and .Net 3.5 RTM
2.0 SP2    2.0.50727.3053                VS2008 SP1 and .Net 3.5 SP1
2.0 SP2    2.0.50727.4016                Windows Vista SP2 and Windows Server 2008 SP2
2.0 SP2    2.0.50727.4927                Windows 7

Framework  CLR           New assemblies
----------------------------------------------------------
3.0 RTM    2.0 RTM       3.0.4506.30     The only "out-of-band" non-SP framework release
3.0 SP1    2.0 SP1       3.0.4506.648    VS2008 RTM and .Net 3.5 RTM
3.0 SP2    2.0 SP2       3.0.4506.2123   VS2008 SP1 and .Net 3.5 SP1

3.5 RTM    2.0 SP1       3.5.21022.8     VS2008 RTM and .Net 3.5 RTM
3.5 SP1    2.0 SP2       3.5.30729.01    VS2008 SP1 and .Net 3.5 SP1
3.5 SP1    2.0 SP2       3.5.30729.4926  Windows 7

Framework  CLR and Assemblies            Release
----------------------------------------------------------
4.0 RTM    4.0.30319.1                   VS2010


If you are interested to know the CLR version which your application is running on, use the following C# snippet to get hold of the CLR version information.


Console.WriteLine(typeof(object).Assembly.ImageRuntimeVersion);

Thursday, December 30, 2010

C# Snippets - Display Console application parameters

The other day while working with a console application, we had to log all the parameters passed on to the  application. Here is a single line code to fetch all parameters passed onto the application.


Console.WriteLine(String.Join(", ",Environment.GetCommandLineArgs()));

C# Snippets - Get executing method name

Recently while working on a C# application we had a requirement like, every method should log its name when called. Here is the solution I came up with to output the method name. The Utils.DispMethodName() utilizes the StrackTrace .Net class to get the method name from which it was invoked from.


using System.Diagnostics;
public static class  Utils
{
  public static void DispMethodName()
 {
    string MethodName;
    string ClassName;
    MethodName = (new StackTrace(true)).GetFrame(1).GetMethod().Name;
    ClassName = (new StackTrace(true)).GetFrame(1).GetMethod().ReflectedType.Name;
    Console.WriteLine("Invoking " + ClassName + "." + MethodName);
 }
}

public class Alpha
{
 public void Foo1()
 {
   Utils.DispMethodName(); 
 }
}
Now, if you were to create an instance of class Alpha and invoke method Foo1(), this would print out "Alpha.Foo" to screen.

Thursday, June 3, 2010

Exploring Main() in C#

In a typical Win32 .NET application you could find that the entry point always point to the Main method, be it Console or Windows application. Out of curiosity I thought of digging into the internals, to see whether is it possible to map the entry point to a method name different from "Main". So to start off with, lets take the infamous HelloWorld sample for demo purpose.

Listing - 1

   1:  using System;
   2:   
   3:  namespace HelloWorldNamespace
   4:  {
   5:      public class Program
   6:      {
   7:          public static void Main()
   8:          {
   9:              Console.WriteLine("Hello World...");
  10:          }
  11:      }
  12:  }

Here in listing 1, you could see the Main method being the entry point as usual; before proceeding have you ever tried renaming the "Main()" to something of your choice?, If so, definitely the compiler would have stopped from compiling the application saying like "The Entrypoint Main() not found". So c'mon lets alter this code to get the entry point name mapped to something different. Before starting off, I strongly recommend using Notepad++ for working with the code listing discussed in the article, as we are going to deal with multi-file assemblies.


Listing - 2

   1:  using System;
   2:  using System.Reflection;
   3:   
   4:  namespace HelloWorldNamespace
   5:  {
   6:      public class Program
   7:      {
   8:          public static void MyEntryPoint()
   9:          {
  10:              MethodBase method = MethodBase.GetCurrentMethod();
  11:              Console.WriteLine(method.Name + ": Hello World...");
  12:          }
  13:      }
  14:  }


In listing 2, you could find the same code as in Listing 1 being retrofitted with some new additions like, the entry point had been re-named to MyEntryPoint, while a new type MethodBase is being implemented for printing out, the method name during application execution, this for ensuring that the MyEntryPoint method name is not being altered or overwritten by the compiler nor by the runtime behind the scenes. 


So lets compile the above code snippet from "Visual Studio command prompt", before this save the code in listing 2, to a file named "HelloWorld.cs". Key-in the commands in listing 3, to the "VS.NET Command Prompt" and make sure the location in console window is set to where the source code is located.


Listing - 3











csc /target:module HelloWorld.cs
al HelloWorld.netmodule /target:exe /Main:HelloWorldNamespace.Program.MyEntryPoint /out:Helloworld.exe  


(If you find working with the VS.NET command prompt cumbersome; like opening up the program from deep inside the start menu item and thereafter navigating to the source code location, I recommend reading this article.)
If you are familiar the commands and parameters in listing 3, you can straight away proceed to "Executing Application" section. In case if you find the commands in listing 3 unfamiliar? Let me give you a sneak preview. The commands CSC and AL are provided by .NET framework SDK, where "CSC" is the "CSharp Compiler", while the "AL" is the "Assembly Linker". Lets analyze the Listing 3, line by line. 


Listing - 4




csc /target:module HelloWorld.cs



In listing 4, you can find the first line from taken from listing 3. Here the csharp compiler(CSC) is passed with two parameters. The first parameter "/target:" instructs the compiler to generate a ".netmodule". While the second parameter "HelloWorld.cs" specifies the file name of source code as input. On execution the CSC generates  a file named "HelloWorld.netmodule" in the same directory as of "HelloWorld.cs".


Listing - 5
al HelloWorld.netmodule /target:exe /Main:HelloWorldNamespace.Program.MyEntryPoint /out:Helloworld.exe

In listing 5, you can find the second line from taken from listing 3. Here we are calling the "Assembly Linker" to generate an executable by referring the previously generated "HelloWorld.netmodule". From the the above listing you could find four parameters being passed to "AL.exe". The first parameter instructs to reference the HelloWorld.netmodule which was generated in the preceding step (Listing - 4). While the second parameter is a '/target:' flag which instructs to generate an console application. The Third parameter '/Main:' is where the entry point mapping happens, here we are specifying the method to be called in replacement of Main method. You can find fully qualified path to the method being passed in the following format {Namespace.TypeName.MethodName}. Finally in last parameter, the "/out:" flag where the name of the executable is mentioned as "HelloWorld.exe".



Executing Application
Voila, we are done with. Now you can execute the application and see the output. The output should be similar to listing 5, if you have used the same name for your entry-point.


Listing - 6




MyEntryPoint: Hello World...



Inside Story
So now we have an assembly with the entry point mapped to a different method name than that of the default Main(). Lets peek inside the HelloWorld.exe Assembly using "Red-Gate Reflector" and see, how this entry point re-mapping works.


Peeking inside the Code
Here is a screenshot from Reflector, of the HelloWorld.exe.




In the above screen shot from "Red-Gate Reflector", you can see two different modules namely HelloWorld.exe and HelloWorld.netmodule. You can find a method named "_EntryPoint():Void" the one highlighted in the screenshot, which does the job of pointing to the  entry-point of our choice. In the Disassembler window; you can see the C# code that does this mapping.


Main Program Variants
Its common to see the Main() method container type being used inside a Reference-Type most of the time. But did you know that, its possible to use "Struct"in place of "Class" container? Here in the below code listing you could find "struct" being used in place of "class", which is perfectly legal.




Listing - 7
   1:  using System;
   2:   
   3:  namespace HelloWorldNamespace
   4:  {
   5:      public struct Program
   6:      {
   7:          public static void Main()
   8:          {
   9:              Console.WriteLine("Hello World...");
  10:          }
  11:      }
  12:  }

So thats it. Truth to be told, If you were you ask me whats the benefit of this remapping Main() with a custom method name? I am clueless on this, if you happen to know any benefits on aspects relating to security or obfuscation, please let me know.


Wednesday, May 12, 2010

Generic Delegates

With the introduction of Generics in .Net, the task of declaring delegates got much simplified. Before this we had to declare a pretty big list of delegates for every callback methods and thereafter creating instances of each delegate. This seems a bit dragging due to the repetitive nature of declaring and instantiating delegates. Here let me show you the usual way of declaring delegates.

    public class DelegateDilemma
    {
        private delegate void Delg_NotifyUser(string Message);
        private delegate void Delg_OpsComplete(int StatusCode,string Message);
        private delegate void Delg_BroadCast(string Message,bool Success);
        private delegate void Delg_OpsFailed(int StatusCode, string Message);
        private delegate void Delg_OpsCancelled(int StatusCode, string Message);
        private delegate void Delg_OpsStarted(int StatusCode, string Message);
        private delegate void Delg_OpsPaused(int StatusCode, string Message);

        // CB = callBack
        private Delg_NotifyUser CB_NotifyUser;
        private Delg_OpsComplete CB_OpsComplete;
        private Delg_BroadCast CB_BroadCast;
        private Delg_OpsFailed CB_OpsFailed;
        private Delg_OpsCancelled CB_OpsCancelled;
        private Delg_OpsStarted CB_OpsStarted;
        private Delg_OpsPaused CB_OpsPaused;

    }


Here you could find most delegates being declared and thereafter being instantiated. Lets cut-short this way of writing delegates with fewer lines of code.


I decided to write a generic utility class for handling delegates. This made the task of declaring delegates much simplified. Here is the code for the GenericDelegate utility class.

public static class GenericDelegate
{
    public delegate void Delg_Mthd();
    public delegate void Delg_Mthd<P1>(P1 Val1);
    public delegate void Delg_Mthd<P1, P2>(P1 Val1, P2 Val2);
    public delegate void Delg_Mthd<P1, P2, P3>(P1 Val1, P2 Val2, P3 Val3);
    public delegate void Delg_Mthd<P1, P2, P3, P4>(P1 Val1, P2 Val2, P3 Val3, P4 Val4);
    public delegate void Delg_Mthd<P1, P2, P3, P4, P5>(P1 Val1, P2 Val2, P3 Val3, P4 Val4, P5 Val5);

    public delegate R Delg_Proc<P1, R>(P1 Val1);
    public delegate R Delg_Proc<P1, P2, R>(P1 Val1, P2 Val2);
    public delegate R Delg_Proc<P1, P2, P3, R>(P1 Val1, P2 Val2, P3 Val3);
    public delegate R Delg_Proc<P1, P2, P3, P4, R>(P1 Val1, P2 Val2, P3 Val3, P4 Val4);
    public delegate R Delg_Proc<P1, P2, P3, P4, P5, R>(P1 Val1, P2 Val2, P3 Val3, P4 Val4, P5 Val5);
}


The only limitation I came to see with GenericDelegate class was that, the developer won't be able to call parameters with Ref and Out keywords in their parameters. While the params keyword can be used with the only limitation that, you need to pass values as an array instead of passing as individual parameters. 


In the following code snippet you can see how the GenericDelegate class is being put to use, in place of creating delegates for each and every callback methods.

namespace DelegatesGeneric
{
public static class GenericDelegate
{
    public delegate void Delg_Mthd();
    public delegate void Delg_Mthd<P1>(P1 Val1);
    public delegate void Delg_Mthd<P1, P2>(P1 Val1, P2 Val2);
    public delegate void Delg_Mthd<P1, P2, P3>(P1 Val1, P2 Val2, P3 Val3);
    public delegate void Delg_Mthd<P1, P2, P3, P4>(P1 Val1, P2 Val2, P3 Val3, P4 Val4);
    public delegate void Delg_Mthd<P1, P2, P3, P4, P5>(P1 Val1, P2 Val2, P3 Val3, P4 Val4, P5 Val5);

    public delegate R Delg_Proc<P1, R>(P1 Val1);
    public delegate R Delg_Proc<P1, P2, R>(P1 Val1, P2 Val2);
    public delegate R Delg_Proc<P1, P2, P3, R>(P1 Val1, P2 Val2, P3 Val3);
    public delegate R Delg_Proc<P1, P2, P3, P4, R>(P1 Val1, P2 Val2, P3 Val3, P4 Val4);
    public delegate R Delg_Proc<P1, P2, P3, P4, P5, R>(P1 Val1, P2 Val2, P3 Val3, P4 Val4, P5 Val5);
}

    public class GenericDelegateDemo
    {
        GenericDelegate.Delg_Mthd DlgProc0;
        GenericDelegate.Delg_Mthd<string[]> DlgProc1;
        GenericDelegate.Delg_Mthd<string> DlgProc2;
        GenericDelegate.Delg_Proc<string,string,string> DlgProc3;

        public GenericDelegateDemo()
        {
            DlgProc0 = DisplayNothing;
            DlgProc1 = DisplayParams;
            DlgProc2 = Display;
            DlgProc3 = GetFullName;
        }

        public void InvokeDelegates()
        {
            DlgProc0();
            DlgProc1(new []{"Alpha","Beta"});
            DlgProc2("Hello");
            Console.WriteLine(DlgProc3("George","Allen"));
        }

        private void Display(string Message)
        {
            Console.WriteLine(Message);
        }

        private void DisplayParams(params string[] Message)
        {
            foreach (var s in Message)
            {
                Console.Write(s + ", ");
            }
            Console.WriteLine("");
        }

        private void DisplayNothing()
        {
            Console.WriteLine("Nothing");
        }

        private string GetFullName(string FirstName,string SecondName)
        {
            return FirstName + " " + SecondName;
        }
    }
}

You can see the code now looks much leaner, while declaring and instating delegates, which made me quite satisfied with the solution.


Microsoft Solution for Generic Delegates
While browsing through the MSDN documentation, I happened to see a similar kind of solution for the very issue we had just discussed. The solution comes with two different types of inbuilt delegates namely Action and Func. The Func being for creating delegates with return types, while the Action for delegates with void return type and with a single parameter.

Lets see how to put to use the Func and Action keywords for implementing Generic Delegates.


public class MSFTGenericDelegates
{
    Action DlgProc0;
    Action<string[]> DlgProc1;
    Action<string> DlgProc2;
    Func<string,string,string> DlgProc3;
    Func<string, bool> DlgProc4;

    public MSFTGenericDelegates()
    {
        DlgProc0 = DisplayNothing;
        DlgProc1 = DisplayParams;
        DlgProc2 = Display;
        DlgProc3 = GetFullName;
        DlgProc4 = IsValidInt;
    }

    public void InvokeDelegates()
    {
        DlgProc0();
        DlgProc1(new []{"Alpha","Beta"});
        DlgProc2("Hello");
        Console.WriteLine(DlgProc3("George","Allen"));
        Console.WriteLine(DlgProc4("1"));
    }

    private void Display(string Message)
    {
        Console.WriteLine(Message);
    }

    private void DisplayParams(params string[] Message)
    {
        foreach (var s in Message)
        {
            Console.Write(s + ", ");
        }
        Console.WriteLine("");
    }

    private void DisplayNothing()
    {
        Console.WriteLine("Nothing");
    }

    private string GetFullName(string FirstName, string SecondName)
    {
        return FirstName + " " + SecondName;
    }

    private bool IsValidInt(string IntVal)
    {
        int Result;
        return int.TryParse(IntVal, out Result);
    }
}

In the above code snippet, the Action delegate is used to declare delegates with for containing methods with parameters of void return types while the Func delegate for holding methods with return types as well as parameters. 


The Action and Func delegates behind the scenes implements generic delegates with multiple parameters, here you can see a screenshot of disassembled code from the Red-Gate .NET Reflector.






I wish, if I knew this inbuilt delegates beforehand, I could have saved some time on more productive tasks. Anyway I am glad to find my generic delegate solution similar to what Microsoft had provided.

Friday, May 7, 2010

Implementing "Extension Methods" for Reversing Strings in C#

While working with strings in C#, to my surprise I couldn't find any inbuilt function to reverse a string. I decided to take on this trivial task.


Before starting out, I was curious to know what really are strings made up of? In .Net, the System.String class is an array of System.Char datatypes, which could hold Unicode values. The string class can hold values which is only limited by the amount of physical memory available.


What is an Extension Method?
Before we move on, If the term "Extension Methods" sounds new to you; then here is concise definition. The "Extension Methods" provides a way to extend existing inbuilt .Net classes, with you own set of methods without sub-classing or recompiling the types. You can accesses your extension methods just like any other methods defined by the type, with the only limitation that you won't be able to access the member variables or internal methods defined inside the type. This feature was introduced with C# version 3.0. If you want know more about extension methods visit MSDN.


What really are Extension Methods at its Core?
The Extension Methods are normal static methods, decorated with the "[Extension]" attribute, by the compiler. If you want to explore further, visit Scott hanselman's blog


So let me show you my very first string reversing extension method.


public static class Utils
{
    public static string Reverse(this string Val)
    {
        bool Proceed;
        
        Proceed = (Val != null);
        Proceed = Proceed && (Val.Length > 1);

        if (Proceed)
        {            
            char[] Chars = Val.ToCharArray();
            Array.Reverse(Chars);
            Val = new string(Chars);
        }

        return Val;
    }
}

Here in the above code snippet, you could see I am using the "Array.Reverse()" method to reverse the character array and passing back as string. 


To my satisfaction, i thought of writing my own reverse function using loops, i.e; WITHOUT using the Array.Reverse() method. 


public static class Utils
{
    public static string Reverse(this string Val)
    {
        bool Proceed;

        Proceed = (Val != null);
        Proceed = Proceed && (Val.Length > 1);

        if (Proceed)
        {
            char[] Chars = Val.ToCharArray();

            for (int i = 0; i < Chars.Length / 2; i++)
            {
                char a = Chars[Val.Length - i - 1];
                Chars[Val.Length - i - 1] = Chars[i];
                Chars[i] = a;
            }

            Val = new string(Chars);
        }

        return Val;
    }
}

The only difference between the first code snippet over this one is that, there is a "For" loop that loops through half of the given characters and does a character swap, pretty simple.


After having two Reverse functions, i got myself in a dilemma on which one to use. There came the idea to evaluate performance aspect of both the methods. I did a performance benchmark by  passing huge string values to both the extension methods and logged the time it took to reverse a string. From the results you could see that, the custom string reverse function, i.e; the one using "For" loop, is clearly the winner while dealing with huge strings.


If you want to try out the benchmarking test for yourself. I am posting the code, which i had used to benchmark the string reverse methods. Please note, while executing the below code snippet, might throw an OutOfMemory exception on machines with low RAM. I had executed this code on a system with 4 GB RAM, on which everything went perfectly fine.

class Program
{
    static void Main(string[] args)
    {
        string str1 = "abcdefgijklmnopqrstuvwxyz";
        string str2 = "abcdefgijklmnopqrstuvwxyz";
        DateTime DT1Start, DT1End;
        DateTime DT2Start, DT2End;
        TimeSpan DT1, DT2;

        for (int i = 0; i < 22; i++)
        {
            str1 += str1;
            str2 += str2;
        }

        Console.WriteLine("CustomReverse Array.Reverse");

        for (int i = 0; i < 25; i++)
        {

            DT2Start = DateTime.Now;
            str2.Reverse1(); //Array.Reverse
            DT2End = DateTime.Now;
            DT2 = DT2End.Subtract(DT2Start);

            DT1Start = DateTime.Now;
            str1.Reverse(); //Custom Reverse
            DT1End = DateTime.Now;
            DT1 = DT1End.Subtract(DT1Start);


            Console.Write(DT1.Milliseconds.ToString().PadLeft(6) + " ms");
            Console.WriteLine(DT2.Milliseconds.ToString().PadLeft(13) + " ms");

        }
    }
}

public static class Utils
{
    public static string Reverse(this string Val)
    {
        bool Proceed;

        Proceed = (Val != null);
        Proceed = Proceed && (Val.Length > 1);

        if (Proceed)
        {
            char[] Chars = Val.ToCharArray();

            for (int i = 0; i < Chars.Length / 2; i++)
            {
                char a = Chars[Val.Length - i - 1];
                Chars[Val.Length - i - 1] = Chars[i];
                Chars[i] = a;
            }

            Val = new string(Chars);
        }

        return Val;
    }

    public static string Reverse1(this string Val)
    {
        bool Proceed;

        Proceed = (Val != null);
        Proceed = Proceed && (Val.Length > 1);

        if (Proceed)
        {
            char[] Chars = Val.ToCharArray();
            Array.Reverse(Chars);
            Val = new string(Chars);
        }
        return Val;
    }

}

I really recommend using the custom string reverse method, i.e; the one using "For" loop. If you happen to encounter any issues, please drop me a comment.



Thursday, May 6, 2010

Singleton Pattern With C#

Singleton Pattern, the most widely known and applied pattern in software development circles. The pattern is put to use, whenever you need to share an instance between different contexts in an application. 


The pattern might not be new to most of you; as you might have heard or have experience in implementing for your own projects. Myself after working on this pattern for some time, thought of exploring more into this pattern to get an expert view from industry veterans. The finding were quite profound, as I came to know the language barriers that existed in implementing the Singleton pattern across different languages like C#, Java, and C++. Here I am going to concentrate mostly on C#, while at the same time skimming through some resources on implementing the pattern with C++ and Java.


So now lets get down to the real stuff. The Singleton pattern as everyone knows has different variants with myriad implementations. Here we are going to explore the three different variants of this pattern like Non-thread safe, Thread-safe, and Static Initialization.




Before starting to explore the these variants, lets see the basic guidelines to be followed when designing a Singleton pattern.
  • Make sure that, only single instance of a given class be created in a given AppDomain.
  • Single instance integrity must be guaranteed in a multi-threaded environment.
  • Provide a global point of access to the singleton class.
  • The Singleton class should be prevented from being subclassed. i.e; It must not be inheritable, for this the class should be supplied with the "sealed" keyword.
  • The Constructor should be set to Private and with zero parameters. If going to have parameterized version, you need to get a Factory pattern wrapped on top of this.
  • The member variable whose instance is to be made singleton, must be declared "private" and "static".
  • The method\procedure through which the instance is accessed, must be set to "public static".
  • The Singleton class should manage its own life-cycle including creation and releasing in unmanaged environments.
  • Never use Singleton pattern as a proxy object for maintaining global state in an Application; similar to a global variable.

Now lets start exploring all the different variants of Singleton Patterns, starting with the non-threaded variant aka the basic version.


Non-thread version
This being the basic versions among the available variants of singleton pattern, is seen being applied in academic projects and at times in commercial projects, where reasons could be either due to dead locks issues while using locks or due to nonavailability of locking features for the given language. The downside of using this approach is that, this could compromise on thread safety, which could lead to race conditions, affecting the application integrity and ultimately ending up with corrupted data. 
    Here is a sample code snippet implementing Singleton pattern the non-thread safe way.
    public sealed class Singleton
    {
        private static Singleton _instance = null;
    
        private Singleton()
        {
        }
    
        public static Singleton GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Singleton();
                }
                return _instance;
            }
        }
    }
    I won't recommend the above non-threaded version for use in commercial projects, except for low profile desktop applications.


    Now lets move on to the next variant, the Thread safe one.


    Thread safe Version
    Lets see how to implement the Singleton class in a thread safe way using locks. 
    public sealed class Singleton
    {
        private static volatile Singleton _instance = null;
        private static Object _lock = new Object();
    
        private Singleton()
        {
        }
    
        public static Singleton GetInstance
        {
            get
            {
                if (_instance == null)
                {
                  lock(_lock)
                  {
                    if (_instance == null)
                      _instance = new Singleton();
                  }
                }
    
                return _instance;
            }
        }
    }
    Here you could find the some additions to the non-thread safe version. 


    First of all, a private member variable of object type "_lock" is declared exclusively for locking. By using a separate variable to lock on to, we could avoid dead lock scenarios being raised while accessing the "_instance" variable. 


    Next inside the "GetInstance" method, a lock is engaged before the instance is created so as to avoid multiple threads from executing the critical area where the instance is created. By placing locking code inside the null check condition, prevents locks from being engaged each time when "GetInstance()" is called, there by nullifying the performance overheads associated with locks. 

    Finally the volatile keyword is added to the singleton member variable. This guarantees that, the assignment to the instance variable is completed before the "_instance" variable is being accessed from any threads.

    The advantages of using this approach is that, the instance is created in only when the "GetInstance" method is called for the first time aka Lazy-Initialization, there by avoiding unnecessary instance creations when the application starts.


    Lets move on to the next version of Singleton Pattern the Static Initialization.


    Static Initialization
    I believe this is the most resource efficient way implementing a Singleton Pattern with C# applications, as this gives the advantage of lazy initialization along with freedom of avoiding locks.


    public sealed class Singleton
    {
        private static readonly Singleton _instance = new Singleton();
    
        private Singleton()
        {
        }
    
        public static Singleton GetInstance
        {
            get
            {
                return _instance;
            }
        }
    }


    Here in this version, the "_instance" variable is initialized only when the "GetInstance" member is called. The lock section is also removed from the "GetInstance" member, as now the instance is statically constructed while the class is called. Also the constructor is set to private like that of non-threaded version to restrict instantiation from other classes.
    Generally Static Initialization is not seen to be recommended by Design Patterns, as i came to know from other sources that; in languages like C++ and Java there was some ambiguity around the initialization order of static variables, which proposes a pattern called "Double-Check Locking" for implementing lazy loading in multi-threaded environments. The issue is caused whenever the call to the instance in our case "GetInstance" is first executed even before the constructor code, which is perfectly legal with the Java and C++ memory model, but will cause to break the solution.


    Practical Use
    Its always good to ask yourself this question like, What are the applications of Singleton pattern in a real world scenario. Here I am listing down a couple of application areas for potential use of Singleton pattern.


    Application Instrumentation - This is one area where Singleton pattern is put to use. Usually in applications lots of instrumentation code is being added for analysis and debugging purpose.


    Socket Programming - Here you could apply Singleton Patterns while dealing with ports.


    Hardware Resources - If you were to interface with hardware resource like Serial Port or external devices, its mandatory to have a single point of access to the device, through which the entire communication happen to pass on with.


    Device Spoolers - This is another scenario similar to Hardware Resources where the object should have exclusive access to the given device.


    The Otherside
    Its common to every man made objects in the world to leave room for improvement, so the same applies to this Singleton Pattern too. Here are some resources where you can find the issues and alternatives to this pattern.

    Tuesday, May 4, 2010

    C# Video Tutorials for Newbies

    I came across a resourceful site on C# tutorials for newbies. The site has loads of video tutorials, detailing CSharp features. The video is supplemented with relevant write ups and sample code.

    Thursday, April 22, 2010

    C# Copy Property Values between Types


    For a recent project, i came across a quite weird requirement. The requirement was to copy Public Property values in TypeA to TypeB. The criteria was that both the types should have the same property names, otherwise those properties will be skipped. The second criteria was that, it should copy nested types contained in a given source type. 


    A word of caution. If you have Enums as properties, then both Enums in TypeA as well as in TypeB should share the same numerical values, even if Enum names are different. One more item is that, nested types should have the default constructor, else you should remove the "new()" generic constraint.


    You can use this use the code below, if you come across similar sort of requirements. :)

        public static class Converter
        {
            public static void CopyProperties<T, Q>(T Src, Q Dest)
                where T : new()
                where Q : new()
            {
                foreach (PropertyInfo objSrcPI in Src.GetType().GetProperties())
                {
                    PropertyInfo objDestPI = Dest.GetType().GetProperty(objSrcPI.Name);
                    Object Val = null;
    
                    if (objDestPI != null)
                    {
                        if (objDestPI.PropertyType.BaseType == typeof(Enum))
                        {
                            Val = (int)objSrcPI.GetValue(Src, null);
                            Dest.GetType().GetProperty(objSrcPI.Name).SetValue(Dest, Val, null);
                        }
                        else if (objDestPI.PropertyType == objSrcPI.PropertyType)
                        {
                            Val = objSrcPI.GetValue(Src, null);
                            Dest.GetType().GetProperty(objSrcPI.Name).SetValue(Dest, Val, null);
                        }
                        else if (objDestPI.PropertyType != objSrcPI.PropertyType)
                        {
                            if (!objDestPI.PropertyType.IsValueType &&
                                !objDestPI.PropertyType.IsPrimitive &&
                                objSrcPI.GetValue(Src, null) != null)
                            {
                                Type objDestType = objDestPI.PropertyType;
                                Object objDest = Activator.CreateInstance(objDestType);
                                Val = objSrcPI.GetValue(Src, null);
                                CopyProperties(Val, objDest);
                                Dest.GetType().GetProperty(objSrcPI.Name).SetValue(Dest, objDest, null);
                            }
                        }
                    }
                }
            }
        }
    

    Using the CopyProperties procedure

        class A
        {
            public string FirstName { get; set; }
            public int Age { get; set; }
        }
    
        class B
        {
            public string FirstName { get; set; }
            public int Age { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                A objA = new A();
                B objB = new B();
    
                objA.FirstName = "Alpha";
                objA.Age = 12;
    
                Converter.CopyProperties(objA,objB);
            }
        }