Jonas Stawski

Everything .NET and More

ASP.NET Custom Expression Builder For Azure

ASP.NET 2.0 brought a new feature called Expression Builder, which allows you to assign dynamic values to a control’s property. The syntax is very similar to the well known <%= value %> and <%# bind(“property”) %>:

<%$ expression %>


Please note the “$”. This syntax can be found mostly for connection strings when doing some declarative binding with ASP.NET:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" />


This built in Expression uses the connection string MyConnectionString found in the Web.Config.

It is a fact that with Azure it is better to store the AppSettings and Connection Strings in the CSCFG file, because the web.config is not changeable at run time due to the nature of Azure deployment model. Therefore we can’t use the ConnectionStrings Expression Builder.

The solution is to use Custom Expression Builders. All we need is a class that inherits from ExpressionBuilder and overrides the GetCodeExpression method. So to solve our problem and retrieve the ConnectionString from the CSCFG file we need the following class:

using System.CodeDom;
using System.Web.Compilation;
using System.Web.UI;
using Microsoft.WindowsAzure.ServiceRuntime;

public class AzureSettingsExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        return new CodePrimitiveExpression(RoleEnvironment.GetConfigurationSettingValue(entry.Expression));
    }
} 

We basically wrap the usual GetConfigurationSettingValue used with Azure with a CodePrimitiveExpression object.

We then register the Custom Expression Builder in the web.config:

<compilation>
  <expressionBuilders>
    <add expressionPrefix="AzureSettings" type="AzureSettingsExpressionBuilder"/>
  </expressionBuilders>
</compilation>


And use it from our aspx pages:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ AzureSettings:MyConnectionString %>" />


WARNING: this will break the QueryBuilder UI of the Configure Data Source wizard.

Happy Programming!

Add comment

biuquote
Loading