I know the answer (it's 42)

A blog on coding, .NET, .NET Compact Framework and life in general....

  • I know the answer (it's 42)

    Error messages


    Frequently we are presented with error message pop-ups with messages like "Unable to open file". Error messages are popped up when something has gone wrong. If SW cannot convey to the user what went wrong and what he can try to fix the problem, it might as well not show the error message at all.

    So all errors messages must have three components

    • Notification
    • Explanation
    • Solution

    A good example for a Team Build scenario would be

    Unable to connect to the build machine "BuildServer01"
    Make sure that the machine is connected to the network and the TeamBuild Service is running on it.

    So all error messages that have one sentence in them are most probably not as helpful as it states what happened and not what can be done to rectify it.

    Another important thing to note is that the user is never to be blamed for any error. If the action he did was dumb then we are at fault that we did not restrict him from committing a dumb action.

  • I know the answer (it's 42)

    Team Build blog


    I guess the least represented module of Visual Studio Team System on msdn blog was Team Build . This is going to change now with the Team Build PM khushboo taking up bloging actively. See http://blogs.msdn.com/team_foundation or http://blogs.msdn.com/team_foundation/archive/2005/03/02/383479.aspx


  • I know the answer (it's 42)

    C#: String comparison guidelines and common usage


    The recommendation for string comparison has been updated for Whidbey (Visual Studio 2005) and there is an excellent MSDN article on this. One of the highlights is the introduction of the clear cut enumeration that can be passed into most string comparison methods to indicate the kind of comparison you are trying to make.



    public enum StringComparison


    CurrentCulture = 0,

    CurrentCultureIgnoreCase = 1,

    InvariantCulture = 2,

    InvariantCultureIgnoreCase = 3,

    Ordinal = 4,

    OrdinalIgnoreCase = 5,


    The recommendation also states that for culture-agnostic comparisons use the Ordinal and OrdinalIgnoreCase comparisons. These are fast and also safe. They rely on byte matching and are excellent options for matching strings for internal (non-UI) processing.

    string.Compare(str1, str2, StringComparison.Ordinal);

    With the introduction of the guidelines, developers have become defensive and have started looking for all code that compare string and re-coding them to meet the guidelines. Let's take a look at the most common culture-agnostic string matching used in code and see if they are safe.

    string.Equals(string1, string2)

    Default interpretation for equals is Ordinal so using this is fine. In case of using any other type of comparison use in the lines of
    string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

    string1 == string2

    In accordance to the class library design guidelines the == operator for string is overloaded and the implementation is same as for string.Equals. So this is equivalent of calling string.Equals(string1, string2, StringComparison.Ordinal) which is also fine.


    For small sized switch blocks of the form

    string myStr = "Abhinaba";

    // ...

    switch (myStr)


    case "Abhinaba":

    Console.WriteLine("switch match"); break;


    Console.WriteLine("switch did not match"); break;


    the code is compiled into 

    if ((myStr!= null) && (myStr == "Abhinaba"))


    Console.WriteLine("switch match");




    Console.WriteLine("switch did not match");


    So this is also fine and the comparison will be a string.Equals( strA, strB, StringComparison.Ordinal) comparison.

    However, if the switch block is larger then things get complicated. A dictionary is created and lookup happens through Dictionary.TryGetValue with the string as the key. Lookup happens using code similar to

    int num1 = this.comparer.GetHashCode(key) & 0x7fffffff;

    for (int num2 = this.buckets[num1 % this.buckets.Length]; num2 >= 0; num2 = this.entries[num2].next)


    if ((this.entries[num2].hashCode == num1) && this.comparer.Equals(this.entries[num2].key, key))


    return num2;



    A quick look and a bit of poking around with reflector indicates that the result will ultimately be the same as string.Equals( strA, strB, StringComparison.Ordinal).


    As the guideline suggests replace all InvariantCulture usage with either Ordinal or OrdinalIgnoreCase

    Be on the Safe Side

    The above discussion was mainly to figure out what to make out of common string comparison statements in existing code. Going forward I think its best to be defensive and clear in code and explicitly call the comparison methods and pass the correct StringComparison enumeration constant.

  • I know the answer (it's 42)

    C# 2.0: life was a bit more difficult without Static classes


    Usefulness of a new feature is best understood if you try to implement something that the feature targets without using that feature. I started programming in C# when v2.0 was already available internally, so I got used to many of the new features in v2.0 without realizing the people outside have to work hard to get the same thing done.... One of these features is static classes. We use this in lot of places in our Team System code to group resources like constant strings, methods that operate on them and also utility methods that do not need any instance to operate. So a typical implementation is something like

    public static class BuildStatus


    public static string Initializing { get { return BTRes.Initializing; } }

    public static string Sync { get { return BTRes.sync; } }

    public static string SyncCompleted { get { return BTRes.syncCompleted; } }

    /* ... */

    internal static bool IsOneOfCompletedStatus(BuildStatusIconID status)

    { /* ... */ }


    Marking these classes as static ensure all of the following

    • Ensure that only static members can be placed in them
    • Unnecessary instance of the class will not be created
    • They are sealed and cannot be inherited from
    • They will not contain instance constructors

    Pre C#2.0 classes couldn't be marked as static and the workaround was to use the following pattern

    public sealed class MyStaticClass


    private MyStaticClass(){}

    public static void MyStaticMethod(){ /* ... */}

    public static string Author = "Abhinaba";


    So the class had to be marked sealed to stop inheriting and you needed to have a private constructor to stop creation of instances. Even then things did not work out perfectly as anyone could just go ahead and add instance members. With static modifier being supported for classes, the compiler can ensure that no instance members are added by mistake and it also helps in code-readability.

  • I know the answer (it's 42)

    TFS prank: Scare your developer with a bug created by the CEO


    Raymond Chen in one of his posts jokingly wished that if he could use an alter-ego to update bugs in the bug-repository it'd be great. Actually there is a neat feature in Team Foundation Server's Work-Item tracking (WIT) client using which you can do just that. See the screen shot below. Looks like Mr.Ceo made some changes to the bug.

    The feature is that the history tab where you enter comments support rich text. So I copied a bit of the history text, pasted it and then changed the text. So this exactly looks and feels (the + buttons are expandable as well) like another history item. Next time the dev checks the bug, he'd not be very happy about it.

    I'll let you into another secret. I did make a change like this in an actual bug. A reward awaits for the dev/test in our tem who finds it......



  • I know the answer (it's 42)

    Everyone working in Microsoft are millionaires


    24 hours and 5 movies later I finally landed in Seattle. Journey was uneventful other than the fact that the security in Amsterdam had some doubt about my passport :) As usual my Microsoft blue badge did the trick. They seemed to be more convinced by the blue badge than my passport, I guess the computer in front of them running Windows helped me a bit :)

    I was in the immigration check queue and the officer there asked me how much cash I was carrying. I gave him the 3 digit number (see I'm being discreet here) and he gave me a shocked look and said "I thought everyone working for Microsoft are millionaires, and you are carrying just that much cash!!!".

    I didn't get into a detailed discussion about the merits of credit cards or the current price of MS stocks, just gave a little smile and proceeded to get into US....

  • I know the answer (it's 42)

    Calling desctructors in email


    I have the habit of ending emails I send with ~Abhinaba. So my emails would go like

    Hi <Someone or SomeGroup>
    <body of email>

    Each time one of my friend would recieve such an email he'd reply back with "Email error: Calling destructor explicitly is not allowed. After closing the email you'd anyway go out of scope and the desctructor would be called"

    Avoid having such friends and if you do kick them on their backside for such replies :)

  • I know the answer (it's 42)

    Front license plates are not required in NC and many other states in the US


    While this can be very common and insignificant information for most people in US and specifically those from the 19 states that doesn't officially need a front license plate, it caught us by surprise. 

    We (me another colleague Neeraja) went to Microsoft Raleigh (in NC) for some work. Early morning we got down at the airport and reached Avis car rental. We were given the car number and so we headed towards the parking lot. The first car didn't have a number plate and so we went to the next and the next and the next. Puzzled we went to the attendant and told him none of the cars have number plates. He explained and we went to the back of the car and finally found the one we were looking for!!

    Its another thing that Neeraja felt that the car, a Chevy HHR was the ugliest looking car she had ever got into. I kind off liked it though. However, we can vouch for one of the claims they're making on the web-site the hidden rear cargo compartment. We didn't see it, so it must've been well hidden.

  • I know the answer (it's 42)

    Most users do not read documentation


    This was something our User-Experience folks keep telling us. Frameworks and UI needs to be designed such that they fall into the pattern that'll be assumed by the user.

    Recently I got bitten by this. I was writing some verification code which needed to get the pixel color from a location on desktop and match it against a known color. I used the following code

    int hwnd = Native.GetDesktopWindow();
    int desktopDC = Native.GetWindowDC(hwnd);
    uint pixel = Native.GetPixel(desktopDC, x, y);
    Native.ReleaseDC(hwnd, desktopDC);
    Color realCol = Color.FromArgb((int)pixel);

    Then I was comparing the RGB components of realCol with my expectedColor. Funnily the test was failing each time. Then I dug a bit into the documentation and to my utter disbelief found that the following code was yielding me ABGR and not ARGB.

    GetPixel returns COLORREF who's documentation states that the color is stored in 0x00bbggrr. This resulted in this.

  • I know the answer (it's 42)

    Back from vacation


    For folks missing my posts (are there any such people :) ) I am back from vacation. I was getting scorched in the hot Mumbai sun and then I was chilling out in Daman or in the Buddhist caves in the western Ghat.

    I was welcomed home with a long list of bugs and emails, emails and more emails. As someone who joined MS recently said "Man!!! it rains emails here"

    Me getting baked in Juhu Beach

    Chilling out in Cidade De Daman. Obviously I'm not in the frame as I took the picture and was juggling 2 beer cans and my camera at that time ;^)

  • I know the answer (it's 42)

    C#2.0: Generic methods, delegates and type inference...


    I did not like var in C# 3.0 because I felt it reduces code readability. For the same reason I do not like using Type-Inference in C# 2.0 generics.

    class MyClass


    public void MyMethod<T>(T value) {

    Console.WriteLine("{0} {1}", typeof(T).FullName,



    class Program


    static void Main(string[] args)


    MyClass mc = new MyClass();

    mc.MyMethod(5); // Type inference

    mc.MyMethod<int>(12); // Explicit type parameter



    Even though the first one using type inference requires less typing (and I'm sure will go a long way in CTS erradication) I prefer the more verbose explicit type parameter.

    However when applied to generic delegates, type inference becomes a bit different. Consider the following

    class MyClass


    public delegate void Foo<T>(T item);

    private void Bar(int i)


    Foo<int> foo = MyMethod; // MyMethod<int> is inferred

    //Foo foo = MyMethod<int>;


    public void MyMethod<T>(T value)




    I was talking to a friend some-time back and when compared to generic methods, he had assumed that  type inference for generic delegate would mean that the type parameter of the delegate will be inferred. However as we see from the example above that the type of the delegate needs to be explictly given and from this the type of the generic method is inferred. I am kind of OK with this because at least the types are specified in the statement...

  • I know the answer (it's 42)

    C#2.0: Nullable types, lifted operators and some compare weirdness

    Recently I was stumped on some weird comparisons and I promised myself I'd do some investigations. I figured out with help of some people like Erric Lippert they are due to the inclusion of nullable types in the language. When a new feature is added the ripple effects reach every nook and corner of the language, nullable types are no exception to this. Consider the following code and try to guess whether they'll compile

    int i = 5;

    if ( i == null )

    Console.WriteLine ("null");

    if ( 5 == null )

    Console.WriteLine ("null");

    The answer is "NO" on C#1.1 but "YES, with warnings" on C#2.0. The warning give away the reason why they compile "The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' ". The part in bold clearly indicates that the i and 5 are getting converted to the nullable type int?.

    Lifted conversion operator

    According to the C#2.0 spec if there exists an conversion from a type S to T then a lifted conversion operator exists from S? to T?. For this conversion T? will be unwrapped to T, then T will be converted to S and then S will be wrapped into a S?

    struct S


    public static implicit operator S(T t){

    Console.WriteLine("Conversion T=>S");

    return new S();



    struct T



    class Program


    static void Main(string[] args)


    T t = new T();

    S s = t;

    T? tq = new T();

    S? sq = tq;



    In the above code even if T? to S? conversion does not exist directly it will go through. The output will have two "Conversion S=>T" indicating that even for the second conversion the same conversion operator was called. There is an exception rule to it though. Consider the following when applied to the same classes

    T? tq = null;
    S? sq = tq;

    For this the compilation will go through as ususual but the convertion function will not be called and sq will be null. This is called null propagating in which the null source is directly converted into null target without going through the underlying conversion function. However, the conversion function needs to exist so that the compiler can verify that the conversion is valid (even though it does not call it). In our conversion function we create a new S irrespective of the value of T. So if our function was called, sq would have been non-null which is not the case...

    Lifted Operators

    Lifted operators allow predefined and user-defined operators (overloaded-operators) that work for non-nullable types to be used for their nullable forms as well. Consider the code below

    struct S


    public int val;

    public S(int val)

    this.val = val;



    public static S operator +(S s1, S s2)


    Console.WriteLine("+ operator called");

    return new S(s1.val + s2.val);



    // user-defined operators

    S? sq1 = new S(5);

    S? sq2 = new S(6);

    S? resq = sq1 + sq2; // resq will be 11

    resq = sq1 + null; // resq will be null


    // pre-defined operators

    int i = 5;

    int? j = 6;

    int? k = j + i; // 11

    int? q = i + null; // null

    In the above code even though the + operator is overloaded for S it also works for S?. Even here null propagation takes place and for resq = sq1 + null; the overloaded operator function is not called as one of the sources is null.

    For the expression S? resq = sq1 + sq2; the code that is generated is something like

    S? resq = (sq1.HasValue && sq2.HasValue) ? (sq1.Value + sq2.Value) : (S?)null;

    Equality operator

    This is the one I hit in my previous blog. The == and != operators have been lifted so that it allows one operand to be a value of a nullable type and the other to be the null literal. So both of the following expressions are valid

    int i = 5;

    if (i == null)


    if (5 == null)


    However if you want to get the following to work you need overload the == and != (and Equals) of the type S

    S s = new S();

    // compile error is == and != is not overloaded

    if (s == null) Console.WriteLine("null");

  • I know the answer (it's 42)

    Scheme of things


    Unfortunately I did not attend MIT, and Scheme was not taught to us as one of the first languages :) . Our college used Prolog for similar purpose and I learned scheme much later. When I first started out what intrigued me most was that its one of the oldest launguages around and was still holding ground. It was developed in 1975 a year before I was born and in the field of computing things seldom stick for so long.

    After taking a brief look into the syntax I figured out this is not one of those languages where you try out "Hello world" first. I brought up the DrScheme IDE and tried out (/ 22 7) which is supposed to print out 22 divided by 7. I was surprised that to get back 3 1/7 and not something like 3.1428.

    The results of the next attempt was even for interesting. I tried out (% 22 7). This was a typo as there is no % operator in Scheme. The Scheme interpreter actually displayed the imageof a bug to indicate there was a bug in the code I typed. Whenever I get a VSTS bug assigned to me on some improper/ambiguous/funny error messages I always feel like showing that person this message :)

    DrScheme Screen shot
  • I know the answer (it's 42)

    Customers rule


    I develop commercial software which is critical for our customers' success. In this effort we always take decision in favor of the customer. The customer rules!!!  Many times the decisions are not of great liking to the developers and we get into heated arguments with the PMs and leads arguing that we should do this feature or we should use that technology. Sometimes we become over-passionate about fixing some bugs which gets reproed in arcane situations. The PM's generally know more as these are the folks who do all the research on customer requirements, usage scenarios and they are right most of the times.

    But this does not mean that the developers are wrong. I was greatly inspired by the following piece from SICP

    "I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more."

    Alan J. Perlis (April 1, 1922-February 7, 1990)

    So there exists no monarchy is software development, its democracy and customer's rule as much as fun does. So lets get going and have all the fun we can afford......

  • I know the answer (it's 42)

    We just got jolted


    I'm sure the world already knows, but still there's nothing wrong in saying it over and over again. The results of the 2006 Jolt award is out and we've won in the Development Environment category. Check out Rob Caron's post on this.

    If I ever got the chance to go on stage to recieve an award I'd do it exactly in Oscar style and thank Douglas Adams the person who taught me the answer to life, Universe and everything.

  • I know the answer (it's 42)

    Team Foundation Server is released


    Its hard to express in a blog the feeling of seeing the Earth shattering product I was working on for about 2 years getting released. Its official now Team Foundation Server has shipped.  However the bang was kind of diluted as the news went out a bit earlier with the posts here and here. Unfortunately we are ahead in Time Zone and its already Saturday morning here. So our celebrations have to wait till Monday morning.

    This is the 4th product I'll be shipping in my career and the 1st from Microsoft. Everytime its an unique feeling and I keep going back to the site to see the anouncement and get amazed as I see the sales figures and get humbled by the fact that such a large user base is going to use the product.

  • I know the answer (it's 42)

    command line tool syntax

    Command line interface (CUI) designs for many of the tools found with VS or in Windows were to include a bunch of individual commands or exe with options or flags.

    To get a directory listing: dir <options> as in dir c:\temp /w
    To create a directory: md c:\temp\foo
    To delete a directory: rd /s c:\temp\foo

    So even though all the tasks pertain to directory or path handling , you need to know three command to do the task. This design is slowly changing to the format of command <action> [</options:attributes>]

    For example if we change the above commands to this format with the common command called dir, we will be getting
    To get a directory listing: DIR list c:\temp /w
    To create a directory: DIR  make c:\temp\foo
    To delete a directory: DIR rem c:\temp\foo /s

    So effectively user learning is reduced. One can argue that he still needs to remember the names of the actions. But in the previous case he needs to remember rd, md, dir. Now he knows everything to do with path handling is to be done with DIR. So he can run DIR /? to get the list of actions and then do a DIR list /? to know the options for listing. The other advantage is namespace pollution in terms of the names of the executables also reduces.

    This new format has also been adopted in the VS as in the source control tool. So to get the listing of all workspaces on MyServer you  run the command
    h.exe workspaces /s:MyServer
    To create a new workspace you run the command
    h.exe workspace /new MySpace /s:abhinab-test
    I guess going forward we will see more and more of the standard OS commands also taking up this format. A very common example is the NET command

  • I know the answer (it's 42)

    All new MSN blog


    With all those blog servers floating around I was waiting for MS to do something about it, and voila there are here with http://spaces.msn.com . Its free provides all that other blog servers do and more. MS has made it a habit to wait and watch a technology to grow and mature, then take it up and make it reach new heights :)

    Just thought I'll copy/paste the feature list I got through an internal mail

    MSN Spaces Enables Rich Self-Expression

    MSN Spaces enables consumers to easily share things with the people they care about in a format that can be easily customized. People can start a Space with just a few clicks, and then personalize it to reflect their moods, likes and dislikes:

    ·         Rich layout. Fifteen custom backgrounds and five layout template choices allow consumers to customize their MSN Spaces quickly.

    ·         Web logs. The MSN Spaces blogging tool allows people to publish and maintain online personal journals and enables them to link to photos and other Web sites.

    ·         Photo albums. Consumers can upload up to 10 MB of photos (250 images after compression) to their Spaces sites and display them to others in slide shows.

    ·         E-mail uploads. Consumers can upload photos or blog postings to their Spaces from virtually any e-mail service or e-mail-enabled mobile device.

    ·         Music favorites and lists. Consumers can create and manage lists of information that is important to them, such as their favorite music, books or travel destinations. Consumers can easily share playlists through their Space with Microsoft® Windows Media® technologies. With just two clicks, people can sample or purchase a song on someone’s playlist through MSN Music.*


    MSN Spaces Helps Users Connect With Others

    MSN Spaces is designed to help people express themselves online while better connecting them with their friends, family and other contacts:

    • Contact Cards. When a person clicks on a Contact Card in a MSN Messenger or Hotmail® Contact list, the card pops up and gives a sneak peek at that contact’s Space – from its look and feel to the person’s most recent postings. The Contact Card includes links to the Space and those entries for easy access.
    • Gleaming. When a Spaces site is updated or content is added, the MSN Messenger Contact icon of the Space’s owner will light up, making it easy for friends and family to know when there have been changes. This facilitates more visits to a Space, faster responses to new postings and closer bonds between Space owners and their contacts.
    • RSS. MSN Spaces also supports RSS 2.0, so consumers can publish their Space to others by way of RSS viewers and aggregators, including My MSN, scheduled to come soon. This is another way to ensure that the people who matter to a user can stay up to date on his or her Space.


    MSN Spaces Offers Protection and Control

    MSN Spaces is designed to give consumers control over how they share their Space information and who can access it:

    • Permissions. Consumers have three permission control settings on their MSN Spaces site, enabling them to decide just how widely they want to share their content:

             Public: Viewable by anyone

             Contacts Only: Viewable only by their MSN Messenger contacts

             Private: Viewable only by contacts whose e-mail addresses are manually entered by the MSN Spaces author or selected from an MSN Contact list

    • Controls. MSN Spaces gives the consumer control over how others interact with his or her Space. MSN Spaces includes settings that give each person power over who views his or her Space and how people can interact, read and comment on the Space. This includes the ability to set up the Space so people can read but not comment.
    • Statistics. Consumers will be able to track visitor statistics on their Spaces site, so they will know how many people are visiting as well as other detailed information
  • I know the answer (it's 42)

    Shooting star


    Yesterday night when we (me, Ankur and Hemant) were going out to dinner from office (Microsoft India Campus), we saw a meteor shooting past us in the sky. It was huge and almost looked like some firework except that it was coming downwards. I had never seen a larger shooting star and nither had the others. I was big enough and close enough for atleast the ashes to fall on earth. Unfortunately, there were no report of it in the news papers, I guess we should have reported it in the first place.

    The worst part is that we figured out that we've been playing Halo a bit too much 'cause Ankur said that he thought it looked like a shot from the Rocket launcher.

  • I know the answer (it's 42)

    Build Type creation and Drop Location


    One of the most common issues everyone is running into with Team Build is configuring the Drop Location.

    All builds that happen through Team Build are dropped (bits are copied) to this location. Drop location is entered in the Location page of the Build Type wizard. This is essentially a shared folder on the network and needs to be available in UNC format as in \\server\share. However most users enter a path in the wizard and then any of the following three things happen

    1.      They forget to share the folder out
    Result: First build fails

    2.      The folder is shared out but adequate permissions are not given on it
    Result: First build fails

    3.      The folder gets unshared at some point of time
    Result: Suddenly builds start failing after that

    A common question is raised that both the first and second reasons of failure are a pre-requisite to starting a build, why doesn’t the Build Type wizard verify that the share exists. We could have done this but there are a couple of reasons we do not.

    Firstly it could be a common scenario that the administrator is first setting up couple of Build Types and will then go and share those folders. So failing would simply hinder this process. However, this is not a very good excuse because we could have at least gone ahead verified the share and then given warnings stating that the share does not exist and the admin should share them with the correct permissions.

    The main reason for not doing this verification is that scenario 2 is not easily verifiable. To undertand this let’s consider the permission required on the shared folder

    1.      The service account under which the Team Build Service is running on the  Build Machine needs write permission on this folder

    2.      Other users need to have read permission on this folder so that they get to see build logs and the build itself

    On the client where the Build Type is getting created through the wizard there is no information regarding the service account on the Build Machine so we cannot verify 1. This is because the admin while installing the BM could have chosen any valid account to run the service and can give explicitly and exclusive write permission to this account on the share. Moreover, user can change the Build Machine while firing the build and the service account on the new Build Machine might be a different account and that might not have permissions.

    On OS’s like WinXP in addition to the sharing permission you can go to the security tab on the folders properties and apply a lot of permissions which are not accessible over the network but would make the build to fail. Take for example in share tab you give Full control to everyone and in the security for that folder you explicitly deny create folder permission. So even though our verification succeeds build will fail.

    Verifying 2 does not add any value if we cannot verify 1.

    Its not that we cannot verify drop location, what I tried to highlight above is that it is non-trivial. Many users think that the Wizard should just try to see if the share exists and then create and delete a file on the share to ensure it is writable. However for the reasons mentioned above this approach would just not work.


  • I know the answer (it's 42)

    Ensuring only one instance of an application can be run and then breaking that approach


    A question posted on a DL was as follows

    "I have an application that allows only one instance on the desktop, how do I force it to open multiple instance for some testing purposes".

    Disclaimer: Note that this is kinda hacky and only relevant if you are a tester trying to break something. This shouldn't be treated as a way to achieve anything productive.

    Since the user didn't explain which approach is used to ensure only one instance is allowed I'll try listing down the methods I know off and how I can break them.

    Using named Mutex:
    This is the more resilient approach taken by applications like Windows Media player. Here the application tries to create a named Mutex with sufficiently complicated name to avoid collision. E.g. namespace.app.guid and then try to acquire the mutex. In case it fails to acquire it then an instance is already running and it closes itself. If it acquired the mutex it means it is the first instance and it continues normally. An approach is outlined here.

    Even though this seems to be the most robust solution this can be made to fail as well. If an user has sufficient permission he can do a CloseHandle on a Mutex handle created by some other application as well. For this you don't even need to write code. Do the following

    1. Download and install Process Explorer.
    2. Launch it (might need elevation on Vista)
    3. Have an application that uses this approach like my application named SingleInstanceApp.exe. Try launching a second instance and it will fail to open it.
    4. Click on the app finder toolbar button in Process Explorer and drag it to SingleInstanceApp window. This will get this application selected in process explorer.
    5. Select View->Lower Pane View ->Handles or simply Ctrl+H
    6. This will show all the handles created by SingleInstanceApp.
    7. Scroll down looking for the mutexes. At the end the screen looks something as follows Capture
    8. Right click on the mutex and choose Close Handle.
    9. Now try creating the second instance and it will open fine.

    Enumerate the names of applications running and see if the app is already running:
    This uses a combination of Process.GetCurrentProcess and Process.GetProcessByName(), see an implementation here.

    This is easy to break. To do a DOS (Deinal of Service or DOS) just  create another application with the name that the app expects and per-launch it. To open two instances copy the application to another name and open that first and then the original application.

    Enumerate Windows

    This involves iterating through all the open windows in the system using EnumWindows and then seeing if a Window with a given name or classname is already present. Since the system doesn't guarantee uniqueness in either of the text or class name this can be broken in a similar approach to the first one. However, there are some complications to it as it is difficult to change window text from outside. However, a combination of code injection and SetWindowText win32 API should work.

  • I know the answer (it's 42)

    Time for a change


    I've been working for some time in Visual Studio Team System (first on the TFS server and then on the testing infrastructure). I was looking for a change and then I happened to talk with the GPM of the .NET COMPACT FRAMEWORK team. The following explains in brief what followed...


    ... and so I landed a job in the .NETCF Garbage Collector and other parts of the execution engine. I'm sure I'll be super busy as the team is heads down into getting Silver Light onto mobile devices and going cross-plat (I guess most folks have heard about SL on Symbian/Nokia).

    What this means is that I can (or rather I have to) muck more with .NET (both desktop and CF) without any guilt and can claim that blogging about them is actually a part of my job. So what this means for this blog is that there'll be more hardcore stuff about .NET and an additional Tag called NETCF when I post specifically about it.

    In case you are in India and want to work in a Kick-ass team delivering one of the most key technologies for the industry then drop me a line at abhinaba.basu @ you know where. Bragging rights will come for free when you point to all those cool WinMobile/S60/XBox/Zune devices and claim how you coded .NET for it....

    Wish me luck...

  • I know the answer (it's 42)

    Multi-threaded developer


    Once upon a time a kick-ass developer I knew told me that a good developer needs to be multi-threaded and run the following threads

    1. The main worker thread: This is the one used to code up 3-tier applications for your employer. This pays for the rent and for that fancy big car.
    2. The core thread: This is the one that's used to read up data-structures, OS and other fundamental CS stuff which helps you to join into discussion when folks are discussing threaded BST. This also helps you to crack an interview in case you need a new job.
    3. The cool thread: This is the one you use to read up about Silver Light Mobile, ASP.NET MVC Framework, JSON, etc. This keeps you up to date and let's you hang around with other geeks like Scot Hanselman and Don Box

    The same person also told me that real programmers do not blog, he asked me "Do you know about Dave Cutler or Linus Torvald's blog?". So I guess we can safely ignore him :)

  • I know the answer (it's 42)

    Model, View, Controller


    These days the whole world is abuzz with the Model, View, Controller (MVC) architecture. This is not something new and is known by computer scientists for close to 30 years. I guess the new found popularity is due to the fact that this has heavy application is web development and lot of main-stream web development platform are putting in support for this. Ruby-on-rails and ASP.NET MVC are classic examples.

    Coding horror has a nice post on this topic. I liked the following statement it made

    "Skinnability cuts to the very heart of the MVC pattern. If your app isn't "skinnable", that means you've probably gotten your model's chocolate in your view's peanut butter, quite by accident."

    I actually use a very similar concept. The moment I see an application's architecture (be it an interview candidate or a friend showing off something) I ask the question "Can you write a console version of this easily?". If the answer is no or it needs a re-design it means that the separation of model, view and controller is not correct. You are going to have a nightmare if you write and maintain that software.

  • I know the answer (it's 42)

    Moving blogs to http://geekgyan.blogspot.com/


    It's been a drag maintaining two blogs for some time now. So going forward I'll shift to posting only on my personal blog. I'll be cross posting for some more time and then stop this blog.

    The new address is: http://geekgyan.blogspot.com/

    Point your aggregator to: http://geekgyan.blogspot.com/feeds/posts/default?alt=rss

    We are moving in Microsoft India as well. We will move to the spanking new Building-3. While putting my stuff in the boxes supplied, I thought its a good time to announce my blog move as well :)

  • Page 11 of 16 (378 items) «910111213»