ASP.NET Expression Builders - Part 2 - Using them for Localisation

An expression builder is invoked by ASP.net when it transforms the ASP.net server control markup into C# code ready to be compiled and then rendered out, allowing code to be invoked to set properties on controls without having to put it into the coded-behind.

A specimen expression builder class is below:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
using System.CodeDom;
[ExpressionPrefix("L10N")]
public class LocalisationExpressionBuilder : ExpressionBuilder
{
    public LocalisationExpressionBuilder()
    {
    }
    public override bool SupportsEvaluate
    {
        get
        {
            return true;
        }
    }
    public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        return entry.Expression;
    }
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        CodeExpression[] inputParams = new CodeExpression[] { new CodePrimitiveExpression(entry.Expression) };
        return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()),
                                              "GetRequestedValue", inputParams);
    }
    public static object GetRequestedValue(object expression)
    {
        string expressionString = (string)expression;
        if (expressionString == "a.localisation.string")
        {
            return "b";
        }
        else
        {
            return expressionString;
        }
    }
}

This basically allows a server control to be marked-up as follows:

<asp:Literal runat="server" Text="<%$ L10N: a.localisation.string %>

In that example, the "Text" property will be set to "b", if the string in the expression was anything else, it would be echo'd back. The code in the static "GetRequestedValue" method could do anything. In my working solution it connects to the database.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment