Imtech SharePoint Gems: SPUrlExpressionBuilder
Recently, while working on a SharePoint solution I have rediscovered the SPUrlExpressionBuilder class – one of the many hidden gems of SharePoint 2007. After some research it turned out to be more than the URL tokenizer we know from WSSv3.
How does it work?
SPUrlExpressionBuilder internally uses the GetServerRelativeUrlFromPrefixedUrl(string) method which replaces the ~SiteCollection/ and ~Site/ tokens respectively with the values of SPContext.Current.Site.ServerRelativeUrl and SPContext.Current.Web.ServerRelativeUrl properties. There is a big chance that you know this already. SPUrlExpressionBuilder adds two new things on top of that.
First of all it adds a new prefix: ~language/. This prefix is being replaced by the value of the SPContext.Current.Web.Language property. So imagine having a tokenized URL like ~SiteCollection/~language/ and calling it from a site built using the American English Site Template: SPUrlExpressionBuilder would translate it to /en-US/. This functionality becomes very useful while working with localized resources but also on sites using Variations!
Another new concept used by the SPUrlExpressionBuilder is the Expression Builder itself. It allows you to use dynamic URL’s in the declarative markup of your Master Pages and Page Layouts. Knowing that you no longer need to create a custom control each time you want to reference a resource using a dynamic URL. You can use the standard available SPUrlExpressionBuilder class to do the job for you.
So what about these “gems”?
Both Windows SharePoint Services (WSS) 3.0 and MOSS 2007 ship with tons of great functionality. Because we don’t know most of it (and not just because it’s hidden or poorly documented – there is really a lot of it), we end up reinventing the wheel and programming the same stuff all over again while it’s there. To help you discover some of these hidden gems, I have decided not only to write about my findings but also to create some sample Application Pages which can help you understand how it all works and how you can benefit of it.
The first release of the SharePoint Gems is available on CodePlex: both as a WSP and the source code. The sample Application Page for SPUrlExpressionBuilder doesn’t contain any code behind: it works the moment you copy it to the 12\TEMPLATE\LAYOUTS directory.
If you choose to go with the WSP, the pages will be available in /_layouts/gems/ directory. As some of the functionality is based on the context, you may want to open these pages under different sites, languages, etc.