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.