Decision matrix implementation in C#

Dear Reader,

Yesterday i faced a problem where the combinations possibilities were many and i had to implement code for this problem. Obvious solution is to implement If – else ladder. But i absolute hate this solution because the combination were around 5C3. The combination data was about behavior aspect of a scenario. Next solution is to use Switch block. But this solution involves inner switch combinations. So down the line it gets more complicated.

Next solution was to go for dictionary. But the problem with dictionary is the key uniqueness. In my case, most of the keys were not unique. So either i had to customize the dictionary behavior (List of KeyValuePair) or go for some thing else. The earlier will lead to writing alot of code for small problem and involves more cost factor in terms of development time and testing effort.  Idea rejected.

Then i suddenly remembered to make use of Decision table. So googling a bit to learn more about decision matrix, this is what i could implement which is not just extensible but also easy to understand and easy to add/modify later on. No need to change in the actual code (finding the combo) unless the way to look up methodology changes.

Sample code:

Untitled

At line 27, i am here searching for a combination key of “Condition3” AND “ASC”, then get the result from the matrix. Line 31, have used FirstOrDefault() than First() to avoid exception when result is not found.

Hope it helps,
Thanks,.
Zen :)

Convert 3 digit number to words (TIP)

Dear Reader,

Today i was wandering through Codeproject as my daily routine and found one tip about Converting numbers to word. I actually got interest in it and began to read through and i was surprised how easy code the author has written. As well as i gone through the comments section. People have expressed various views about it as well. I suggest you to read through it.

So after completing the article i wanted to improve the way it is implemented. Of course i do not claim its the best solution. Have put my effort for 2 hours and came up with below code for the same 3 digit scenario.

So at first, i decided to have a lookup table kind of data structure for numbers to words. So i created a dictionary for the same as shown below:

static Dictionary < int, NumbersPositionsInWords > numbersToWordsDictionary =
             new Dictionary < int, NumbersPositionsInWords >();

The value for the dictionary is a class which holds the positions words as shown below:

class NumbersPositionsInWords
    {
        public string zeroPosition;//One, Two, Three
        public string tenthPosition;// Holds Twenty, Thirty, etc.
        public string elevenSeries;//Special words like 11 = Eleven, 12 = Twelve, etc.
    }

After i have this look up table frame being constructed which deals with all kinds of special words in the numbering system, next i need to fill the lookup table with the data. Below .cctor code does the same:

static Program()
    {
       numbersToWordsDictionary.Add(1,
         new NumbersPositionsInWords()
         { zeroPosition = "One", tenthPosition = "Ten", elevenSeries = "Eleven" });

       numbersToWordsDictionary.Add(0,
         new NumbersPositionsInWords()
         { zeroPosition = "Zero", tenthPosition = null, elevenSeries = "Ten" });

       numbersToWordsDictionary.Add(2,
         new NumbersPositionsInWords()
         { zeroPosition = "Two", tenthPosition = "Twenty", elevenSeries = "Tweleve" });

       numbersToWordsDictionary.Add(3,
         new NumbersPositionsInWords()
         { zeroPosition = "Three", tenthPosition = "Thirty", elevenSeries = "Thirteen" });

       numbersToWordsDictionary.Add(4,
         new NumbersPositionsInWords()
         { zeroPosition = "Four", tenthPosition = "Fourty", elevenSeries = "Fourteen" });

       numbersToWordsDictionary.Add(5,
         new NumbersPositionsInWords()
         { zeroPosition = "Five", tenthPosition = "Fifty", elevenSeries = "Fifteen" });

       numbersToWordsDictionary.Add(6,
         new NumbersPositionsInWords()
         { zeroPosition = "Six", tenthPosition = "Sixty", elevenSeries = "Sixteen" });

       numbersToWordsDictionary.Add(7,
         new NumbersPositionsInWords()
         { zeroPosition = "Seven", tenthPosition = "Seventy", elevenSeries = "Seventeen" });

       numbersToWordsDictionary.Add(8,
         new NumbersPositionsInWords()
         { zeroPosition = "Eight", tenthPosition = "Eighty", elevenSeries = "Eighteen" });

       numbersToWordsDictionary.Add(9,
         new NumbersPositionsInWords()
         { zeroPosition = "Nine", tenthPosition = "Ninty", elevenSeries = "Ninteen" });

    }

