Introducing SPUrlExpressionBuilder to resolve SharePoint URL Tokens


Introduction

One of the great things when developing with SharePoint is being able to use URL tokens such as:-

  • ~SiteCollection – this will resolve to the current site collection root
  • ~Site – this will resolve to the current web root

For an extensive list of SharePoint URL tokens, take a look at Namwar Rizvi’s SharePoint Insight blog post, http://sharepoint-insight.com/2008/12/01/list-of-sharepoint-url-tokens/.

If you have done much with creating or modifying Master Pages or Page Layouts then these tokens become very useful to locate resources such as images, XSL or CSS files.

For example, to reference an image which is stored in a SharePoint Publishing web’s Site Collection Images folder you could use something like this:-

~SiteCollection/SiteCollectionImages/myimage.png.

Recently, I have been working with multiple language user interfaces and wanted to be able to display a different image based on the language. One of the steps to do this was to work out how to process these URL Tokens.

Solution

This is where the SPUrlExpressionBuilder class comes to the rescue. This class is part of the Microsoft.SharePoint.Publishing.WebControls assembly.

To evaluate a string with a url token like ~SiteCollectionUrl/Images/MyImage.png you can use the following SPUrlExpressionBuilder class’s method EvaluateUrlExpression().

string imagePath = SPUrlExpressionBuilder.EvaluateUrlExpression("~SiteCollection/Images/myimage.png").ToString();

 

Visual Studio Tip: Using SharePoint Site Url in Pre-Deployment and Post-Deployment scripts.


Within Visual Studio 2010 SharePoint projects you might want to use the SharePoint Site Url that you have specified for your SharePoint project in Pre or Post Deployment scripts.

The SharePoint Site Url value can be retrieved using the $(SharePointSiteUrl) variable.

Usage

For example, this variable could be used in a pre-deployment script to deactivate certain features for the debug configuration.

To add the Pre Deployment script do the following:-

  • From Visual Studio 2010
  • Open your SharePoint Solution/Project
  • Click Project Properties
  • Click the SharePoint Tab
  • Add the following script to the Pre Deployment Script text box.
echo SiteUrl: $(SharePointSiteUrl)
if "$(ConfigurationName)" == "Debug" (
stsadm -o deactivatefeature -name "Feature1" -url $(SharePointSiteUrl) -force
stsadm -o deactivatefeature -name "Feature2" -url $(SharePointSiteUrl) -force
stsadm -o deactivatefeature -name "Feature3" -url $(SharePointSiteUrl) -force
stsadm -o deactivatefeature -name "Feature4" -url $(SharePointSiteUrl) -force
stsadm -o deactivatefeature -name "Feature5" -url $(SharePointSiteUrl) -force
)

Hope that helps.

For more information on Pre and Post-Deployment steps see this MSDN Link:

How to: Set SharePoint Deployment Commands (http://msdn.microsoft.com/en-us/library/ee231534.aspx)

 

U4FVW5JMFNEH