Tuesday, December 4, 2007

Crazy Enums

Few days back I got a great opportunity to talk with a senior thoughtworker, Chris. He told me few things related to Agile and NUnit. Apart from this there was one intresting thing that I want to share. Almost all of us have worked with .Net Enums. Let me show you something,
Create a project and add one Enum to it,

enum MyEnum
{
Orange=0,
Red=1,
Green=2
}


Now create another class where we will use this Enum,

class Program
{
static void Main(string[] args)
{
MyEnum obj;
obj = (MyEnum)5;
Console.WriteLine(obj.ToString());
Console.ReadLine();
}
}


Did you noticed something? Our Enum only had 0,1 and 2 as valid values. I went on and assigned 5 to it. Now try compiling this code. Aha! no compilation errors. Now try running this. Everything goes well and 5 gets printed on console. Did you expected this?
I never expected this. Did Microsoft forget about type safety and type checking issues while copying from Java Enums? I think Java enums works fine.
If you ever worked with Bit Flags you will some how realize that all this is due to them. Bit flags can actually take up values which are a combination of values that are defined in Bit Flag Enum. Here is an example:

[Flags]
internal enum Actions
{
None = 0,
Read = 0X0001,
Write = 0X0002,
ReadWrite = Actions.Read Actions.Write
...
}

There are number of threads going on in forums related to this. Just keep this in mind before using Enums.
I am exited about playing EA Game's CRYSIS. I have the DVD and will be installing the game tomorrow. Actually I need to clean up my system a bit before I get on with the game. CRYSIS CD says, "Game needs 20 Gb of free hard drive space."

Currently listening to: Black or White - MJ
~nJoY CoDiNg~

Monday, November 19, 2007

Amazing Graphics..EA Rocks!!!

Check these screenshots of Need for speed Most wanted...amazing graphics...EA Games rocks..









Saturday, November 10, 2007

C# 3.0 - What's new?

Hello! everyone. This is festive time here in India. Yesterday we all celebrated Diwali, festival of light. I must tell you that lot of things have changed, things like playing with crackers, going out with friends and watching the way people decorated their houses using lights and ribbons. Yesterday, after having our Diwali prayer I just watched a movie (CHUCK) @ home and slept at around 11. Nothing new for me and it turned out to be yet another holiday. I wish things remained the same way as they were before.