Once i have full table data, next i have to take the input from the user and validate it as per requirement. The requirement i have assumed here is to have the input in integer format and with no less or greater than 3 digits.

Once i have validated the input, my next strategy is to split the 3 digit number into hundred, tenth and units positions. First i consider the hundred position digit which is 0 index in input string. Once i get 0 index digit, i check if it’s not less than 1 i.e 0, because if input number is 024, then it should not result in as Zero Hundred And Twenty Four rather it should be Twenty Four. Hence i have to check for the 0 index digit (hundred position digit) and then construct the output string as per the lookup table. Below code does the same logic:

int hundredthPostionDigit = GetDigitFromPosition(inputString, 0);
StringBuilder resultString = new StringBuilder();

if (hundredthPostionDigit > 0)
  resultString.AppendFormat("{0}{1} {2}",
  numbersToWordsDictionary[hundredthPostionDigit].zeroPosition,
  string.Empty, hundredString);

Once the basic string (left to write parsing) is constructed, next for me is to consider the tenth and unit position together. This is because, at different conditions (11, 03, etc.) i need to parse and convert to equivalent words. Hence below code does the same:

if (tenthPositionDigit > 1)//For 45, 98, it shud be Fourty Five, etc.
 numberToWordText.AppendFormat("{0} {1}",
 numbersToWordsDictionary[tenthPositionDigit].tenthPosition,
 unitsPositionDigit != 0 ? numbersToWordsDictionary[unitsPositionDigit].zeroPosition :
 string.Empty);

if (tenthPositionDigit < 1)//For 02, 06, 00 it shud be just pick unit digit or none.   
 numberToWordText.AppendFormat("{0}", unitsPositionDigit > 0 ?
 numbersToWordsDictionary[unitsPositionDigit].zeroPosition : string.Empty);

//For 11, 13, 14 it should be special words like eleven, twelve, etc.
if (tenthPositionDigit == 1)
 numberToWordText.AppendFormat("{0}", unitsPositionDigit == tenthPositionDigit ?
 numbersToWordsDictionary[tenthPositionDigit].elevenSeries :
 numbersToWordsDictionary[unitsPositionDigit].elevenSeries);

The appended text could be either empty (in case of 100, 200, 500, etc.) or with valid content like Twenty Five, Ninty One, etc. This text is then consumed back to append to the actual resulting string for display and below code does the same:

if (resultString.Length > 0 && numberToWordText.Length > 0)
  resultString.AppendFormat(" {0} {1}", "And", numberToWordText);
else resultString.Append(numberToWordText);

You can get the full formatted, compilable source code from here: http://ideone.com/LEYQ1

That’s all my friend. I wanted to keep it as simple as possible and i did/wanted to spend very minimal time writing this logic. Thanks goes to the original author from codeproject (article linked above).

Disclaimer: I have not given enough concentration/efforts to make the code more good. I do agree that there is a lot to improve in terms of design? refactoring? Maintainability? Extensibility? etc. I shall aim to improve the code and consult my smart colleagues/friends for suggestions to improve this code then update the same in my blog post.
However please feel free to give your comments/ideas here for my learning’s.

Thanks and Happy Coding,
Zen :)

Refactoring Hooking and Unhooking events TIP

Dear Reader,

Today i was fixing a bug w.r.t event handling. So as part of this there were couple of forms (classes basically) which were trying to hook to an KeyDown events and unhooking upon disposed. Basically the requirement is, for every customized control in the forms/panel, this keydown event should be hooked. So no matter which ever control (child/parent) has the focus, keydown event has to get fired. So as part of this implementation, the code goes like this:

Hooking events:
public void HookingEvents()
{
    IEnumerable < Controls > allControls =
            CollectUIControlsHelper.Instance.CollectAllControls(this);

    foreach (Control ctrl in allControls)
    {
        ctrl.KeyDown += new KeyEventHandler(OnControlKeyDownHandler);
    }
}

UnHooking events (Part of Dispose call):
public void UnHookingEvents()
{
    IEnumerable < Controls > allControls =
           CollectUIControlsHelper.Instance.CollectAllControls(this);

    foreach (Control ctrl in allControls)
    {
        ctrl.KeyDown -= new KeyEventHandler(OnControlKeyDownHandler);
    }
}

