ASP.net Expression Builders 2 - 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 this Entry

This page contains a single entry by Robert Wray published on May 8, 2009 8:30 AM.

ASP.net Expression Builders was the previous entry in this blog.

ASP.net Expression Builders 3 - In the web.config file is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.04