Custom Expression Builders

Posted Friday, January 7, 2005 8:32 AM by C-Dog's .NET Tip of the Day
I got a new MSDN magazine in yesterday, so there is actually some new content.  A while back I talked about expressions in ASP.NET (i.e.: <%$ ConnectionStrings:ReservationsConnectionString %>) and I mentioned that there is a way to create your own.   At the time, I didn't know how to do that.  According to Marcus that was "Lame!".  So now I am following up, and showing you how to implement a custom expression builder.
 
As an example (straight from MSDN), if you wanted to display the current version of ASP.NET, we can make a custom expression builder like this:
 
<%$ Version:MajorMinor %>
 
You can create your custom expression logic by building a new class and inheriting from ExpressionBuilder.  In this class you must override the GetCodeExpression method.  This method takes multiple parameters.  The BoundPropertyEntry parameter contains the text to the right of the colon expression.  To access that text you use the Expression property of that parameter.
 
public class VersionExpressBuilder : ExpressionBuilder
{
      public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext content)
      {
             // check to see what the parameter of entry.Expression was
             if (entry.Expression == "MajorMinor")
             {
                   return new CodePrimitiveExpression(String.Format("{0}.{1}", Environment.Version.Major, Environment.Version.Minor));
             else
             {
                  // add more conditionals here
              }  
             }
       }
}
 
To register the expression builder, add the following section to the web.config.
 
<compilation>
     <expressionBuilders>
           <add expressionPrefix="Version" type="VersionExpressionHandler">
     </expressionBuilders>
</compilation>
 
This is obviously a simple example, but you can easily see how we could adopt this to get data from XML files, etc.  This could easily replace our custom label controls and things like that.
 

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=203