Now let's talk technology. Microsoft have another a new set of features to C# in its third avatar. There is complete list available at MSDN, but I just wanted to add my comments to it as I study new features one by one. What I am planning is, I'll study one new feature everyday, post it here with my comments.
  1. Implicitly Typed Local Variables
    • Type is inferred by the expression used to initialize the variable
    • Only applicable to local variable
    • Variable declared using keyword 'var'
    • There should be no Type with name 'var' defined in scope. Only then type inferring will work
    • We should initialize the variable where we declaring it
    • Initialized must be an expression.
    • Local variable declaration should not include multiple variables
    • Initializer should not refer to variable itself
    • Some Examples: [ <=> is Same as ]
      var i = 5; <=> int i = 5;
      var s = "Hello";
      <=> string s = "Hello";
      var d = 1.0;
      <=> double d = 1.0;
      var numbers = new int[] {1, 2, 3};
      <=> int[] number = new int[]{1,2,3};
    • Some incorrect use of var:
      var x; // Error, no initializer to infer type from
      var y = {1, 2, 3}; // Error, collection initializer not permitted
      var z = null; // Error, null type not permitted
      var u = x => x + 1; // Error, lambda expressions do not have a type
      var v = v++; // Error, initializer cannot refer to variable itself
    • for, foreach and using (resource acquisition) can also use var. Like,
      int[] numbers = { 1, 2, 3, 4, 5 };
      foreach (var n in numbers) { //Do some thing }
    • COMMENTS
      Why do we need to use var? Everything should be Type Strict. I think this will impact performance as compiler will use some kind of intelligence to find out variable type and it will surely take up some time. This is no scripting language...man this is C#. It will just complicate things even more and add to huge list of keywords that we already have like sealed, virtual, override, abstract, new, internal etc. I don't see any use of this so called added feature.
      Please let me know your opinions.
Currently Listening To: Shadow of the day-LINKIN PARK
~eNjOy cOdinG~

Sunday, November 4, 2007

Debug ASP.net apps on VISTA

There is a lot of criticism going around regarding debugging capabilities of Windows VISTA and Visual Studio 2005. A lot of guys that are using Vista Home (cheapest and all laptops comes with HOME) think that it's only a problem with Vista Home edition and MS must have done this as a marketing gimmick. I think this is not true. Last night I was not able to debug a simple web application on my computer, that's running Windows Vista Ultimate X86 edition. So I just googled for few seconds and solution was in front of me.

You can either go to msdn web Dev blog or check out steps and links given below. Actually all the content that you see below is just copy pasted from above link. So it will be much better if you check out the link.

The Visual Studio team has just released a down loadable hot fix, which fixes problems resulting in such errors, and also enables the ability for Visual Studio 2005 to F5 debug web applications on IIS7 in Vista Home versions.

The following steps should be done to properly configure your IIS7/Vista environment for building ASP.NET web applications using Visual Studio 2005:

  1. Install Visual Studio 2005 SP1
  2. Install Visual Studio 2005 Update for Vista
  3. Install Visual Studio 2005 hot fix for F5 authentication errors
  4. Configure required IIS7 components
  5. Run Visual Studio using the "Run As Administrator" option on the right-click menu
Currently Listening To: What Have I done-LINKIN PARK
~eNjOy LiFe~

Wednesday, October 31, 2007

C# Optimizing Compiler

Let me share nice thing that I noticed about C# compilation model. What I did was, I created a small program to print an Int32 array to console. Then I went into IL and checked out various function calls that C# compiler has made. There was one nice thing that I noticed. C# compiler sometimes optimizes your code by itself. Let me show you,

using System;

namespace Optimization

{

class Program

{
static void Main(string[] args)
{
Int32[] arr ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,11 };
for (Int32 i = 0; i<=arr.Length-1;i++) {
Console.WriteLine(arr[i]);
}
Console.ReadLine();

}

}

}

This is the code that I wrote to print a simple Int32 array. Below is the IL generated by this code snippet.


Compiler stores the array length in line IL_0000. The you can see there is no call to Array.Length property [internally it will call the method get_Length()] which I have used in For loop. Only calls that C# compiler added were to Initialize array, WriteLine() and ReadLine(). C# compiler have optimized our code internally so that there is no need to call Length with every loop iteration. It uses the length that is stored in the beginning to provide a performance boost. So, if you are doing such thing in your code, don't complicate things by declaring a variable just before the for loop just to store array length and use that variable in loop condition. You will be doing that to improve your application's performance but doing such heroics is not needed in this scenario.

I have just started to read about ASP.net internals and currently I am dating HTTPSys driver :). I hope to get this done by November 2nd week.
Currently listening To: SHAGGY Feat. AKON - What's Love
...nJoy CoDiNg...

Tuesday, October 2, 2007

MS Office - One click blog publishing



Hey! guys, do you know how I created this blog entry. I simply wrote some stuff in my new MS Word 2007 and published it with one mouse click to my web blog. It's so damm easy, you only have to set up connection with your blog space provider and your blog account with your MS Word. From then onwards you can just write any content offline and publish it using new utility menu in office 2007. Information given bel;ow is just may be useless to most of you, but this just another document that I prepared long ago. You tend to forget things if you dont use them often :). Take a look at the menu screen shot above:
  • XML
    • Introduction
      • XML vs. HTML
        • xml describe data
        • xml focus on data
        • html display data
        • html focus on how data looks
      • XML
        • Extensible markup language
        • Define your own tags
        • DTD or XML Schema to describe data
      • W3C recommendation

Friday, September 28, 2007

Future peek...

Hey guys! congrats to all of you, INDIA finally won a Cricket World Event. It's a huge surprise for me as they did this without my hero Sachin. They defeated every team except New Zealand. I think in this FaSt-FoOd era , 20-20 matches are here to stay. MS Dhoni appeared to me as a strong captain but as you all know India is a country driven by emotions, one or two series losses can change all this hype that he is getting. At least they won, three cheers for our 20-20 team. Hip hip Hurray!!!!

Its been long time since I wrote something really useful for coding community. Although I haven't yet completed my Vista post and Secure string post, I want to share more of my experiences. I have done some exiting stuff related to VB.NET Macros and CSLA framework. Also, it's a long time since I have been using MS Office 2007. It's a gem of a software and Microsoft's OneNote tool is really amazing. Microsoft have completely revamped office application user interface. It's much more organized now. Other thing in which I am involved right now is configuring my company's Share point site and project web server. My future posts will be centred around CSLA framework and VB.NET macro that I wrote.

Just check this screen shot of MS Word 2007 upper menu bar. 100% WoW factor,

Let's hope I get some time to write my posts.

Have Fun!


Wednesday, September 19, 2007

The Throne

Check this out..I found this funny wallpaper somewhere on web...



Tuesday, September 18, 2007

Process..Thread..Fiber

Franky speaking, how many of us know that a concept of Fibers exists in Windows? I can't see any raised hands :)

Few days back I was checking some thread synchronization stuff on MSDN, that's when I found this strange thing (What Fiber???Which Fiber???Where Fiber???). Let me share my G.K regarding Fibers with you...

Fibers were added to Windows to make life easier for guys trying to port existing UNIX server applications to windows. Actually, UNIX server application works with a single thread but act as multi threaded apps. That is, UNIX server applications are single threaded but can serve multiple clients. Developers creating applications for UNIX have to create their own threading library in order to simulate pure threads. These developer created threading packages contains multiple stacks, persists data in CPU registers and switch among these stacks to give user an impression of multi threading.

Redesigning existing UNIX server applications for Windows can take months to complete. To help companies port their code correctly and quickly to Windows, MS added the concept of Fibers to windows.

Fibers always work in user mode and kernel knows nothing about them. They work according to algorithm that you define i.e. fiber scheduling algorithm is defined by you.

This is just a brief knowledge about Fibers. I don't want to dig deep into it as everything that comes after this is related to windows internals, like WIN32 API calls to convert existing threads to Fibers, allocating stack memory and playing with registers.

So now, if some one asks you a silly question you can ask him to define a Fiber. It will be fun. Anyways, right now I am having some fibre rich breakfast i.e. some honey almond museli with cold milk. Have to reach office within one hour. Hurry up!!

"I am the One" - [ Neo says so in Matrix ]

Sunday, September 9, 2007

Sachin and his LuCk

India lost yet again due to exemplary performance by all three sides, i.e. England, mighty India and Aleem Champions (captain Mr. Aleem Darr). Mr. Aleem Darr should have been declared man of the match for his amazing eyesight which can see some things that a normal human eye can not. Even complex machinery was not capable of identifying things that Mr. Aleem's eye noticed. I think these things happen, but it hurts when it happens to someone like Sachin. For me, cricket means Sachin and Sachin means cricket. I really wanted to jump to Lords and thrash Mr. Darr for his foolish looking decisions. I really don't know how to spell out his name but for making things more clear I can split his name wide open, A LAME DEAR.

Saturday, September 8, 2007

Remember The Name-Fort Minor

Let me show you one of the most amazing music video that I've seen in recent times. Name of the song is Remember the name and it's performed by Fort Minor. Fort Minor is a group starring Mike Shinoda of Linkin Park fame. Mike says Fort Minor is his side project and if such songs are part of side projects then I can't imagine what goes into Mike's major projects. Really nice song and amazing video.


Friday, September 7, 2007

My Flickr Show

This is cool..




Thursday, September 6, 2007

Old days are back again !

You know what, I got my brand new graphics card ( GPU a.k.a. Graphic Processing Unit)

Bought it from US at 79$ i.e. around 3,500 Rs. In India, its about 13,000 Rs. Isn't it amazing??? Nice deal I must say. A friend of mine, Ravi, went to US on official trip. He's the one who bought this one for me. I was bit scary regarding its compatibility with Vista, but all worked fine.

