.NET, LINQ, Sitecore

Inheritance techniques in Sitecore ASP.NET CMS

There are two techniques for inheritance which are commonly used in all Sitecore solutions; hierarchical inheritance and template inheritance. Sadly, Sitecore offers no straight forward out-of-the-box API methods for the two techniques. This post describes some simple and neat ways of implementing these techniques – and also shows of how to use extension methods in .net to extend Sitecore and ASP.NET classes. This post was partly inspired by the extension method contest at the Learn Sitecore website.

Template inheritance:

Template inheritance is an integral part of Sitecore which I hope that all of you Sitecore fans out there use extensively in your solutions. At Pentia, template inheritance is so vital that in practice, you will see no item.TemplateID == SomeID or item.TemplateKey = "sometemplate" in any of our code, just like you (hopefully) would never use MyObject.GetType().Name == "MyClass" in C#.
No, we always use the following extension method:

public static bool IsDerived(this Item item, ID templateId)
  if (item == null || templateId.IsNull || item.Template == null)
    return false;
  TemplateItem templateItem = item.Database.Templates[templateId];
  if (templateItem == null)
    return false;

  Template template = TemplateManager.GetTemplate(item);       
  return template != null && (template.ID == templateItem.ID || template.DescendsFrom(templateItem.ID));

The method is used as item.IsDerived(“MyTemplate”) just as you would always do MyObject is MyClass in c#. Sadly, Sitecore offers no obvious way to do the same out-of-the-box….wait… oh yeah, you could naturally do Sitecore.Xml.Xsl.XslHelper.IsItemOfType()

Hierarchical inheritance:

While template inheritance is used to give all content of different types the same properties, hierarchical inheritance in Sitecore is slightly different. This is primarily used to allow a piece of content, a setting or a configuration to propagate down a branch in the tree – i.e. propogate down a number of content types which can be totally unrelated, but grouped together solely because of their content position. For example, this could be used to apply a given design theme to an entire subsite within you site. Using hierarchical inheritance, extension methods and Linq, this could be accomplished as such (pardon the train-wreck):

protected void Page_Load(object sender, EventArgs e) {
  var theme = this.GetDataSourceItem().GetAncestorOrSelf().First(i => i.IsDerived("HasTheme")).Fields["Theme"].Value;

In this example there are – besides the IsDerived extension method described above – two very useful extension methods:

GetDataSourceItem extends the ASP.NET UserControl to provide easy access to the DataSource set on a sublayout and is implemented as follows:

public static Item GetDataSourceItem(this UserControl control)
  Sublayout sublayout = GetSublayout(control);
  if (sublayout == null)
    return null;
  string dataSourcePath = sublayout.DataSource;
  return !String.IsNullOrEmpty(dataSourcePath) ? Context.Database.GetItem(dataSourcePath) : null;

GetAncestorOfSelf extends item to return a list with the item itself and all its parents – and this is naturally where the key to hierarchical inheritance lies:

public static IEnumerable<Item> GetAncestorOrSelf(this Item item)
  do {
    yield return item;
    item = item.Parent;
  } while (item != null);

I hope this post shows you how some simple extension methods can give you a lot of power in your solutions.

.NET, Architecture, publishing, Sitecore

Drawing the customization line

Sitecore is an extremely flexible system; in fact most of Sitecore is built with the extensibility and customization functionalities which is provided. This includes pipelines, events, commands, SheerUI, providers and more. All in all: there is not much which cannot be achieved in Sitecore and only the imagination of you and your client sets the limits of customizations – and believe me, in my work of helping out clients and Sitecore partners all over the world, I’ve seen Sitecore completely twisted in many ways. I’ve seen Sitecore’s entire layout engine replaced with an item based layout definition, with subitems representing placeholders and subitems representing presentation elements. I’ve seen publishing and item saved pipelines so crammed full of custom functionality that performance was non-existent and I’ve seen XSLT’s with one line of code: a call to an extension function which would return an entire HTML structure as a string.

So where do we draw the line in the holy name of bending functionality and giving the customer “what they want”? Remember:

  • Convincing the client to choose standard functionality is also an option.
  • Each change of standard Sitecore functionality is potentially expensive – for you and for the client.
  • If possible, do not replace Sitecore functionality, extend it.
  • Think about what you put into Sitecore: Content and functionality can be accessed through .NET code and does not necessarily need to be added to the Sitecore DB’s or in a pipeline.
  • Keep track of your customizations – source control it and document it.
  • Remember that your customizations will have to upgrade with Sitecore.
  • Stay true to yourself: If it feels wrong, don’t do it.

In short, just because you can does not mean that you should:-)

