Monday, May 31, 2010

The Super Computing Race

        With the technology moving at a fast pace, countries especially the developed ones are on a stiff competition to catch up with the supercomputing  power they posses. While USA and China had taken the supercomputing to the Peta-flop level, with USA at the forefront achieving a landmark of 1.7 Peta-flops with their Jaguar(Cray) super computer, while China taking the second position with their 1.2 Peta-flop super computer.

       The research laboratories had reveled that, in near future the super computing speeds are going to be taken to Exa-flops level, which could crunch a whopping of one quintillion (one million trillion) calculations per second. The Exa-scale system is proposed to process tons of data sourced from SKA (Square Kilometer Array), which are a series of telescopes spread over hundreds of square kilometers.

    Here in a current release of the biannual supercomputing survey, you can find the Top 500 supercomputers grouped on the basis of Country, OS, Processor and many more parameters.


Friday, May 21, 2010

Business Objects - Crystal Reports

The other day while working with crystal reports for .NET, I was confronted with deployment issues, where "Business Objects - Crystal Reports"  merge modules and redistributable's were missing. After some search all the required components were available from the "SAP" site. You can find Hot fixes, Patches and more in the following URLs


http://resources.businessobjects.com/support/additional_downloads/runtime.asp 
(Packages along with documentation)



https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/bobj_download/main.htm
(Download Links)


Monday, May 17, 2010

Active Desktop Recovery

If you ever happened to encounter the "Active Desktop Recovery" screen on your desktop, which itself is annoying. To make matters worse clicking on "Restore Active Desktop Recovery" won't make any difference. As the issue started to pop up regularly, I thought of documenting the solution.


Before reading on, make sure you have registry access permissions, as most of the steps involves some registry tweaks here and there. So lets move on the solution. 


The following solution worked for me, which I believe should definitely work for you too. 


Step 1:
Delete "Desktop.htt"


1. Key in "." (period without quotes) to the "Start->Run" window.
2. The "Documents and Settings" folder of user login should open up.
3. From there navigate to "\Application Data\Microsoft\Internet Explorer"
4. Delete "Desktop.htt". If you couldn't find the file, make sure "Show hidden files" is turned on.
5. Refresh the desktop. If the error still persists, move on to Step 2.


Step 2: (Before proceeding, make a backup of the registry keys you are about to alter.)
Modify "SafeMode" registry key.
1. Open Registry.
2. Navigate to "HKCU\Software\Microsoft\Internet Explorer\Desktop\SafeMode\Components"
3. Change the DeskHTMLVersion key from 272 to 0 and reboot. The original desktop should now be back.
4. If the error still persists, move on to Step 3.


Step 3: (Before proceeding, make a backup of the registry keys you are about to alter.)






1. Open Registry.
2. Navigate to "HKCU\Software\Microsoft\Internet Explorer\Desktop\SafeMode\General"
3. Delete the value in "Wallpaper" key, which will be "%SystemRoot%\Web\SafeMode.htt".





2. Navigate to "HKCU\Software\Microsoft\Internet Explorer\Desktop\General"
3. Delete the value in "BackupWallpaper" key. 
4. If the error still persists, move on to Step 4.

Step 4:
1. I am out of options, please post your issue with Stackoverflow, Experts-Exchange or Windows forums or with Bytes.



Friday, May 14, 2010

World Time

If you are developer or accounts manager working for a remote client in a different timezone, definitely you need to know their local time before making a call or scheduling a meeting over the web. As a solution to this, most company's put up wall clocks, displaying local time of their clients, which is pretty elegant solution. 

But what if you want to know beforehand the local time of your acquaintances who are geographically located? The solution comes right to you desktop under the title QClock, a freeware desktop based application. The application lists timezones from cities all around the world, which itself is a pretty good list of major cities to choose from.


Here is a screenshot of QClock on my Desktop





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.

Tuesday, May 11, 2010

Online Storage Space

I always wished to have an online storage space which is free of Ads and obviously big enough to hold some Gigabytes and that too certainly free of cost. 

After some search I narrowed down to the best available option, which was Microsoft's SkyDrive online storage service. The Skydrive service allows up to 25 Gigabytes of online storage space for sharing files, images, music, videos and more. To Sign Up for the service you just need to have an Hotmail account and thats it. 

If you aren't impressed with Skydrive, there is handful of commercial services providing more features for a nominal fee, here you can get a comparison of different online storage solutions.

Tips on Remote Desktop

In the day to day life of a IT Professional, Remote Desktops has come up as an single window solution for managing multiple machines at the convince of without leaving your desk. I was pretty impressed with the features it had to offer. During the initial stages, I came to confront some trivial issues like how to Move files, Copy text, Restarting\Shutdowning Remote Desktops etc.

After some research, I got the solution to all those aforesaid issues, so lets move on to the solution part.

Moving Files
If you happen to be in a situation where, you need to copy files to or from a remote desktop. Enable resource sharing, and here's how its done.

1. Open Remote Desktop(enter mstsc in run window)
2. Click on "Options" Button.
3. Next, Click on "Local Resources" Tab.
4. Under "Local Resources" grouping, Check "Disk Drives".



5. Now after establishing a remote desktop session, you could see your local drives listed in the Remote machine under "My Computer", thats it.


