Using a Custom Expression Builder in MOSS

18 Mar

It’s pretty easy to create a custom expression builder so that you can use custom expressions in your MOSS Master Pages and Page Layouts.

(Check Out The: MSDN Documentation Page)

Expression builders allow a declarative expression syntax  which lets you substitute values into your page at run time.  They are fantastic for referencing resources, localization, app settings, etc.

Here’s an example of an expression builder in use in the default RedirectPageLayout.aspx, it is providing the value for the name attribute:

The above example uses the SPUrl expression builder, which knows how to handle the ~sitecollection and ~language keywords, and swap them out with other values before the page is processed.

So, how do you make your own?  It boils down to 5 steps, and they are all easy!

  1. Create yourself a new c# project, and create a class that inherits from: System.Web.Compilation.ExpressionBuilder
  2. Add the [ExpressionPrefix("Name")] metadata to your class.
  3. Override the GetCodeExpression(…) function and return a CodeExpression object.
  4. Strong name your assembly and add it to the GAC.
  5. Add an entry into your web.config to call out your assembly in the ConfigurationcompilationexpressionBuilders section of the config file.

Here is a simple expression builder based on (read: stolen from) something my colleague threw together as part of a MOSS localization project (I’ll dive deeper into how we re-rolled variations in a future post!)  It works similar to SPURL, it takes in a path, and replaces keywords using the switch statement.  A lot of expression builders will work in this way.

First, the C# class:

The additions to the web.config:

And how you could use it in a page:

The expression builder would replace ~sitecollection and ~language per the switch statement in our class.

(Which happens to be a bit different than the MOSS built in SPURL expression builder, but this is just an example and we’ll cover why that might be useful at a later time!)



One of the comments left here mentioned that people were having trouble using this with no-compile pages.  If you follow the MSDN article at the beginning of the post you’ll see that you can enable it for no-compile pages by setting an extra property and supplying an evaluation function:

Leave a Reply

Your email address will not be published. Required fields are marked *