I know the answer (it's 42)

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

June, 2007

  • I know the answer (it's 42)

    VSTS Source Control Annotation


    One of the coolest feature of the upcoming Orcas release is the Source-Control file Annotation feature.

    "Annotate is a feature that allows developers to inspect a source code file and see at line-by-line level of detail who last changed each section of code. It brings together changeset data with difference technology to enable developers to quickly learn change history inside a source file.".

    This is the tool for you if you want to figure out a change by contacting a developer or want to play the "you screwed up" blame game. You can right click any source-controlled file in the solution explorer and choose annotate.

    This is how the file is annotated at line-level


  • I know the answer (it's 42)

    Using Trace-Points in Visual Studio


    Even though everyone knows about break-points, trace points seem to have been used way less.

    Developers sometimes need to inspect variables and other state as a program flows without interrupting the execution (so no break points). Even if the program is built with detailed tracing (as outlined here) a lot of things are missed in them (how  many local variables are traced?).

    So most developers quickly add a Console.WriteLine or Debug.Trace.Write to dump the information. Now this requires changing code (checkout), not able to remember all the changes and so forth.

    Visual studio supports this scenario very well. Just add a break point to the line where you want to trace and then right click on the break point icon and choose "When Hit" in the context menu. The dialog shown below opens up and you can choose to trace anything you want using the Print Message checkbox including function, thread, variables, messages. The messages are dumped to the output window when you debug the application. It's easy to manage these as well as they come up in the BreakPoints window (Debug->Windows->Breakpoints).

  • I know the answer (it's 42)

    It's Link


    I saw the same thing in TechMela which Dinesh reported. Many attendees was pronouncing LINQ as "link cue". The actual pronunciation is "link".

    Not that it matters much (this is not as bad as C Pound or C Hash where the meaning maybe completely lost).

  • I know the answer (it's 42)

    The difference between is and as and dealing with FxCop Warning CA1800: variable is cast multiple times


    I had the following code

    public static void f1(object ob)
        if (ob is Foo && ((Foo)ob).m == 10)

    This gave the following FxCop (Code analysis) performance warning: 'ob', a parameter, is cast to type 'ConsoleApplication5.Foo' multiple times in method 'Program.f1(Object):Void'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.

    I could easily resolve this by using

    public static void f2(object ob)
        Foo foo = ob as Foo;
        if (foo != null && foo.m == 10)

    Or in my scenario I could've ignored this warning as this code handles a very corner scenario where the is is supposed to fail almost 99.99% times and hence the cast bit would almost never be called (hence double cast would happen say 00.01% times).

    I had used the is subconsciously feeling that is is lighter weight than as . Even the as docs expresses as to be equivalent to expression is type ? (type)expression : (type)null;

    But if that was the case then there should've been no double cast warning (as is doesn't do a cast). So I did the obvious. Pulled up reflector on both these methods.

    The generated IL for f1 is as follows

    L_0002: isinst ConsoleApplication5.Foo
    L_0007: brfalse.s L_001d
    L_0009: ldarg.0 
    L_000a: castclass ConsoleApplication5.Foo
    L_000f: ldfld int32 ConsoleApplication5.Foo::m
    L_0014: ldc.i4.s 10
    L_0016: ceq 
    L_0018: ldc.i4.0 
    L_0019: ceq 
    L_001b: br.s L_001e
    L_001d: ldc.i4.1 
    L_001e: stloc.0 
    L_001f: ldloc.0 
    L_0020: brtrue.s L_002d
    L_0022: ldstr "Yea"
    L_0027: call void [mscorlib]System.Console::WriteLine(string)
    L_002c: nop 
    L_002d: ret 

    And that for f2 is

    L_0002: isinst ConsoleApplication5.Foo
    L_0007: stloc.0 
    L_0008: ldloc.0 
    L_0009: brfalse.s L_001a
    L_000b: ldloc.0 
    L_000c: ldfld int32 ConsoleApplication5.Foo::m
    L_0011: ldc.i4.s 10
    L_0013: ceq 
    L_0015: ldc.i4.0 
    L_0016: ceq 
    L_0018: br.s L_001b
    L_001a: ldc.i4.1 
    L_001b: stloc.1 
    L_001c: ldloc.1 
    L_001d: brtrue.s L_002a
    L_001f: ldstr "Yea"
    L_0024: call void [mscorlib]System.Console::WriteLine(string)
    L_0029: nop 
    L_002a: ret 

    So for both is and as the isinst IL instruction is used. One more interesting thing I noticed in the 2nd case is that after isinst there is no other casting IL used. Some more investigations revealed from this link that "The isinst instruction evaluates whether the reference on the stack is a Foo or a subclass of the Foo type. If it is, then the reference is cast to the type defined in the isinst instruction and pushed onto the stack. Otherwise the value null is pushed onto the stack."

    So this means that the documentation was over-simplifying the situation. is does the whole cast bit and the check is done by the brfalse.s L_001d  instruction which just checks the cast returned null or not. So in reality the equivalence is as follows

    is = (expression as type) != null;

  • I know the answer (it's 42)

    Which font do you use for your resume


    I had asked this before, but this time the question is "which font do you use for your resume?". The other question is what do you tell a person who sent me her resume in Comic Sans MS font.

  • I know the answer (it's 42)

    Static method calls in generics


    I go this question from a blog reader.

    "The following code should be possible

        public class Class1
            public static void Hi()
        public class Class2<T> where T : Class1
            public static void Hi()
                T.Hi();//This should be possible.

    However, if you try to compile this then it fails with the "error: 'T' is a 'type parameter', which is not valid in the given context". At first to me it looked logical and symmetrical to be able to call static methods on a generic type by directly using the type parameter as during compile time it is known from the constrain that T is Class1 which has the static method Hi().

    Then I sent this to the internal C# DL to get this clarified. Eric Lippert gave the answer.

        public class Class3 : Class1
            public new static void Hi()

    Since the user chose T.Hi() over Class1.Hi() it would mean that he expects a dynamic dispatch which lands in Class3.Hi(), but that is very misleading because by definition static methods are determined statically during compilation. So this option is pointless.

    If the call always lands in Class1.Hi() as in the case of true static call it should be, then the user would be better off having it as Class1.Hi() which is what is supported.

    Update: Just found that Eric has posted this on his blog. Check that out here

  • I know the answer (it's 42)

    The Microsoft Sourcer is here


    I had never heard of this position before either , but in case you are looking for working with Microsoft anywhere in the world, Sourcer in Microsoft is your best bet. Check out Jim one of the sourcer here or see the cool video below

    Video: The Recruiters Lounge - Who is behind SourceCon?

  • I know the answer (it's 42)

    I'll be going to TechMela 2007


    Like TechEd, here in India we are having TechMela this year. This time the venue is Mumbai and I'll be there!!!

    Unfortunately there is very little bit of Language stuff. I plan to attend all UX presentations (covered in the agenda's Track 2) and also attend our very own VSTS stuff presented by our PMs Abhishek Mathur and Rohit Chauhan.

    The  details of the VSTS presentations goes as follows

    1. Dev Oriented Testing using Microsoft Visual Studio Team System (with new "Orcas" Features) - Track 1
    2. Drill down into advanced features of Microsoft Visual Studio Team System - Track 2
  • I know the answer (it's 42)

    Interviewing with Microsoft India


    "What to expect in the interview" I've had this question from candidates that I have referred or distant relatives or friend's friend (you get the idea!) who are appearing for an interview with Microsoft . Somehow people still get to hear that Microsoft asks riddles. Though this was true way back but now these questions are rarely asked as they indicate very little about the candidate's potential.

    I have been through interviews with some leading companies as an interviewer or interviewee and IMO Microsoft's interview process is a bit different. So here goes a list of what to expect and be prepared for in a technical interview with Microsoft.

    1. Unlike some other companies, Microsoft takes people from a lot of diverse background. E.g. if you are from C++ compiler development background you can be easily considered for the VS IDE's intelli-sense development if your interviewers think that you can fit in.
    2. Your dress really doesn't matter. You can expect to see your interviewer in shorts and he can't care less about what you wear.
    3. The interview process is loooooong. Expect multiple people to interview you one after the other. So when you get the lunch break, eat well.
    4. Put things in your resume only when you know about them well. People in Microsoft comes from diverse background (see above) and their  is every possibility that your interviewer will be very aware about the technologies you have mentioned in your resume and will ask you about them.
    5. Know your past projects well.
    6. You will be asked to solve technical problems and write pseudo-code for the solution. 
    7. Whether you are interviewing for Software development role, a test role or a lead/manager role you will be asked to code. The reason is simple, in Microsoft leads and development/test managers and even PUMs in some case (Program Unit Managers) code.
    8. Think aloud when solving problems, approach is as important as the final solution.
    9. When giving a solution, find out the fallacies your self and try to come up with better alternatives.
    10. Its an interview, so ask questions about Microsoft and the position/role you are being interviewed for.
    11. This is not true :)
  • I know the answer (it's 42)

    Adding Trace to a .NET application and listening to it


    Just yesterday I was chatting with a friend and he was telling me how they are writing a thread-safe logging library for their .NET app. I was astonished to find out that they were completely unaware of the awesome trace library in .NET.

    So this post is about how to add configurable tracing to an .NET app and how to use some cool tools to see the log. In case you know about the how-to-add part skip down to the listening part as it talks about some neat tool you may not know about.

    Adding trace

    The System.Diagnostic namespace contains the tracing API's that are thread-safe, have configurable levels of tracing, zero-foot print with conditional compilation, trace listener support, etc...

    First lets define a simple wrapper class over the trace API

    public static class Logger
        private static string procName =

        private static TraceSwitch traceSwitch =
                new TraceSwitch("AppTraceLevel", null);

        public static void Info(string format, params object[] args)
            Info(string.Format(CultureInfo.InvariantCulture, format, args));

        public static void Info(string message)
                TraceLine(TraceLevel.Info, message);

        public static void Error(string format, params object[] args)
            Error(string.Format(CultureInfo.InvariantCulture, format, args));

        public static void Error(string message)
            if (traceSwitch.TraceError) TraceLine(TraceLevel.Error, message);

        // TODO: Add Warning/Verbose and other methods in line with Info/Error

        private static void TraceLine(TraceLevel level, string message)
            string traceLevel = null;

            switch (level)
                case TraceLevel.Error:
                    traceLevel = "ERROR:  "; break;

                case TraceLevel.Warning:
                    traceLevel = "WARNING:"; break;

                case TraceLevel.Info:
                    traceLevel = "INFO:   "; break;

                case TraceLevel.Verbose:
                    traceLevel = "VERBOSE:"; break;

                    traceLevel = "DEFAULT:"; break;

            string finalMessage = string.Format(
                "{0}, {1}, {2}, {3}, {4}", traceLevel, procName,
                Thread.CurrentThread.ManagedThreadId, DateTime.Now, message);


    The statement private static TraceSwitch traceSwitch = new TraceSwitch("AppTraceLevel", null); on the top is used to read the trace level from the Config file (more about how to use it below). After that the Log and the Error Methods simply forward the call to TraceLine. TraceLine creates a formatted message and uses Trace.WriteLine (message) to dump it to the Trace.

    The app just calls Logger.Info("message") or Logger.Error("message") to trace something.

    Note that the methods have conditional compilation attribute on it and hence have zero overhead in case the TRACE symbol is not defined.

    Configuring Trace and listening to it

    The trace-level and how the actual trace is dumped is configured using an App.Config file that is added to the application to be traced. The file after adding the configuration looks as

          <!--  0-off, 1-error, 2-warn, 3-info, 4-verbose. -->
          <add name="AppTraceLevel" value="4" />
        <trace autoflush="true" indentsize="4">
            <add name="myListener"
                initializeData="C:\logs\TraceSample.csv" />
            <add name="EventLog"
                     System, Version=, 
                     Culture=neutral, PublicKeyToken=b77a5c561934e089"
               initializeData="sample application"/>

    Here we are setting AppTraceLevel to 4 which means that all tracing is allowed. If you set it to <=2 then calls from our Logger::Info will not be logged.

    We also have two different trace listeners configured. One is named myListener which uses the system provided file based tracing and dumps everything to a csv file (c:\logs\TraceSample.csv). We used a csv file because intentionally we chose a format of tracing (see string.Format in Logger::TraceLine) where the trace is comma separated and hence can be easily opened in Microsoft Excel. You can as well name it .txt and use notepad.

    The problem with file based tracing is that its not real-time and you can only post-process it. The other option is to see in real-time what is being traced. The 2nd trace option named EventLog just does that. It traces to the system event trace which you can see through the system management console in by running Start->Run->compmgmt.msc. However, a better tool for this job is DebugView  from the erstwhile Sysinternals now acquired by Microsoft. Its free and available from here.

    Install this and bring up DbgView.exe. Hit Ctrl+L to bring up the filters dialog (so that you can narrow down and only see your app's log). In the Include text box enter your application's name (note that we put that in the trace messages and hence you can filter on it).

    Run the App and DebugView will dynamically show the trace messages as the app traces them.

  • I know the answer (it's 42)

    SPAM is served


    When I was deleting spam from the spam folder of one of my personal email accounts, the advertisement on that page pointed me to the recipe of SPAM VEGETABLE STRUDEL.

    I could almost hear the waiter say "Today's speciality is spam".

  • I know the answer (it's 42)

    Domain experts and their fixation


    Some times all programmers get stuck in some weird issue with a specific technology which doesn't fall in his area of expertise. If this problem is really weird or very specific to a scenario then it's difficult to find a solution online and the only thing left is to contact a Domain Expert who knows more about it than an Eskimo about snow.

    This is when the fun starts. The expert has a fixation on the subject (hence he is the expert) and starts raising all sorts of issues and will not agree to any solution unless it works 100% of all cases in his domain, he really has no clue about your scenario and couldn't care less.

    Typical exchange goes as:

    Me: Hello Mr.Expert, I'm using the Elephant technology in my product and I am hit by the issue that it is not working as expected in a situation. This is my code ....

    Expert: This is will not work for this, this and this

    Me: Can I fix this by doing this?

    Expert: And then this will not work in that that and that won't work either.

    Me: But in my scenario I do not need that and that.

    Expert: But still it doesn't work in that and that and so the solution is not fine

    Me:So what is the solution

    Expert: You can use an alternative Foo but then Bar won't work

    Me: Fine I'll go ahead because in our products we don't much care about Bar and we have some alternative solutions to it.

    Expert: You are writing code that isn't going to work in 20% scenario and hence it's a bad solution. I don't have a solution and I suggest you don't try to support your feature at all.

    Me: But that is your 20% scenario, since I don't target them its not even 2% of mine and our feature is super important to us.


    This is when I give up and start solo flight.

Page 1 of 1 (12 items)