Installation was pretty simple, open your CPU side cover, fix up card in PCI- E slot, blah blah blah, nothing complex in it.

I don't know why manufactures assume that the people buying their products are blessed with a good Internet connection. It's same with every company, be it my beloved Microsoft or XFX. Why can't they [XFX or NVIDIA] supply Vista compatible drivers with the driver CD that came with the package. I have to download that 10 Mb set up package for installing Nvidia GPU drivers on windows Vista. I just don't like this type of marketing. Manufacturers should do everything possible so that their product is completely packaged together. It's like going to a shop for buying pants. You buy a nice trousers, you reach home, you open the package, waiting to try out, but package content reveals that Zip was not available when this pant was manufactured, and you should go and get your zip from so and so location. If they print on their package that product is 100% vista compatible, they should also mention that you will need to download this set up from their support web site. Funny and painful.

Keeping aside all these woes, let me tell you some of the specs:

Stream Processors:16
Shader Clock:900 MHz
Chipset:GeForce™ 8500 GT
Memory Clock :667 MHz
Dual Link DVI - Supporting digital output up to 2560x1600
Memory:256 MB
Bus Type:PCI-E
Memory Type:DDR2
Othe Features
Vista Ready, DVI Out , HDCP Ready , SLI ready , RoHS , HDTV ready

I have installed Need For Speed-Carbon and Quake 4. Amazing graphics and details. I haven't seen anything like this on computer before.

Quake Sceenshots:





















If it's in the game, then it's in the game [EA Sports tag line]
~bLaCkHaWk~

Sunday, September 2, 2007

My life with Vista

I have been using Windows new much hyped Operating System from over 6 months now. Most of the things are nice but there are few areas where it could have improved. I'll try to list them here. These are 100% according to my own experience and my machine configuration and may vary from system to system.

Check out my system information:



