I know the answer (it's 42)

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

July, 2006

Posts
  • I know the answer (it's 42)

    Campus trivia: Microsoft Walk of Fame

    • 0 Comments

    I was casually strolling around the MS Redmond campus when I reached the area in between building 16 and 17. I was surprised to see that similar to Hollywood Boulevard the pavement was embedded with tiles featuring shipped products.

    I had never heard about this place before. Its was specially interesting to see this one. It was released in the year I was born. So now you know how old I'm :)

  • I know the answer (it's 42)

    Howto distinguish between a C and C++ program

    • 5 Comments

    Q: Write a piece of code that compiles as both C and C++, but from the execution you can determine under which mode they were compiled

    This is the question which I overheard Amit and Srivatsn discussing before I left office. Obviously you cannot go to sleep if you don't get that nailed. So after pondering for some time I came up with the following code.

    #include <stdio.h>

    int main(int argc, char* argv[])

    {

    // 1: Using comments

    int val = 42//* WooHoo*/ 2;

    ;

    val == 42 ? printf("C++\n"): printf("C\n");


    // 2: Using sizeof

    sizeof('a') == sizeof(char) ? printf("C++\n"): printf("C\n");

    return 0;

    }

    If this code is placed in a .cpp filed and compiled in VS the output is C++, C++ and if placed in a .c file with language extensions disabled the output is C, C. If you are using the Microsoft Compiler this is how you do it

    c:\> cl CCPP.c /Za
    c:\> CCPP.exe
    c:\> cl CCPP.cpp
    c:\> CCPP.exe

    The second approach is trivial because in CPP the sizeof a literal character matches 
    sizeof a char and in case of C it matches sizeof an int.

    However the first approach is kind of tricky. Lets conside the code

    int val = 42//* WooHoo*/ 2;

    ;

    In C++ all the characters after // is considered as comment and hence this is compiled as

    int val = 42;

    However C doesn't recognizes the // comment and this gets compiled as

    int val = 42/ 2;

    ;

    I'm sure people can think up of other approaches....

  • I know the answer (it's 42)

    Make all your utility methods 'Extension methods'

    • 4 Comments

    As I had previously said I love extension methods and have started using them at multiple places like converting enums to strings. The CSharp 3.0 specification clearly calls out the following in red

    Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.

    This piece of advice is exactly like being advised not to eat junk food. Doing it makes one happy and lazy irrespective of the fact that he might get obese and in bad shape. So I'm just going to ignore this advice and convert a lot of my utility methods into extension methods.

    Why? 'cause you can define an extension method and use it either as method(object); or object.method(). Sometimes it just feels weirdly cool to be able to do that. Let's take an example:

    I had a utility method to look up an object in a table. The utility method took a name (string) as argument and returned an object from the table. So I converted the code to extension method like

    public static MyClass Find(this string name)

    {

    MyClass mc;

    //look up the table;

    return mc;

    }

    Now I can either use either of the following

    MyClass mc;

    mc = Find("abhinaba");

    mc = "abhinaba".Find();

    The second option (in bold) is uber-cool. Just the fact that you can call arbitrary function on a sealed class like string makes you feel happy. It's even better if you can sneak this into code which a non-C# 3.0 aware coder is trying to maintain :)

    Now since I have not-followed the doctor's advice of avoiding junk food, I feel happy and contented. I tend to ignore that I have difficulty going up stairs and frequently have numbness in my left hand. I think every thing is fine and all the programmers that maintain my code bless me everyday for writing such cool code. It's there blessing that'll ensure me a long prosperous life.

  • I know the answer (it's 42)

    Calling desctructors in email

    • 2 Comments

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

    Hi <Someone or SomeGroup>
    <body of email>
    ~Abhinaba

    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)

    clip it

    • 6 Comments

    In PowerShell I ran (dir *.exe).Count to see the number of executables in System32 folder in a Vista box and it prompty returned 401. So there are 401 executables and most of us are unaware of most of them.

    Recently I wanted to copy the output of a console application to the clip board. I was on the verge of writing a program to do just that when I reminded myself of the programmers disease. After a bit of digging around I found the neat little clip.exe in the system32 folder.

    d:\prithvi\Setup>clip /?
    
    CLIP
    
    Description:
        Redirects output of command line tools to the Windows clipboard.
        This text output can then be pasted into other programs.
    
    Parameter List:
        /?                  Displays this help message.
    
    Examples:
        DIR | CLIP          Places a copy of the current directory
                            listing into the Windows clipboard.
    
        CLIP < README.TXT   Places a copy of the text from readme.txt
                            on to the Windows clipboard.
    

    So clip does what I was exactly looking for. Its a neat tool and I have grown fond of it. Guess how I pasted the output above. I ran clip /? | clip :-)

  • I know the answer (it's 42)

    using UIAutomation events

    • 5 Comments

    In my previous post I had written about how UIAutomation (UIA) can be used to drive user interfaces. UIA was designed to serve both assistive and test-automation requirements. Both of these require that user interfaces fire events to notify clients that some thing happened on them. Assistive tools like screen readers can notify the user (e.g. new dialog has come up) or automation tools can use this to wait on completion of some action. UIA supports these scenarios by the use of UIA events. User-interfaces fire these events and client applications can subscribe to them to "listen" to changes in the user interface.

    UIA works across UI technologies and provides bridges (providers) for existing accessibility technologies like Microsoft Active Accessibility (MSAA) so that they work seamlessly through UIA. MSAA uses WinEvents to notify other applications of such change. UIA wraps these up and also exposes them as UIA Events.

    Its easy to listen to these events. The following code subscribes to events so that we are able to listen to all invokes (as in button clicks) and all menu open/close events. It adds OnUIAEvent as the handler for the event which displays it

    UIAEventHandler = new AutomationEventHandler(OnUIAEvent);
    Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent,
    AutomationElement.RootElement,
    TreeScope.Descendants, UIAEventHandler);
    Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent,
    AutomationElement.RootElement,
    TreeScope.Descendants, UIAEventHandler);
    Automation.AddAutomationEventHandler(AutomationElement.MenuClosedEvent,
    AutomationElement.RootElement,
    TreeScope.Descendants,
    UIAEventHandler);
    public
    void OnUIAEvent(object src, AutomationEventArgs args)
    {
    AutomationElement element;
    try
    {
    element = src as AutomationElement;
    }
    catch
    {
    return;
    }
    string name = "";
    if (element == null)
    name = "null";
    else
    {
    name = element.GetCurrentPropertyValue(
    AutomationElement.NameProperty) as string;
    }
    if (name.Length == 0) name = "<NoName>";
    string str = string.Format("{0} : {1}", name,
    args.EventId.ProgrammaticName);
    Console.WriteLine(str);
    }

  • I know the answer (it's 42)

    Multiple desktop support in Windows

    • 15 Comments

    In my previous job I worked in the development team of Adobe FrameMaker. This product shipped on Sun Solaris, Windows and Mac. I worked parallely on a Windows box, a Sun Blade system and a PowerMac G5. So I got used to the best of all of them.

    Solaris (and many other window managers) supports multiple desktops for each user and easy swtiching between them. I got used to have 4 desktops and spread my applications across them. One had all the coding stuff like the editors and debuggers and the other had email-client and browser and so on. I always felt unhappy that Windows didn't support this. It was much later when I came across the multi-desktop Win32 API's. After playing around a bit with them I was really surprised that Windows (XP/2000/2003) didn't expose this feature directly. Later I found Microsoft Power Toys for XP which supported multi-desktops. I assumed that Vista Window Manager will have this directly. But unfortunately it does not (see the feature list here). 

    Using the Windows Desktop API's its extremely easy to create multiple desktops and switch between them. The following code creates a new desktop name MyDesk and launches Windows explorer on it and switches to the newly created desktop

    IntPtr hDesk = Native.CreateDesktop("MyDesk", IntPtr.Zero,

    IntPtr.Zero, 0, AccessRights, IntPtr.Zero);

    STARTUPINFO si = new STARTUPINFO();
    si.cb =
    Marshal.SizeOf(si);
    si.lpDesktop =
    "MyDesk";
    PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
    bool result = Native.CreateProcess(null, @"C:\WINDOWS\explorer.exe",
    IntPtr.Zero, IntPtr.Zero,
    true, NORMAL_PRIORITY_CLASS,
    IntPtr.Zero, null, ref si, ref pi);

    Native.SwitchDesktop(hDesk);

    Check out http://www.pinvoke.net for the C# signatures for these Win32 api's. Similarly is easy to enumerate all the desktops

    delegate bool EnumDesktopsDelegate(string desktop, IntPtr lParam);

    private
    bool DesktopEnum(string desktop, IntPtr lParam)
    {
    Console.WriteLine(desktop);
    return true;
    }
    Native.EnumDesktops(windowStation,
    new EnumDesktopsDelegate(DesktopEnum),
    IntPtr.Zero);

Page 1 of 1 (7 items)