Introduction, Sitecore

Getting your Sitecore project right

This post is for you clients who have already selected Sitecore as your new website platform and is starting up a new Sitecore project.
Here are a couple of my thoughts on how you can get your Sitecore project on the right track from the beginning, by setting the stage for a good collaboration with your implementation partner.

The website you a building today should also be the website for tomorrow and hence the website you are building should be extendable, flexible and scalable. It is absolutely possible to build a Sitecore web platform which will last many iterations – considering that you take this into account early in the process.

Select your implementation partner carefully

Your implementation partner is the single most important collaboration partner in your project. They bind everything together; requirement specifications, user experience design, hardware, software, domain knowledge and more, and is therefore crucial for the project’s success. Therefore your primary focus initially in your project should without doubt be to find the right implementation partner.

In my opinion, what you should focus on is:

Human chemistry: A website is not primarily a technological project, but a communication project. Therefore select a partner with whom you can communicate openly and freely. If you sense that they are listening, factors as for example domain knowledge is less important.

Experience: Sitecore is not a difficult tool to learn – but is takes time to master. Therefore, try to find a partner which has multiple large scale projects under its belt, and preferably with projects which has undergone a number of iterations.

Technology based: In my experience, companies which are technology based, i.e. which focuses primarily on the integration and platform parts of the solutions compared to the user experience driven companies, e.g. design agencies, makes more future proof Sitecore solutions. Therefore if you are looking for someone to build your future webplatform as opposed to just your next website, opt for a company with vast knowledge of Microsoft .NET and surrounding technologies.

References: Most implementation partners can most likely show an impressing list of references – but please do not stop there. Call their references and enquire about support, quality etc. Hearing whether their existing customers have gotten value for money is very useful.

Don’t be too specific in your requirement specifications

My suggestion is that you use your implementation partner as a sparring partner on requirements. Remember that these guys have built other solutions before yours and might bring experience, skills and functionality which will benefit you. Also, allowing multiple implementation partners to suggest different solutions to your website’s objective – as opposed to a RFP checklist – will allow you to better evaluate their creativity.

Therefore, in the specifications, try to explain the objectives you have for your company, users or editors, instead of the precise functionality. In Pentia we have had multiple requests for debate forum functionality in solutions – which in our experience is a prime example of a specific functionality which is often never used by users. By explaining which objective the clients wanted to achieve on the website, instead of the specific functionality, we could have advised better, earlier in the process and given more value to the client. By the way; in most cases we managed to dissuade the clients to actually implement the debate forum, and used the precious development time for something much more valuable.

In short: Requirements change. Therefore, being too specific and detailed about functionality already in the RFP process will most likely get you a whole lot of expensive, unused functionality.

Be open about your development budget

This is in my book a no-brainer. The only reasons for not being open about the budget are if you adopt the “they-are-all-thieves-and-robbers” attitude or if you hope to haggle your way to a cheaper website. In both cases, you are doing yourself and your website a whole lot of damage.

First of all, you have to trust your implementation partner, as they hold an immense power to make your project a success or failure. If you don’t, find another partner. Secondly, this is not a standard product you are buying. If you push your implementation partner on time or money, they have but one place to push back: quality. This basically means that your solution will be in a worse state, bringing lower reliability or higher support cost.

Therefore, a selection process is not about getting the lowest price or best solution description. It’s all about finding the implementation partner which you trust the most. And if you found that implementation partner, why not be open about mostly everything, including budget?