As you can see from the above code, its pretty clear that the first method is just collecting all the controls from parent to child from the current form/panel/control via a method CollectAllControls(this). And does the opposite in UnhookingEvents. Do note that these methods are called in any fashion by the usage code. Hence every call has to fetch all the child controls.

Yes i do agree that this code is noting of great. But the annoying thing for me or primary concern for me was to see this code getting repetitive in many forms or classes across my application.

So i wanted to make this above code perhaps more common so that any form which wishes to hook for Keydown events can just reuse this code. As part of that effort, i came up with this simple solution as shown in the below code:

class KeyDownEventsHelper
{
    private static readonly KeyDownEventsHelper m_Instance =
             new KeyDownEventsHelper();

    public static KeyDownEventsHelper Instance
                   { get { return m_Instance; } }

    private KeyDownEventsHelper() { }
    static KeyDownEventsHelper() { }

    public void HookingEvents(Control control,
             Action<object,KeyEventArgs> eventHandler)
    {
        IEnumerable < Control > allControls =
          CollectUIControlsHelper.Instance.CollectAllControls(control);

        foreach (Control ctrl in allControls)
        {
            ctrl.KeyDown += new KeyEventHandler(eventHandler);
        }
    }

    public void UnHookingEvents(Control control,
            Action<object, KeyEventArgs> eventHandler)
    {
        IEnumerable < Control > allControls =
          CollectUIControlsHelper.Instance.CollectAllControls(control);

        foreach (Control ctrl in allControls)
        {
            ctrl.KeyDown -= new KeyEventHandler(eventHandler);
        }
    }
}

As you can see from the above code, it is a singleton class which publishes 2 methods for hooking and unhooking. So as part of the this methods, i have provided a delegate for the event handler to invoke upon any events generated. So each class can provide its own even handlers for hooking.

Now i am feeling a bit relaxed as i could reduce around 8 lines of code getting repeated over in many different forms/classes couple of times. So as of now, i could find 4 classes/forms which are repeating this above code, so thus i could save around 32 lines altogether.

I do agree that there is still alot room for improvement. How ever at the moment i can not foresee those improvements. It would kind and great of you as a reader to suggest me those improvements.

My next concentration would be to refactor the event handlers for KeyDown so that i can minimize the implementation code. May be i shall add a base class to all of those classes which has a virtual method having common code and in the derived i invoke first base and then implement few more code.

Thanks and Happy Coding :)

Update: As part of this refactoring, today i found out few more places in my code base which could reuse this common code, such a way now i could save around 60 lines of raw code getting repeated to just few lines. I am finally happy and satisfied :)

Static in generics

Dear Reader,

Although this topic is quite common, but still i see here and there folks getting confused about the behavior of having a static members in the generic type.

Today i saw another question on stackoverflow about the same. So i thought i shall write a small blog post about the same.

Normally we know that static members are unique for a type no matter how many instance you create of that type. But this concept behaves a bit differently in generics. If you have read the C# spec, then you would have figured out by now. It states some thing like this “For every open type T, the type having static members maintains the common/unique value”.

Let me show you a sample code for explanation:

public class Base
    {
        public static string str = null;

        static Base()
        {
            str = "hello";

            Console.WriteLine("Ctor cald");
        }
    }

As you can see in the above code, the static member by virtue of its nature stays common/unique for this type Base no matter how many derived/base instances are created right. Yep.

But as soon as you introduce generics to this code, things starts to behaves a bit differently. As already stated above, for each open type T (in below code) the base type holds a common static members in it.

Lemme show you a sample code for the same:

public class Base < T >
    {
        public static string str = null;

        static Base()
        {
            str = "hello";

            Console.WriteLine("Ctor cald");
        }
    }

    public class Derived1 < T > : Base < T > { }
    public class Derived2 < T > : Base < T > { }

    public class Program
    {
         public static void Main()
        {
            Derived1 < int > derv = new Derived1 < int >();
            Derived2 < double > derv2 = new Derived2() < double >;
            Derived2 < double > derv3 = new Derived2() < double >;

            Console.ReadKey();
        }
    }

So how many times the static ctor in the above code would be called? 3? No, wrong. In this case, its only 2 times. Because for every open type T you pass (in this case int and double types in main method) the base types static members are maintained unique for that open type T.

If you supposedly run FxCop on your generic type code having static members, you would get this warning. So be careful in using static in generics.

Hope it helps. Thanks for reading.

Your comments/votes are always appreciated :)