Let's start our Vista story,

  1. Driver Drivers Drivers
    This is the worst part of my Vista life. Somethings that worked fine on Xp, were not able to run on VISTA. There are no Vista compatible drivers available for them.

    First thing that I want to list here is my Creative 5.1 Live sound card. I bought this card and a set of Creative 5.1 speakers few months ago. They worked without any trouble on XP. Vista came and all things went off. There were no drivers available for the sound card. I searched a lot, but to my surprise, Creative have decided not to work on Vista drivers for this sound card. I don't know why they didn't want to work on this, but this is just not good. If they converted all their Xp drivers into Vista why leave this product. It's sad. I have tried all generic drivers available but none of them works. Problem is that although I am having 5.1 speakers capable of surround and DTS sound, I have to listen to stereo output. One of my rear speaker is not working. I have decided not to buy any product from creative in future.

    Next came my TV Tuner card. I bought Pinnacle's PCi TV tuner card which according to mighty Pinnacle is (was) 100% vista compatible. I don't know what they mean to say when they write -"this product is 100% vista compatible." Vista didn't even noticed their product. I searched a lot, both on open source websites and Pinnacle driver support, but nothing concrete. I downloaded about 100 mb of different driver packages from Pinnacle that promised to make my TV Tuner work on Vista, but nothing worked. At last, after 1 month of my purchase, some one from Pinnacle responded to my query that i had put on their support site. They provided me the link to appropriate driver. It worked. At least they were better than Creative guys.

    I bought new handset, Motorola E6 smart phone. It's so damn smart that Vista decided to totally ignore it. Motorola USB didn't worked, so no matter what I do, vista never recognises that something known as Motorola Smart phn is attached to my PC. As you all know by now, Motorola USB drivers are not compatible with Vista. I have tried different driver packages but nothing works. I am planning to sell of this phone and buy a Sony Erricson one soon. I heard they are out with their Vista drivers.

    One of my friend, Prashant, bought a new HP laptop with (LOL) Vista OS. He came to my house to get some music. I have a 40 GB USB Hard Drive and we planned to use that to transfer data. I attached that drive to my PC, copied the songs and then attached that drive with my friends laptop. You know what, his Vista didn't recognised my drive. I must say, Vista profiles drivers according to user. That's bad. When we both had Vista Ultimate, this should have never happened.
  2. MS own products are not Vista Compatible
    I count myself as .Net developer and for this I need to have some things that are usually not found on every other PC. These things are Visual Studio and SQL Server. Both these are products developed by Microsoft. I had Visual Studio 2003 and 2005 and both SQL 2000 and 2005 installed on my XP machine. There was a software, a small application, provided by Microsoft to check which of my applications will not run on Vista. To my delight, result showed, none of my application will fail and everything will work fine. I installed Vista, and guess what, both Vista and SQL didn't worked.
    I tried installing SQL 2005 and VS 2005 as it thought, they will work fine. But somewhere Bill Gates was smiling, thinking, Aha Gaurav got Vista and he thinks everything will work fine, how foolish someone can get :) . I ran VS 05 installer and a great looking message box popped up, Hey Gaurav!, I know u want to install VS 2005, I know u have broadband on your machine and I know u will do whatever it takes to keep your Vista, so please download and install this Visual Studio 2005 update from www.microsoft.com, it's just 80 mb in size. Good Luck! Then what, i downloaded that 80 mb, installed it and everything worked fine.
    Next came SQL 2005, and to my horror I needed one vista update and one SQl update to get this going. Download size approximately 300mb. This is not good, Microsoft should have used space left behind on VISTA Ultimate DVD to copy all these required updated for us. I am blessed with a good Internet connection, but not everyone is, so Microsoft and other companies should think about this. 300+80 mb means a lot here in India.

  3. Hardware companies playing the spoil sport
    It's again related to drivers. I don't know what these hardware companies were doing when MS was creating Vista. Were they asleep? I think they were sleeping. Sometimes they don't have drivers and sometimes they say they have them but links that they provide only helps you download some junk to your PC. USB drivers are missing, what's going on guys, wake up else you will be out of market soon. Motorola and Creative are leading contenders this so called ''soon to be out of market" race.
  4. Blue Screen
    I am facing this problem from first day of my Vista life. Boot process just kicks off and Blue screen shows up and it gets restarted again. After trying 2-3 times everything works fine as if this is the best computer with best OS. Earlier message with which that blue screen greeted me was, "Recent hardware change corrupted some thing...", then after few months it got changed to, "PFN_LIST_CORRUPT." Will someone tell me what I am supposed to do. I ran BIOS update for my mother board, but all in vain.
  5. Com Surrogate
    This is another one that I am having from day one. It stopped recently but I don't know how. May be some windows update solved that. It happened when ever I went near to any movie [.avi] files. Some blogs says un-install Nero, but I swear it didn't helped. I hope this is not coming back to me in future.
  6. Windows updates without any bug fix details
    Every week MS guys are ready to patch up Vista with new updates. There is no detail regarding what is being updated. Updates are categorized as Recommended, Security and optional. I hope! every one will agree with me that there should be some sort of release notes attached with these updates.
  7. Internet Explorer Crashes
    Aha! I found a bug in IE. If you try to run multiple You tube videos at the same time in one browser window in separate tabs, IE will crash. I need this fixed as soon as possible. I have started using Firefox for You Tube. Let's hope MS fixes this soon.
  8. Windows Explorer Crashes
    This was some bad software that i installed. It's fixed now.
  9. No Updates for Windows Defender
  10. Which Antivirus should I use?
  11. Folder views are same everywhere
  12. Pinnacle TV Tuner wakes up when Vista is sleeping

    I'll keep updating this list as soon as i found new things bugging me. Please! hope this list doesn't gets too long. I like Vitsa for its speed and Visuals and I don't want to see inkish XP again.
to be continued....

Saturday, August 25, 2007

Secure Strings in .Net

[System].String objects contains an array of characters that reside somewhere in memory. We usually store our confidential entities (information that is meant to be secure) in these String objects. This information can range from your password to you salary code. If some un-managed/ unsafe code is allowed to run, that code can get into our process's address space, find out the required String object and use it in any way as it like.