Bring your partners on board early

There is a lot of benefit in bringing in all your partners as early in the process as possible – this means both strategy and design partners and well as implementation and hosting partners. Each domain has something to bring to the process and can potentially save you a lot of money and hassle. Getting the implementation partner and hosting partner to talk together as early as possible can save a lot of time in the deployment process, and in my experience, by getting the implementation partner involved in the strategy and graphical design process a lot of hours can be saved in communication afterwards. Furthermore implementation partners often have prebuilt functionality which – if it fits the project – can save you a lot of time and money. The earlier this is brought forward, the easier it is to fit into any graphical design or information architecture.


New releases, publishing, Sitecore, Uncategorized

Dedicated image server in Sitecore – part 2

I have earlier blogged about setting up a dedicated image server for Sitecore here. The implementation required some customization of the LinkProvider, but from Sitecore 6.3 it is possible to achieve the same just using configuration.

A dedicated media server can be used to serve media on a separate URL, so that you can optimize performance due to limitations on the amount of connections the browser can open to the domain, which I also described in the last post. Further it can be used to optimize your server for handling media and supporting a CDN.

As mentioned it is now possible to have a separate server for media by configuration. In this scenario you might have a dedicated publishing target for media, and this should just be a standard Sitecore installation, which then only handles media by directing the DNS for your image URL to this server. For instance I have setup three Sitecore installations – one as a content manager server, one as the dedicated image server and one as content delivery server. The domain for my content management server is http://sitecore63/, the one for my image server is http://sitecore63imageserver/ and the content delivery server has the domain http://sitecore63cd/. What I then want to achieve is:

  1. That my content management server serves images in the normal way, so that the editors can insert, alter and preview images without having to publish.
  2. On my content delivery servers I want my images to be served by the image server.

The first goal is easy. I just leave every configuration to the standard. This means that the content management server serves media itself.
The second goal requires some configuration changes. On the content delivery servers I must make all media references point to the image server. This can be done by setting the Media.MediaLinkPrefix in the web.config to the domain name of the image server plus the media prefix I want. For instance like this:

<setting name=”Media.MediaLinkPrefix” value=”http://sitecore63imageserver/~/media/” />

This means that all media items on the content delivery server(s) will be prefixed with the above url:

<img width=”128″ height=”128″ alt=”” src=”http://sitecore63imageserver/~/media/Images/user.ashx?w=128&amp;h=128&amp;as=1“>

So in this scenario the html is delivered by http://sitecore63cd and the image is served by http://sitecore63imageserver. In the content management environment, the media is served locally. Now this is a lot easier, than the customization you needed in older versions of Sitecore.

dedicated image server in sitecore

If you want another media prefix then the standard /~/media, you also need to make the media server handle these requests as media. This is done by adding the prefix to the <mediaPrefix> element in the web.config and add the prefix to the customHandlers section in the web.config.


Hidden functionality: The XPath Builder

Maybe it is just me, who never found it, but after a support request I was made aware of a feature in Sitecore, I have missed for years. I thought I’d just share it, if there were any others like me, who wasn’t aware of the great Sitecore application XPath Builder.

Whenever I create a template which uses a Sitecore Query to populate a multilist field with items, I always spend a little too much time figuring out the correct syntax for the Sitecore Query. But no longer… now that I have found the XPath Builder!

The XPath Builder is triggered in the Developer Center through the Tools menu. The application helps you build the right query and shows the result of the query:

Sitecore XPath Builder

The XPath Builder in Sitecore

Yay! What a great tool!

New releases, Sitecore

Sitecore Rocks – preview the future of Sitecore development

Something really cool happened today!

A new tool called Sitecore Rocks has been released in a CTP (Community Technology Preview) version – a early sneak peek. The tool, although a little rough around the edges, really shows a bright new future for Sitecore development, a future where we as developers do not need to muck about with browsers interfaces, only to connect our code, .NET pages and user controls into Sitecore. Now we can stay within in the tool we use and like, Visual Studio.

Together with the Team Development for Sitecore module from Hedgehog, this tool looks to be a must-have in the Sitecore developer toolbox.

In short, Sitecore Rocks is a Sitecore editing environment in Visual Studio. The environment naturally does not contain the complete set of features of the Sitecore content editor, but is focused on the features we as developers use. This includes for example:

  • Quick and easy navigation in the content tree and on the item editor.
  • Multi-item editing.
  • Linking Visual Studio project to Sitecore, and automatic creating of layout related items in Sitecore from your .NET files.
  • Live Sitecore log viewer.
  • Job viewer allowing you to examine running tasks in Sitecore.
  • Edit rich text fields in Visual Studio HTML editor/designer.
  • Easy interface for layout management.

You can watch a video of Lars Fløe Nielsen presenting some of the Sitecore Rocks features here.

In my view, the tool is very nice and definitely a vision of what’s in store for us as developers, but the tool is still in the early phase and still has a lot of unused potential. Personally I feel that one of the most promising features is the ability for everybody to extend the functionality, and hopefully this will create a flood of shared source plug-ins with really useful features. Of the top of my head, I can mention countless possibilities, so drop a comment if you have a lot of time on your hands 🙂

The tool is available through the Visual Studio 2010 Extension Managers Online Gallery – just open it up in Visual Studio and search for “Sitecore” – or download Sitecore Rocks from the MSDN:

New releases, Sitecore, Uncategorized

What TODO – in Sitecore 6.3

Sitecore 6.3 was recently released. A lot of great improvements was included in this version – for instance support for multiple backend web servers and Windows Azure support. Read more about it in Marco Tana’s blog post and read more about the event queue on Adam Conn’s blog.

Besides these new features  a huge amount of bug fixes has been included. Some of them quite important; some of them quite funny…

Almost two years ago I wrote the blog post What TODO? In short I described the somewhat weird way of marking TODO’s by the kernel develepors at Sitecore. Well guess what… In Sitecore 6.3 they thought they would finaly do something about it. It has now…. been marked as obsolete (?!).

“The Sitecore.Todo class has been marked as obsolete. (323278)”

I must admit it made me laugh again. Why not just remove it, when you decide to do something about it?

.NET, Architecture, Sitecore, Uncategorized

5 worst code smells in Sitecore

Last year I wrote a blog post on doing code reviews on Sitecore. While dealing with conceptual issues it doesn’t really say what to look for in code, when evaluating the quality or to evaluate if any wrong decisions have been made when developing the solution.  Therefore I wanted to wright a post about the top 5 code smells I look for, when I am trying to evaluate or trouble shoot a Sitecore solution. These code smells often indicate that the developers have gone down the wrong road and there is something fundamentally wrong in the architecture.

So here goes:

1) Using the descendant axes in xpath expressions:

This one I especially look for, when I am looking at a site which doesn’t perform. It may be used in some cases, but very often I find that a developer has used this to generate relations between content and thereby iterating over the complete content tree. This works fine in development where there are a few hundred content items. However in production where thousands of items are created this simply breaks the performance of the site – especially after publishing which clears the HTML cache.

The descendants can be accessed in multiple ways. In XSLT it normally looks like this:
<xsl:for-each select=”$sc_currentitem/descendant-or-self::item”>
</xsl:for-each>Or like this:
<xsl:for-each select=”$sc_currentitem//item”>

In C# using the Sitecore API it is most often accessed like this:


2) XSLT Import:

This is related to a point in the post about code reviews on Sitecore, where I argue that overcomplicated functionality and logic in XSLTs, is a problem. If you need to do an import of another XSLT in your rendering, you probably do it to call a method or in another way try and reuse functionality. If you want to do this, don’t use XSLTs! XSLTs should only – if you really want to use them at all – hold simple presentations.
XSLTs can be imported like this:

<xsl:import href=”YourOtherXslt.xslt” />

3) Explicitly accessing the master database

Although this can be needed in some cases and especially in scheduled tasks or other backend functionality, most often it is because the developer haven’t thought the issue through or if they have made a wrong decision of how data entered by the user should be stored.
The master database is most often used like this in c#

Database masterDatabase = Database.GetDatabase(“master”);

If you see a call like this, your solution is most likely not ready for staging, where there is no access to the master database from the content delivery server. You should generally use something like this:

Database database = Sitecore.Context.Database ?? Sitecore.Context.ContentDatabase;

This means you operate on the context database and on the content delivery databases this will be the web database and in preview you will use the master database, which is probably what you want.
If you need to write something to the master database, you first need to decide if this is a good idea at all. If you write to the master database from your frontend, you make yourself vulnerable for malicious attack, as people from the outside can enter data into the master database. Normally we handle user entered data in a custom database or parse all user created content to ensure that the master database won’t be flooded with data.
If you really need to access the master database, you should create a service that handles access to the master database, so that your solution is ready for staged environments.

4) XSLT extension over 100 lines of code:

This point is closely related to point number 2, but I really see a lot of issues with XSLTs which have been used wrong and this creates a lot of issues later on in the project lifecycle. If you have an XSLT extension with over a hundred lines of code, chances are, that the developer made a wrong decision when creating the XSLT; instead he/she should have created a sublayout.
XSLT extensions are functional programming and you should use an object oriented approach, so my advice is not to use XSLTs at all, unless you are doing something really simple. Otherwise your solution will become harder and harder to maintain, as utility methods like the XSLT extensions are very hard to understand and couplings in the renderings themself are difficult to map.
You can find all registered XSLT extensions in the web.config under xslExtension and it looks something like this:

  <extension mode=”on” type=”MyNamespace.XslHelper, MyAssembly” namespace=”http://www.example.net/helper” singleInstance=”true”/>

5) Clearing of cache

This may seem obvious to some, but I have seen surprisingly many methods, which cleared the entire Sitecore cache including the data and item cache. If you see this in your code and it is needed, chances are, that you have an architectural issue in your solution. It should most rarely be needed to clear the cache, unless it is after a publish and Sitecore handles this automatically. I have heard many reasons for clearing the cache including an issue, where the developer argued that it was necessary, as he wrote directly to the Sitecore database with a SQL statement, and then Sitecores cache wasn’t updated.
If you experience something like this, the issue is of cause not the cache, but that you don’t use the Sitecore API to read and write data from the database.
The caching is most often cleared like this:


This is just some of the things I have seen many times, but I know there are many other bad code smells when developing Sitecore solution. Do you have any other code smells to share?

IndexViewer, Lucene, New releases, Sitecore

Sitecore Lucene index viewer 1.2 released

Last week I was contacted by the Sitecore Shared Source coordinator Jimmie Overby and he told me that a guy in the Sitecore Ukraine office had made some changes to the Sitecore Lucene IndexViewer, I released some time ago. At first I was a bit sceptic about it, so I asked to review the code changes and see the new functionality. So I installed the new package and looked through the code, and I discovered that the Sitecore Ukranian Vyacheslav Tronko (don’t ask me to pronounce it:)) had done a fantastic job!

Not only had he added some very nice features but he had rewritten some of the code so the application is more stable and extendable. So I really appreciate his work!

The new features are:

  • Possibility to browse indexes defined in the new search section in the web.config
  • Rebuild indexes through the IndexViewer (which is really nice, as you can’t rebuild the new type of indexes any other way)
  • Optimize indexes.
  • Improved usability and look-and-feel of the application

So go take a look at the changes at http://trac.sitecore.net/IndexViewer 

If you want to see some screenshots of the new features, take a look here

What I would like to add next, is extended search functionality.

New releases, podcast, Sitecore

Sitecore podcast launched

Over at Learn Sitecore my coworker Jimmi Lyhne Andersen and I have just launched a brand new Sitecore podcast. Hopefully you will all like it and hopefully it will bring more article contributors to Learn Sitecore.

In the first episode we interview Sitecore CTO John West. We talk about Dreamcore and Sitecore in general. Check it out at: http://learnsitecore.cmsuniverse.net/en/podcasts.aspx