Happy coding.

String Concatenation vs Memory Allocation in C# .NET

Dear Reader,

I would like to bring into your attention an old article written on this topic. This article explains alot about strings concatenation and does very good performance analysis.

Here is a glimpse about this article:

Over the years, plenty has been written about string performance, lots of comparisons between String.Concat and StringBuilder. Today I decided to do some of my own research into the subject and contribute to the knowledge already out there. More specifically, I’ll be taking a look at the memory usage for various concatenation methods and compiler optimizations used to generate the IL.

The test scenario I defined consists out of several methods, each returning the same string. The string I created is supposed to resemble a real-life scenario. I identified five different ways of concatenating strings for my test. I will be taking a look at the numbers when calling each method once and inside a very small loop of 50 calls, which is another real-life number in my case.

Single line concatenation.

The easiest way of concatenating strings together, by simply putting a plus sign between them.

public string GetPlussedString()
{
 string myString = "SELECT column1,"
 + " column2,"
 + " column3,"
 + " column4,"
 + " column5,"
 + " column6,"
 + " FROM table1 t1"
 + " JOIN table2 t2"
 + " ON t1.column1 = t2.column1";
 return myString;
}

Although it seems like we are creating 9 string instances, the compiler optimizes this into the following IL:

.method public hidebysig instance string GetPlussedString() cil managed
{
 .maxstack 1
 .locals init (
 [0] string myString)
 L_0000: ldstr "SELECT column1, column2, column3, column4, column5, column6, FROM table1 t1 JOIN table2 t2 ON t1.column1 = t2.column1"
 L_0005: stloc.0
 L_0006: ldloc.0
 L_0007: ret
}

In reality, we created one string instance and returned it, which is about the most efficient way we can achieve.

When profiling the test application, I couldn’t even find a call to GetPlussedString in the profiler, which makes me believe the runtime even optimized this.

In total, our application created 113 string instances and barely used any memory.

Running this in the loop gives the following result:

Important to note is the fact that we still have 113 string instances. This is because .NET used String Interning on my string and simply returns a reference to that instance over and over.

You can read full article here : http://www.cumps.be/nl/blog/commented/string-concatenation-vs-memory-allocation

Thanks, Hope it helps.

Thanks for the original author for this good article.

Internals of Conversion styles in .NET

Dear Reader,

In this post i would like to share some things about Conversion styles in .NET i learned few days back. Basically in this case I am talking about casting any numeric value to an equivalent char type.

There are three ways one can convert one type to another, in this case numeric to char:

  1. Direct Casting
  2. Via Convert helper class
  3. Via IConvertible interface

Lets dig a bit deeper into each of these styles and see its pros and cons if any.

Direct Casting:

This conversion style is the most basic and most efficient one. In this style, the compiler need not to emit any special OpCodes or method calls. Instead it just emits basic OpCodes which does the job efficiently. Basically compiler emits conv.u2 or conv.ovf.u2 OpCode instructions for unchecked and checked operations respectively.

Lets see the IL for this operation:

int value = 99;
char c = (char)value;

For the above code, the IL generated is:

IL_0000: nop
IL_0001: ldc.i4.s 99
IL_0003: stloc.0
IL_0004: nop
IL_0005: ldloc.0
IL_0006: conv.u2
IL_0007: stloc.1
IL_0008: nop
IL_0009: ret

As you can see, there is no extra complex OpCodes being generated nor any method calls. Only opcode which does the actual conversion is generated at IL_0006 line.

Although this style is most efficient one, the only draw back of using this style is that it does not support culture specific conversion in other words you can’t specify IFormatProvider to the conversion operation.

Convert Helper class:

In this style we use Convert class which is a helper class provided by .NET framework class library (FCL).  As you may already know that Convert class is a static class which provides alot of static methods for conversion operations. Since there is a method call in this scenario, so this is considered to be the second most efficient style among others. The Convert methods internally checks for overflow operation conditions by default. Hence when ever there is over flow occurrence, it throws an exception of type OverFlowException.

So in this case, i have used Convert.ToChar(Int32) API. So the code in FCL for this API looks like as shown below:

public static char ToChar(int value)
{
if (value < 0 || value > 65535)
{
throw new OverflowException(
   Environment.GetResourceString("Overflow_Char"));
}
return (char)value;
}