As we all know, Strings objects are immutable i.e. once a string object is created they never change. Old versions of String object are scattered all over memory. There is no guarantee when garbage collector will run and clean up our application’s managed heap. Before GC wakes up, these string objects are within reach of some unsafe code. Unsafe here means code that is manipulating memory pointer. Even if string objects are used for short time and then are garbage collected by the run time, this doesn't mean that memory space used by string will be allocated to another object just after garbage collection (especially if string object was in older generation).

If some government office like CBI (Indian Investigating Agency) approaches you to create a secure application which will handle data about national security, “System.String” type objects will not meet stringent security requirements that application needs. Sensitive information lying in memory can be very tempting for anti social elements (this includes hackers). Due to these requirements Microsoft introduced another type of string class:

  • Class Name: SecureString
  • Name Space: System.Security

When we create an object of SecureString type, it internally allocates a block of memory that contains an array of characters. Now the surprise! this is an un-managed block of memory and this is because runtime don't want garbage collector to know about these SecureString objects. GC knows about all the objects lying in the heap. It has no information regarding object type but it knows its memory address. This class is just in its budding phase and does not provide only few features that are provided with System.String class. Data is encrypted before storing and decrypted before being read. So with good functionality it gives us some bad performance overheads.

System.Secure.SecureString class implements Dispose pattern i.e. it implements IDisposable interface. Another surprise, its Dispose method is called implicitly (i.e. automatically). You don’t need to call this method explicitly. CLR calls SecureString’s Dispose when it realizes that this string is not needed or it is out of scope. Dispose ensures that all memory contents used by object of SecureString type are zeroed out. This class is derived from CriticalFinalizerObject which ensures that finalize method of this class is called no matter what happens. CriticalFinalizerObject in itself deserves a good amount of space. But I’ll leave it for now.

There are certain limitations around usage of SecureString in .Net 2.0.

to be continued…

Thursday, August 16, 2007

Singleton - One of a Kind Objects (Part II)

How will we tame the multi threading beast?
I'm a .Net developer having CLR as my run time. I never worked on Java, but C# and JAVA are almost similar. C# is advance form of JAVA and CLR is much more refine than JVM. Things that comes later are generally more advanced than things that came earlier. I was first introduced to this multi threading problem while going throgh Head First Design Patterns book. According to the book it was damn simple to fix this problem by making access to MySingleton.GetMySingletonInstance() synchronized. Code for this is simple as Singleton class itself,

using System;
using System.Runtime.CompilerServies;
internal sealed class MySingleton
{
//static variable to hold instance reference
private static MySingleton onlyInstance;
private MySingleton();
//Global i.e. public and static point of access
//No two treads may enter the method at the same time

[MethodImpl(MethodImplOptions.Synchronized)]
public static MySingleton GetMySingletonInstance()
{
if (onlyInstance==null)
{
onlyInstance=new MySingleton();
}
return onlyInstance;
}
}


This is as simple as it can get.We just decorated our method with MethodImpl attribute. This is available in System.Runtime.CompilerServices namespace. Now, no two threads can enter our GetMySingletonInstance() method at the same time. This solves the problem but leaves us with another headache, performance. We all know that this synchronization is only needed when onlyInstance is null i.e. we haven't yet created the MySingleton object. So adding synchronization lock to our method doesn't makes sense. Its just like solving one problem and creating another.


Now What?
There is a well known technique used to solve this problem. This is called Double Check Locking Technique. It's used when you want to have lazy instantiation i.e. you want your object to be constructed when your application first requests it. This is not a well known technique because its particularly interesting or useful. It's well known because a lot is written about it and a lot of Java developers use it. This was quite heavily used in Java but lately its discovered that this technique doesn't guarantee that it would work everywhere. If you want to know why this fails then just read through http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html. Just to show you how this double checking is implemented in C# I'll add some code here,