Copying Text from Remote Desktop
1. If copying text from Remote desktop session to you local PC doesn't work, then possibly "rdpclip.exe" isn't running in Remote Desktop machine.

2. Well start the "rdpclip.exe" at the Remote Desktop. For this keyin rdpclip into the "Start->Run" window. After you enter this command, you wont see anything coming up on the desktop; thats perfectly fine. To ensure the rdpclip is running, open "Task Manager", and see the whether "rdpclip.exe" is listed under processes tab.

Restarting\Shutdown RemotePC
I was surprised to see the "Shutdown\Restart" option in start menu was missing when working on Remote machine. I believe this feature makes sense, as usually there won't be any one to turn on a remote PC, which may be either in a secured room or in a remote geographical office far away in a different time zone. But at times this could turn up into a nightmare for Developers, QA's and Release teams as well. Enough talking, lets come to the solution part.

To Restart the Remote Desktop, enter the following command in "Start->Run" window.
shutdown -r -f -t 0




Please note before trying out the shutdown command, make sure you have access to the machine physically or some one is available at the other end on call, to switch on. 


To Shutdown the Remote Desktop, enter the following command in "Start->Run" window. 
shutdown -s -f -t 0

The user with you had logged in should have privileges to execute the "shutdown" command.


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.



Discover more about the coveted MVP Programme

If you are the person whose expertise and skills in Microsoft related products or services are applauded and recognized by your employer and colleagues as well; Then definitely you could the one to qualify for this very coveted MVP programme. The MVP awardees gets the unique opportunity to showcase their skills and expertise by sharing with global community at large and moreover backing from Microsoft, to speak up in exclusive events like TechEd, Microsoft webcasts and in other Microsoft conferences.


In this video Abhishek Kant, MVP lead talks on the Professional advantages and benefits of getting the MVP recognition. Watch out.


Get Microsoft Silverlight

Please note, the video requires silverlight plugin to be installed. Doulbe-click the video, if you happen to see a black screen after clicking play button.


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.

    Monday, May 3, 2010

    Refactoring - Nested Code

    Its the dream of every programmer to pen down code that reflects their prowess, but at times this very prowess could end up churning out cryptic\crude coding styles. So, lets see some common practices where refactoring could have scored up on readability and maintainability factors.

    Before we begin with, its imperative to ask; What is "Refactoring" all about?. In short, its all about pruning and grooming existing code into a well structured and well laid format for improved readability and maintainability.
    Here is a sample bloated code snippet that badly needs refactoring. In this snippet an imaginary procedure named "ExecOps" is to be called; but before this, some conditions had to evaluated in an hierarchical pattern and some logging stuff too.

    if(ConditionA())
    {
        Log("ConditionA success");
     
        if (ConditionB())
        {
            Log("ConditionB success");
    
            if (ConditionC())
            {
                Log("ConditionC success");
    
                if (ConditionD())
                {
                    Log("ConditionD success");
                    ExecOps();
                }
                else
                {
                    Log("ConditionD Failed");
                }
            }
            else
            {
                 Log("ConditionC Failed");
            }
        }
        else
        {
             Log("ConditionB Failed");
        }   
    }
    else
    {
        Log("ConditionA Failed");
    }
    
    huh, a pretty deep nested stuff? ok. Seems a question might be lurking in your mind like, why not move all those log calls to those conditions(ConditionA(), ConditionB() etc.); Good question. Let me ask you, what if you are bound from amending those existing conditions(Conditional procedures) or what if, the conditions are from an object's instance to which you don't have access to; either way its going to be risky affair. Please note, amending existing code without proper know-how could end up breaking the system or the build itself. So lets position ourselves on the safer side, by keeping away from making those changes to those existing stuff.

    Now lets get into the interesting portion; Code Refactoring. Here we are going to move those conditional sections to a different procedure with all those logging stuff and not just that; the nested "If" conditions are also going to be flattened out. 
    public bool CheckCondition()
    {
        bool ReturnVal;
    
        var blnFlgA = ConditionA();
        var blnFlgB = blnFlgA && ConditionB();
        var blnFlgC = blnFlgB && ConditionC();
        var blnFlgD = blnFlgC && ConditionD();
    
        ReturnVal = blnFlgD;
    
        if (blnFlgA)
            Log("ConditionA success");
        else
        { Log("ConditionA Failed"); return ReturnVal; }
    
        if (blnFlgB)
            Log("ConditionB success");
        else
        { Log("ConditionB Failed"); return ReturnVal; }
    
        if (blnFlgC)
            Log("ConditionC success");
        else
        { Log("ConditionC Failed"); return ReturnVal; }
    
        if (blnFlgD)
            Log("ConditionD success");
        else
        { Log("ConditionD Failed"); return ReturnVal; }
    
        return ReturnVal;
    }
    
    //Calling the "CheckCondition" function
    if (CheckCondition())
    {
       ExecOps();
    }
    Here in the above code snippet, each function calls return value is stored onto individual flag variable. After which each flag variable is "ANDed" to the next Conditional functions, so as to prevent next function being called if the previous one failed. Finally all those logging stuff are handled based on the individual flag variables. Thats It and now we have trimmed and elegant version of the code.