I know the answer (it's 42)

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

March, 2006

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

    LINQ Expression tree to generate prefix notation of expressions

    • 5 Comments

    Yesterday I was goint through one of the LINQ hands on lab. I was always interested by the new Expression tree in C#3.0 and one of the expression tree sample in the lab grabbed my attention. I built onto it to create a postfix notation generator from any lambda expression.

    What are Expression trees

    Expression tree is a very interesting concept which allows creation of in-memory expression-tree's out of lambda expressions and then manipulate/inspect the expression as data. Expression trees are created as follows

    Expression<Func<int, bool>> filter = n => !((n * 3) < 5);

    Now filter contains the expression n => !((n * 3) < 5) as data and it can be manipulated and changed at will.

    Pre-fix notation generation

    This Expression tree is just as any other tree and can be traversed preorder to generate the prefix notation of the expression. So given the expression !((n * 3) < 5) it should be easy to generate the prefix form as in ! ( < ( * ( n  3 ) 5 )).

    I wrote up a small extension method that works on Expressions to print the post fix notation doing a preorder traversal as follows

    static void PrefixForm(this Expression exp)
    {
        if (exp is BinaryExpression)
        {
            BinaryExpression binEx = (BinaryExpression)exp;
            Console.Write(" {0} ", NodeTypeLookUp[(int)binEx.NodeType]);
            Console.Write("(");
            binEx.Left.PrefixForm();
            binEx.Right.PrefixForm();
            Console.Write(")");
        }
        else if (exp is UnaryExpression)
        {
            UnaryExpression unEx = (UnaryExpression) exp;
            Console.Write(" {0} ", NodeTypeLookUp[(int)unEx.NodeType]);
            Console.Write("(");
            unEx.Operand.PrefixForm();
            Console.Write(")");
    
        }
        else if (exp is ParameterExpression)
        {
            Console.Write(" {0} ", ((ParameterExpression)exp).Name);
        }
        else if (exp is ConstantExpression)
        {
            Console.Write(" {0} ", ((ConstantExpression)exp).Value);
        }
        else
        {
            Console.WriteLine("{0} is not yet supported", exp.GetType().FullName);
        }
    }
    
    Expression<Func<int, bool>> filter = n => !((n * 3) < 5);
    filter.Body.PrefixForm();
    

    Not all types of expressions like method call, delegate invokes are supported here. The tree uses ExpressionType enum to represent the operators and so I wrote a lookup table to convert them to the operator they represents. I should've used the enum.GetDescription but was feeling to lazy to get that up :)

    The complete code is available here. You'll need Visual Studio 8 and the Linq preview for RTM to build and run it.

  • I know the answer (it's 42)

    Spell check as an OS service

    • 6 Comments

    As Operating systems are maturing different features are finding its way into it. So much so that many software are totally becoming redundant as there USP is already a core OS feature.

    Recently I needed to include some spell-checking in a software that I was writing. I used interop in MS Office (Word in particular) to get this done. Since spell checking is so widely used I do think they should now become part of Windows. It'd be great if the context menu of text boxes have some think like "Check spelling" along with Cut/Copy/Paste.

    The issue is not that things like spell checking is hard to do. The issue is including new dependencies. Now I have a 30 line code that uses Word for spell checking but can I rely on MS Word being installed on all machines where the software will be deployed? This is where OS support comes into play. Someone even suggested using Web-services to get this done!!! That is simply not feasible both from perf as well as security reasons...

    The code I used goes as follows....

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Office.Interop.Word;
    using System.Reflection;
    namespace SomeNameSpace
    {
    class SpellCheck : IDisposable
    {
    private ApplicationClass m_winword;
    public SpellCheck()
    {
    m_winword =
    new ApplicationClass();
    }
    public void Dispose()
    {
    object savenochanges = WdSaveOptions.wdDoNotSaveChanges;
    object nothing = Missing.Value;
    if (m_winword != null)
    m_winword.Quit(
    ref savenochanges, ref nothing,
    ref nothing);
    m_winword =
    null;
    }
    public bool IsCorrect(string word)
    {
    object nothing = Missing.Value;
    return m_winword.CheckSpelling(word,
    ref nothing, ref nothing,
    ref nothing, ref nothing,
    ref nothing, ref nothing,
    ref nothing, ref nothing,
    ref nothing, ref nothing,
    ref nothing, ref nothing);
    }
    }
    }

    This can be used as in

    SpellCheck spellCheck = new SpellCheck();

    if(!spellCheck.IsCorrect(someWord))
    // not correct message

  • I know the answer (it's 42)

    Slicing and C#

    • 4 Comments

    Yesterday I discussing slicing with Manish. Since a lot of folks move into C# from C++, there is an initial tendency of carrying your old baggage of programming fears, gotchas at the back of your mind. Slicing ranks high in this list. Consider the following code

    class Employee
    {
    public:
        Employee(){}
        virtual ~Employee(){}
        virtual void DoWork() {
            cout << "C#, VB.NET, J#" << endl;
        }
    };
    class Manager : public Employee { public: Manager(){} virtual ~Manager(){} void DoWork(){ cout << "Outlook, powerpoint" << endl; } }; void MakeEveryoneWork(Employee emp,
    Employee *empPtr,
    Employee& empRef) { emp.DoWork(); empPtr->DoWork(); empRef.DoWork(); cout << endl << endl; } int main(int argc, char* argv[]) { Employee *emp = new Employee; MakeEveryoneWork(*emp, emp, *emp); emp = new Manager; MakeEveryoneWork(*emp, emp, *emp); return 0; }
    out put
    C#, VB.NET, J#
    C#, VB.NET, J#
    C#, VB.NET, J#
    C#, VB.NET, J#
    Outlook, powerpoint
    Outlook, powerpoint

    Here Manager derives from Employee and overrides the DoWork function. The MakeEveryoneWork function accepts all the three types of parameter passing techniques, by-value, by-pointer, by-reference. First an object of Employee is passed to it and then Manager is sent. In the case of passing by-value slicing occurs and Employee::DoWork gets called instead of Manager::DoWork as highlighted in Red.

    Slicing was a major pain point in C++ code, surfacing in parameter passing, exception catch blocks  (catch a base type instead of the most-derived type) and other places. So most C++ programmers in the back of their head have a slicing filter running. However, things have suddenly become easy with C#. There is no call by-value for reference types and hence the whole story of slicing is suddenly not there.

  • I know the answer (it's 42)

    I am sharing my office Mr.Infinity and The Professor

    • 6 Comments

    Today we had an all-hands meet (we are allowed to bring our other body parts as well :) ) in which Paramesh handed out our boxes (as we lovingly call them). Its the coveted Visual Studio 2005 everything under the sun version (a.k.a. VS Team Suite MSDN Premium Subscription).

    The first thing I did on coming back to my office is to put up the posters and display the box :). Its hard to explain how it feels when you see screen-shots of stuff you've coded being distributed in manuals. I just can't wait for Team Foundation Server getting shipped as well!!

    Khushboo pointed out rather politely that my work-place is looking geeky and that it'd never suite her. As if I care :)

    The Box

    The posters

    Screen shots of stuff I coded!!!

  • I know the answer (it's 42)

    Dynamic languages on .NET

    • 4 Comments

    Dynamic languages prove themselves immensly powerful at places you least expect them to be. I found this out when I started coding in Ruby some time back and I completely fell in love with Ruby when I started working on the webserver project. For the last 3-4 days I'm seeing reference to Ruby on .NET at many places. Most of the links point to a project in Queensland University of Technology which aims at creating a Ruby compiler on .NET CLR.

    Even inside Microsof there are a lot of dynamic language advocate and Microsoft is surely doing something in that space. Proof is here.

  • I know the answer (it's 42)

    We just got jolted

    • 1 Comments

    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

    • 1 Comments

    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.

Page 1 of 1 (7 items)