Sunday, August 23, 2009

CodeDom and Expression Calculator (1)

I have subscribed to .Net Rock podcast and I enjoy listening to this talk on weekly base. At the beginning of almost each talk Carl always gives a small section about one .Net framework library. It is a very brief information about the .Net library or namespace and some descriptions or usages about using it. Recently he mentioned something about Compiler to compile codes but he admitted that he does not know where to use it and how to use it. He just thrown it out.

This reminded me immediately about System.CodeDom namespace. I have used this to dynamically build source codes, to compile codes, to create an instance and to get result by calling a method of the instance. It is very cool stuff. I use this feature to get result of a expression such as:

    24*60*60

so that I can use expression in a configuration XML file. Since the expression is evaluated by building a snip of dynamic codes, the expression can also be a expression of C# codes like:
   Date.Parse(Date.Now.ToShrotDateString())

in the configuration file as a current date in a short date string. Eventually, the value will be a DateTime value as a property value.

I created a class called as ExpressionCalculator. Here is an examples of how to use the class to evaluate expressions:


int iVal = true;
ExpressionCalculator expCalc = new ExpressionCalculator();
expCalc.SetConfiguration("24*60*60",
    ExpressionCalculator.ECValueType.Integer).
    GetAnswer<int>(ref iVal);

Think about the snip codes to evaluate an expression. This is very simple. Here is an example:

using System;
public class ExpresssionEvaluation { // class name
  private int _value = 24*60*60; // type and expression
  public int GetAnswer()         // method to get result as type
  {
    return _value;
  }
}

What I need to evaluate an expression result is to generate a snip of codes with expression and expected type dynamically replaced. By using CodeDom classes, the snip of codes can be built and compiled. Then instance of ExpressionEvaluation can be created. Finally the result can be obtained by calling the method GetAnswer().

Interestingly, I found that the CodeDom compiler uses the exactly same compiler to compile the source codes in %tmp% directory. The assembly then is loaded by using Reflection to get all the classes, properties and methods. I found those background stuff while I had some compiler error with the snip of codes.

0 comments: