CodeProject

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 :)

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 :)

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.

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.

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 :)

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.

Dear Reader,

In this article I am going to explain about a small tool which I have developed as my personal project for a couple of weekends in between my busy schedules. This small tool, which I like to call it as BoxCop is basically a static analyzer just like FxCop. I conceived this idea when I was working with FxCop for a quite some time at work. I would not even claim that this tool is any where similar to FxCop in terms of supported feature.

A Bit History:

Basically I was working with FxCop for a week or so at work place because I am supposed to fix all the FxCop violations in our production code. While doing so, I found many codes which were doing a lot of boxing operations (confirmed by looking into IL most of the time). We already know that this operation is really a big pain if used extensively. So at that time I started to look if FxCop does support this rule so that we can refactor it so that boxing is minimized. But I did not find any, may be fxcop purpose is not for this? No idea.

You might have noticed from my past blog articles that I do spend a lot of time looking at IL for learning purposes. So I was doing the same and I got the idea of developing this small (tiny) tool which could save at least as small as 1% of a programmers/reviewers time.

Please download either of below packages:

Source code : BoxCop (Source code) – DotNET 3.5

Binaries: BoxCop DotNet 3.5 Binaries

Note: The source code package has been uploaded in .doc format due to wordpress issues. Please save it as .zip package or change the extension from .doc to .zip of the above files when downloaded.

Introduction:

I started to think of developing a small tool (tiny you may call) which could help me to find my mistakes itself in my code in the first place. So as said already boxing is one of those mistakes (not always though) I might do in my code.

You might argue now that boxing is not always harm. Yes it’s not, if you use it wisely. Many times it so happens that we programmer due to many reasons write code urgently and finish off the task but fail to see if what we did is really worthy. You might think that these flaws are easily caught when you ask your code to be reviewed by some body. But not always effective I would say. Because your reviewer is not the person who has written the code in the first place, the reviewer may try to understand your code as much as possible, but due to his/her reasons some things may be overlooked.

It’s always pain to review an old code which your suppose to do refactoring on it because it’s not documented properly? The original programmer is no more available? ,etc. But you got to do it.

Any ways, I do agree that boxing is not the only reason for refactoring a code. But it could be one of those pitfalls you might look for.

How it works:

The application analyses the assembly which is given as input and its associated PDB file in searching for boxing instructions in IL as well as related source code information in the PDB file. This tool searched for all the methods defined in each module or types in an assembly and for each of those methods collected, its equivalent pdb information is fetched. Once both of the data is collected, it aggregates the result as per required format which is displayed over UI.

 Let me show you few screenshots of the application:

The above screenshot shows the basic UI window of this tool. First the user has to select an assembly by clicking the browse button.

Once the .NET assembly (exe or dll) is selected, the selected file path is shown on the UI. Hovering mouse on the path shows the complete path (if path is too long) as shown in the above image.

Once assembly is selected, you need to then press analyze button. Once it is clicked, the tool analyzes the assemblies for boxing instructions. The tool automatically tries to look for the pdb information for the selected assembly in the same location internally. In case of pdb is missing, the tool reports an error as shown:

Upon selecting correct assembly with valid pdb information, the tool successfully analyses the assembly for all the boxing instructions for each method in each module and type in an assembly. Once analyses are done, the UI list view displays all the information needed as shown:

screen131

As you can see from the above image, the list view component on the UI displays detailed information about boxing instructions usage in your C# code.

The first column simply displays a serial number, second displays Namespace.Class information, third column displays Method name and the last column displays information about source code path and line, column information appended to it.

You can export the above UI output to a csv format by right clicking on the listview component as shown in below image and selecting Export to CSV menu item:

screen14

Upon selecting the context menu, a save file dialog is displayed as shown:

When Save is clicked, the report is exported and a success message box is displayed to the user.

In case of any exceptions or crashes generated by this application, a log is created with file name  BoxCop.log present in the same location as of this application.

As of now, it supports only target assemblies built for 32 bit .NET 3.5 or earlier frameworks. Any non compatible assemblies selected, the tools displays an error as shown below:

Before using this tool, please make sure following steps are taken care off:

  • .NET 3.5 framework is installed but not 3.5 client profile
  • All dependency assemblies for the targeted assemblies present in the same directory as the targeted assembly.
  • All pdb files are present in the same directory as the assemblies and are updated.

Internal Details:

This section explains in detail about the code parts which this tool uses internally. So if you are non-techie, it may no more interest you.

This tool has 3 parts in it:

  1. BoxCop
  2. ILCodeAnalyzerLib
  3. PDBDataReader

BoxCop: This module is responsible for all the UI components associated with this tool.

This module has following components in it:

  • BoxCopForm: UI form which is only responsible for displaying UI components and handling related events from the components.
  • AnalyzeAssembly: This component is responsible for invoking all related methods for analyzing assemblies and getting pdb information from related modules.
  • AnalyzedData: This component is just a helper component to hold all the collected data which is used to display in the UI.

ILCodeAnalyzerLib: This module is responsible for analyzing, reading all the IL instructions from the assembly.

This module has following components:

  • AssemblyLoader: This component just loads the selected .NET assembly into memory via reflection. It also checks for availability of the pdb file associated with this assemblyThe above method loads the assembly into memory. If there is any problem related to it, an error is sent back. It also checks for pdb information in the same location as of assembly.
  • AssemblyReader: This component just finds all the methods available in the assembly modules and types. Once it is collected a list is built to hold all the information for further analysis.The above code gets all the method in an assembly module and type wise. Once all methods are found, it builds up a MethodInfo list having all the details about a method. This list is later used to get further information about each method.
  • ILInstructionFormat: This component is just a helper class which just holds all the required format of IL instructions.
  • MethodBodyAnalyzer: As the name suggests, this component just analyzes all the method body having MSIL instructions. It reads the method body code as a byte array and then converts the byte array to an appropriate IL instruction sets.The above method reads and analyzes the IL byte array. Each opcode which is in byte value is identified from a standard dictionary of opcodes value based on singlebyte or double byte. Single byte instructions are like nop, break, ldarg, etc. where as double byte instructions are ceq, stloc, etc.
  • OpCodesBuilder: This component is a singleton class which exposes 2 dictionary which holds single byte and double byte MSIL

PDBDataReader: This module is responsible for reading the program debug data base file (.pdb) of an assembly. It uses OLE32 native calls to read this file.

Following are the components in this module:

  • PDBReader: This component is responsible for invoking ole32 native calls to fetch the source information from pdb file for specific method. This component collects all the data viz. Source Lines, Columns, End lines, Source code location, etc.
  • NativePDBReaderWrapper: This component wraps all the native calls to ole32.dll. The native calls are used to get all the source information which is stored in the custom format file called .pdb (Program Database).

Hope you liked it. Your comments/votes are much appreciated.

Happy Coding. Thanks.

Following are few activities which I will be carrying it out in next couple of days if possible:

To Do:

  • Improve design of the classes where ever necessary.
  • Add features if needed and if feasible
  • Make it bug free ;)
  • Central repositories of error strings either in app.config or resource.
  • Unit test cases, although i have done few system tests to test the tool. Its working fine for all production code.
  • Compiler warnings and FxCop fixes if any.

Feel free to:

  • Submit bug via blog comments or email. Do not forget to provide as much details as possible.
  • Improving the design/code. Kindly, keep me updated on the same.
  • Fixing bug yourself. Again keep me updated.
  • Any better ways to do? Add a comment.

References:

Thanks to the following article authors which helped me alot in building this tool.


http://www.codeproject.com/KB/cs/sdilreader.aspx


http://sorin.serbans.net/blog/index.php/2010/08/10/how-to-read-pdb-files/

Dear Reader,

Today i learned some thing from my architect @work place which i would like to share with you all. In fact i was reviewing some code and there i saw a class having singleton implemented but not in a traditional way in other words we developers more often implement singleton pattern for static (sealed)/non-inheritable classes as shown below:

 public class SingletonClass
    {
        private static SingletonClass _instance = new SingletonClass();

        static SingletonClass() { }
        private SingletonClass() { }

        public static SingletonClass Instance
        {
            get
            {
                return _instance;
            }
        }
    }

As you might be thinking, the above pattern is much of a standard one used by most of us right. But this class what i was reviewing had a protected ctor in it instead of a private ctor. Infact until now i did not know there could be a singleton pattern which can be implemented this way. I had always thought that singleton is implemented mostly for non-inheritable classes (static/sealed) but not for classes which are in inheritance heirarchy. So as you might expect this strange code confused me and i started to discuss the same with my architect.

