ItemURIs are useful!

I was down at Sitecore’s offices for a training course the other week and got shown how useful the URIs for Sitecore items can be to your code – something I’d managed to miss before. So in the spirit of sharing, if you’ve not thought about uses for URIs, have a think about this:

It’s a fairly common scenario in Sitecore code: You need to pass details about a specific item between two bits of code, but due to some sort of process boundary you can’t pass the specific Item object. Given that a specific bit of content in Sitecore is specified by its database, identifier, version and language, how can you pass all that data across a boundary easily?

Well it turns out that the answer is the ItemUri object that’s associated with each item. You can fetch this simply. For example, for the context item:

var theUri = Sitecore.Context.Item.Uri;

If you call ToString() on the ItemUri for the /sitecore item you get something like this:


It’s specifying all of the properties of the item in one string – The database, ID, language and version.

When you want to turn this data back to an Item object you only need to do two things:

var theUri = ItemUri.Parse(uriString);
var theItem = Sitecore.Data.Database.GetItem(theUri);

You need to parse the string version of the uri back into a ItemUri object and then you can use a special overload of the GetItem() method (which is a static method on the Database class) to retrieve the correct item for that URI.

Simple, huh?

This is particularly useful if you need to write a record of a specific Sitecore item to process into some sort of persistent queue (eg in a database table) or you’re passing an item to a bit of custom user interface (like a Sheer UI dialog box) where all you can pass across is are strings. In this case it lets you pass one string rather than four.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s