One important point worth remembering here is that, one needs to be careful while using the API Convert.ToChar(Object, IFormatProvider) with valuetypes. Because internally it uses IConvertible interface for conversion which results in low performance issues as explained in the next section.

IConvertible Interface:

In BCL, many basic types viz Int32, DateTime, Char, etc. does implements interface IConvertible. Many other types might as well implement this interface, but it’s of no interest here. One important thing to remember here is that this style of conversion is very poor in performance, since in case of valuetypes the input is first boxed and then conversion is done on it.

Lets see a sample example:

char c = ((IConvertible)95).ToChar(null);

In the above line, Explicit conversion to IConvertible is required, because many types in BCL viz Char, String, Int32, etc. do implements IConvertible methods explicitly.  Looking at the IL for the above code shows the exact problem:

IL_0000: nop
IL_0001: ldc.i4.s 95
IL_0003: box [mscorlib]System.Int32
IL_0008: ldnull
IL_0009: callvirt instance char [mscorlib]System.IConvertible::ToChar(class [mscorlib]System.IFormatProvider)
IL_000e: stloc.0
IL_000f: ret

As you can see in the IL_0003 instruction, the value is getting boxed. Hence this style of conversion is least efficient of all others. So its better to avoid this style.

Now lets proceed to do some performance analysis on all three styles, although from the theoretical aspect from above lines we know their performance costs but still lets prove it with an example to convince fully. Hence i have used the below code:

static Stopwatch sp = new Stopwatch();
static int counter = 10000000;
static int valueToConvert = 70;

public static void Main()
{
    GC.WaitForPendingFinalizers();
    GC.Collect();
    for (int j = 0; j < 3; j++)
    {
        Console.WriteLine("Casting style...");
        StartTimer();
        for (int i = 0; i < counter; i++)
        {
            Char c = (char)valueToConvert;
        }

        StopTimer();
        PrintElapsedTime();

        Console.WriteLine("Using Convert helper method..");
        StartTimer();
        for (int i = 0; i < counter; i++)
        {
            Char c = Convert.ToChar(valueToConvert);
        }
        StopTimer();
        PrintElapsedTime();

        Console.WriteLine("Via IConvertible interface...");
        StartTimer();
        for (int i = 0; i < counter; i++)
        {
            Char c = ((IConvertible)valueToConvert).ToChar(null);
        }
        StopTimer();
        PrintElapsedTime();

        Console.WriteLine("\n\n");
    }
    Console.ReadLine();
}

As you can see from the above test code, i am taking 3 samples of the performance results just to make sure output is quite accurate. Hence from this, i got the below result:

Casting style…
Time elapsed in ms = 22
Using Convert helper method..
Time elapsed in ms = 60
Via IConvertible interface…
Time elapsed in ms = 233

Casting style…
Time elapsed in ms = 255
Using Convert helper method..
Time elapsed in ms = 294
Via IConvertible interface…
Time elapsed in ms = 417

Casting style…
Time elapsed in ms = 439
Using Convert helper method..
Time elapsed in ms = 478
Via IConvertible interface…
Time elapsed in ms = 598

From the above results it is very much clear that the performance issues is much better with the direct casting and acceptable with Convert helper methods in this case.

Hope it helps.

Thanks for reading. Your votes/comments are much appreciated.

Happy Coding,

Thanks, Zen :)

Simple way to build solution with out opening VS (TIP)

Dear Reader,

I learned some thing new (for myself) but could be an old news for you. Any ways just wish to share it with you all in case if you did not know

It may so happen that at times we need to build dependent projects/solutions when we are working on other projects. It’s very clumsy to open those dependents projects/solutions in visual studio and then compile due to time consumption or repeated steps.

 Instead follow this simple yet handy steps as explained below: 

  1. Launch Visual Studio 2008 Command prompt from Start -> All Applications -> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt
  2. Once the command window opens up, type msbuild as command and drag and drop the required csproj or solution file from your views (Windows explorer window) into the command window as shown:
  3. Press enter and your build is started. Its quick and easy. You also can make it a batch script too.
  4. Output is shown on the command prompt itself as shown:

Enjoy, happy coding  :)

P.S: if you are aware of much better idea kindly do let me know.

EDIT: Thanks to @Cdhowie for below tip.

If your on Linux, then you can use xbuild command. If your in the same directory as the solution, then the xbuild command automatically takes it for building (only if one solution is present) with out any additional arguments being passed.