Lemme show you a sample code:

   public class SomeBase
   {
       private static SomeBase _instance = new SomeBase();

       static SomeBase(){}
       protected SomeBase()
       {
           Console.WriteLine("Base");
       }

       public static SomeBase Instance
       {
           get { return _instance; }
       }
   }

   public class SomeChild : SomeBase
   {
       private static SomeChild _instance = new SomeChild();

       protected SomeChild()
       {
           Console.WriteLine("child");
       }
       static SomeChild(){}

       public new static SomeChild Instance
       {
           get
           {
               return _instance;
           }
       }
   }

The above singleton implementation surprised me actually and its pretty cool to see and learn that singleton pattern is quite different in a non-inheritable vs inheritable classes. We actually do this style when we want singleton in inheritance hierarchy. It’s actually like hitting 2 birds with 1 stone. This is why i guess OOPS is lovable :)

Although in the above pattern implementation there is a small catch, the base protected ctor gets called twice, so one must be careful in implementing or having any initialization code in the ctor.

There is also another catch here is that, the base classes singleton pattern is of no use if its sub-classes has not implemented singleton pattern in itself. That way, one can take advantage of actual intentions here in other words even though my intention of the base class was to be a singleton but due to inheritance and due to sub-classes not implementing singleton, i can create many instances of the base class via sub-class.

Now assuming that the inheritance is implemented with complete singleton, i am actually wondering where in our real world design problem such scenarios could get deployed? If you know, kindly leave a comment.

Hope you liked it, your comments are always appreciated.

Happy Coding :)

Dear Reader,

Further to my first post here, today i noticed some thing cool with respect to Using blocks in C#. We all know that in using block, usually we create a type which implements IDisposable as shown below:

public class MyClass : IDisposable
   {
       public void Dispose()
       {
           Console.WriteLine("Disposed");
       }
   }

And the usage code looks like:

using (MyClass m = new MyClass()) { }

Infact all these days i have been doing the same w.r.t using() blocks in all my code. But today i learned (yes a real shame) that you need not always create a type, rather call a method in it actually. Lemme show you a code on the same:

public class MyClass : IDisposable
   {
       public void Dispose()
       {
           Console.WriteLine("Disposed");
       }
   }

   public class UsingClass
   {
       public static MyClass SomeMethod()
       {
           return new MyClass();
       }
   }

    public partial class Program
    {        
        public static void Main()
        {
            using (UsingClass.SomeMethod()){ }

            Console.ReadLine();
        }    
    }

Here, compiler has gone a bit smart here because it efficiently sees that the return type of the method SomeMethod() is returning a type which implements IDisposable, hence it does not issue any error. Just remove the type implementing IDisposable, then you would get error.

Your comments are welcome :)

Happy Coding.

Dear Reader,

Again as with my code reviews one of the thing i noticed in many classes is that they all have properties with only set accessors but either no get accessor at all or with a private get accessor.

Although if you think for a sec, it sounds good to have many times a writable property but not readable. Infact even i had the same notion many a times while writing code so far. But one thing i realized or learned today that such a feature is really not needed or its kinda of not worthy to have in your code. The reason is simple that consumer code using your property can set a value for your private variable, so when he can set a value that means he already knows the value so why to make your property a read only?

As of now you may think that “OK? but what if i change this private variables value once the consumer code set a value to it”. Let me show you that in a code:

    class CustomClass
    {
        private string _someValue;

        public string MyProperty
        {
            set
            {
                _someValue = value;
            }
        }

        public void SomeMethod()
        {
            if (!string.IsNullOrEmpty(_someValue))
            {
                //Do some operations
               _someValue = string.Concat(_someValue, " some other values");
            }
        }
    }

    class TestClass
    {
        public void TestMethod()
        {
            CustomClass cs = new CustomClass();
            cs.MyProperty = "My values";

            cs.SomeMethod();
        }
    }

If you are planning to do this, then you are having a flawed design actually. When your receiving a value from consumer into your class, then you should not change it or use it to store it, rather use other member to store the data. This way, a guy who is having rights to set a data will also have rights to get (read) a data. That way you shall have a more good design implemented. Because if you do not do this, later on if consumer calls a method which may return this set value along with other data (say as a List<TVal>) then your giving the consumer code wrong information.

Along with this, i do not see any better security added to your data in your class at all right? Think for a moment. The only reason you implement properties to have a better security is mostly for not giving writable access. But here in this case, you already gave away the most critical part of the security and now your trying do a small work in making it secure which is not really useful.

Hope it helps, your comments are welcome.

Happy coding, thanks :)