internal sealed class MySingleton
{
private static volatile MySingleton onlyInstance= null;
protected MySingleton() {}
public static MySingleton GetMySingletonInstance()
{
if (onlyInstance == null)
{
lock (typeof(MySingleton))
{
if (onlyInstance == null)
{
onlyInstance = new MySingleton();
}
}
}
return onlyInstance; }
}
What is the best implementation?
Use Type Initializer (static constructor) to create a simple and best implementation of singleton.
internal sealed class MySingleton
{
//Type constructor will be called when any member of type is accessed
//This initialization code will be added to Type Constructor by JIT compiler
private static MySingleton onlyInstance= new MySingleton();
private MySingleton() {}
public static MySingleton OnlyInstance
{
get { return onlyInstance;}
}
}
CLR automatically calls type's class constructor when the code attempts the access a member of the class. CLR ensures that calls to a type constructor are thread safe. Double check locking is less efficient than this technique as you need to create your own lock object and write all additional locking code yourself. Double check locking is interesting only if class has lots of members and you want to have your singleton constructed only when one of the member is called.

I hope! I answered my friend Pramod's question related to minimize overhead associated with double check locking technique.

Wednesday, August 15, 2007

Singleton - One of a Kind Objects (Part I)

SINGLETON PATTERN

  • What is Singleton pattern?
    Singleton Pattern insures that only one instance of a Type is created and that Type provide a global point of access for that instance.
  • How it's implemented?
    Implementing a singleton type is quite simple (if synchronization is not an issue for you). Type should define a static member variable which will contain reference to type's instance. Make type's instance constructor as Private so that no other type can create instance of our singleton class.
    We need to add one static method that will check weather our static instance variable is null or not. If it is null then we will add code so that our static variable will refer to newly created type's instance. Lastly we will return that static variable.
    This way, there will always be one and only one instance of a type around (just forget about multi-threading for the time being).
  • How it looks when coded?

    internal sealed class MySingleton
    {
    //static variable to hold instance reference
    private static MySingleton onlyInstance;

    private MySingleton();

    //Global i.e. public and static point of access
    public static MySingleton GetMySingletonInstance()
    {
    if (onlyInstance==null)
    {
    onlyInstance=new MySingleton();
    }
    return onlyInstance;
    }
    }
  • How multi threading spoils our Singleton party?
    Multi threaded applications are quite common these days. Now suppose we have multiple threads running in our MySingleton application. I'll name two of my application threads as AngelThread and DevilThread. AngelThread and DevilThread both requires MySingleton instance, so they both try to call MySingleton.GetMySingletonInstance().
    AngelThread checks onlyInstance for null, as we haven't created any instance yet this returns true and code next to be executed by AngelThread is,"onlyInstance=new MySingleton();"
    Now, CPU realizes that AngelThread has got enough CPU time slice, let's switch to DevilThread. Remember AngelThread still haven't instantiated MySingleton yet. DevilThread also checks onlyInstance for null, and obviously true is returned and DevilThread is just about creating a brand new MySingleton object. DevilThread created the object and returns its reference. Our CPU interrupts and wakes up AngelThread so that it can continue its execution. Aha! AngelThread also creates a brand new object and returns. So we have two objects of MySingleton type. Multi threading ruined our singleton dream.

    to be continued...

Let's celebrate Independence


Tuesday, August 14, 2007

Independence Day

We all will be celebrating our country's independence day tomorrow and guess what..there is no electricity in country's capital from past 1 hour. Thank god some one invented mighty battery operated inverters. It's quite humid this time of the year and without AC it's almost impossible to live. I wish I had a laptop so that I wouldn't have to sit and do this stuff. It's painful. These are just my early blogs and I know they are of no use. I seriously want to start up something really useful.

Today during my lunch break, a friend of mine, Pramod, asked me a tricky question regarding singleton objects. I'll check that out today and will try to post something about singleton here tomorrow.

Happy Independence (without BiJli)

Console.WriteLine("Hello World");

It's been almost 7 years since I started using web and computers. Blogging is around from past 3-4 years. Now, after spending about 7 years (30660 hrs approx.) with computer, finally I got some time to start my own blog. Let's see how it shapes up. Keep your fingers crossed and hope! this goes well.

Note: If you didn't get how I came up with 30660 hrs. it's not my fault. It uses some supercomputing algorithms and it's surely not novice's cup of tea.