.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:-)

.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?

.NET, New releases, Sitecore

Will dynamics in .NET 4 change the way we do Sitecore?

I am spending my time these days walking the halls of Berlin Messe at the Microsoft TechEd 2009. One of the interesting upcoming features of .NET 4 is the introduction of dynamic language support in the .NET Language Runtime. This does not only mean that you can write your .NET code in dynamic languages such as Python (IronPython) and Ruby (IronRuby), but also that you can use some of the dynamic features from C#. With the introduction of the dynamic type keyword, method calls and member access can be evaluated at runtime instead of at compile time (previously known as late-binding). This does not mean that C# is no longer a type safe language, it merely means that the language now provides a more “syntax correct” way of accessing those dynamic types of data, we previously used to access via strings, invokation, reflection etc. Examples of dynamic data models includes COM, the HTML DOM and XML.

Another one of the dynamic types of data we all works with each day, is Sitecore. The structure, i.e. templates and fields, we are coding up against changes constantly, and Sitecore provides a string based way to access specific items and fields and values in fields. Some of these dynamic types are exposed via classes in the Sitecore API, e.g. the fields type classes in the Sitecore.Data.Fields namespace. In Pentia we have a concept we call Sitecore wrapper classes, i.e. classes which we custom write to provide a proper interface to items of a given template. Writing these classes are tedious and potentially error-prone, which is why we are working on code generator for generating these classes (similar to e.g. LINQ to SQL). But with dynamics in .NET 4, we have a way of eliminating these classes completely, while still maintaining a proper syntax – and hopefully Sitecore will implement this to our common advantage. Here is an example of how code from the current version could look in a future version of Sitecore:

//BEFORE: .NET 3.5 Framework, Sitecore 6
public string GetContextItemDocumentImage() {
  Item item = Sitecore.Context.Item;
  ImageField field = ((ImageField)item.Fields["DocumentImage"]);
  return field.Src;

//AFTER .NET 4 Framework, Sitecore 7?
public string GetContextItemDocumentImage()
  dynamic item = Sitecore.Context.Item;
  return item.DocumentImage.Src;

Note that although the syntax differs, the actual functionality executed in both example would be the same. So, what does it require from Sitecore to do this? The secret lies in the System.Dynamics. IDynamicMetaObjectProvider interface or more easily, the DynamicObject class. This interface and class allows the derived class to provide its own resolving to e.g. members access and method calls via a number of virtual methods. The methods are Try based, which means that you should return false if the functionality is not supported, or e.g. a method with an invalid method is called. Some of the most important virtual methods which can be implemented via DynamicObject are:


A cast is attempted, trying to convert the dynamic type to a static.


An indexer is called, trying to get a value with a given id or index.


There is an attempt to get the value of a named member (e.g. a field or property)


A method with a given name and parameters is invoked.


There is an attempt to set the value in an indexer with the given id or index.


There is an attempt to get the value of a named member (e.g. a field or property)


An example of the above Sitecore 7 (:-)) implementation could therefore be:

namespace Sitecore.Data.Items
  public class Item : DynamicObject //...and other interfaces
    public override bool TryGetMember(GetMemberBinder binder, out object result)
      dynamic field = Fields[binder.Name];
      if (field != null) {
        result = field;
        return true;
     	return base.TryGetMember(binder, out result);

Let this be an inspiration to Sitecore for the next version – I for one truly hope we see something like this in the product.


Google Search Appliance, cool API’s

Google Search Appliance

Me and my colleague Brian Pedersen have been spending time in London (thx to Google London and Dave Gallerizzo of Fig Leaf) this week looking into the Google Search Appliance (GSA) – which is a really cool search product which I hope we will implement in a lot of future solutions. By the way, Pentia is now a Google Enterprise Partner 🙂

The GSA though, is a double edged knife – on one hand, it provides really good value out of the box (best of class in search relevance), and has a lot of nice features and configuration possibilities. On the other hand, the configuration interface on the GSA sucks! yes, it sucks! I would never expect any end-users to understand what happens in the UI, and in worst case, they will mess up the nice out-of-the-box functionality. Said in other words: the summer intern who wrote the config UI should be definately find work in a non-computer related sector.
This said, the GSA has some really cool API’s, which will allow you to provide nice functionality for your users:

Admin API
If you consider integrating a GSA in a Sitecore (or any CMS) solution, you should consider integrating some of the configuration directly in the CMS backend. Imagine users being able to tweak the biasing of content, or adding content to the “recommended” box in the top of the results directly in Sitecore. This is all available through the Admin API – which is nicely wrapped in .NET assemblies.
You can find the Admin API here.

Feeds API
The Feeds API allows you to insert content directly into the crawler queue. There are three options: web feeds, which simply adds URLs you want the GSA to crawl, url-and-metadata feeds, which allows you to add additional metadata to URLs being crawled (think adding metadata to PDF files), and content feeds which actually insert the html or binary data directly into the GSA.
You can find the feeds API here.

Policy ACL API
One of the strong sides of the GSA is the possibility to crawl and serve secure content, e.g. on your extranet or intranet. The problem though, is how to determine which URLs the individual users in your custom security solution has access to. This is where the Policy ACL (access control list) API comes handy. In short, it allows you to insert access lists in the GSA and map them to URLs – which again allows you to have fast secure queries – simple and wrapped in .NET.
Find the Policy ACL API here.

There are tons of other APIs and documentation on the Google Search Appliance on code.google.com.

.NET, Open source, Sitecore

Composite Layouts – keeping your stuff together

I’ve always been a big fan of keeping things that belongs together, together. This might be an obvious fact, but I sometimes find that in Sitecore, it’s not so easy to follow. If you read my post on agile Sitecore design, you’ll get my drift. But this post is on something much more practical, i.e. composing your layouts in Sitecore, and how something I choose to call composite layouts can help you make your practice better.

When it comes to putting your pages together in Sitecore, you have two choices:

You can choose to build up your entire page composition on your templates in Sitecore, i.e. choose a layout and putting all sublayouts, renderings etc. on a template (which is naturally the __standard values of the template). This method is in my book the most correct, as it allows you, your fellow developers and the administrators to see the complete structure of a page, without leaving Sitecore. Unfortunately Sitecore does not deliver any layout inheritance etc., so this way requires a lot of hard work and mouse clicking (“try adding a rendering to all pagetypes late in the process – phew”) and is potential place for mistakes. Also, the page designer and Webforms module copies the layout from the template, locally to the item – and trust me, you do not want your layout with 20 renderings spread over your 15 pagetypes and 356 local items (“try adding a rendering to all pagetypes late in the process – double-phew”).

So, unless you are committed to keeping your page composition in one place, and choose not to use the page designer and webforms, you are left with the second option – putting page composition in sublayouts. This is where you put renderings and other sublayouts directly in the .ascx file, either through Visual Studio or the Sitecore layout designer. The big problem I have with this option, is that you separate page composition into two places – Sitecore and the ascx files. This forces you to use two different systems to setup caching etc. and makes it difficult to overview the complete page composition.

Enter Composite Layouts:

Composite Layouts is a new type of rendering I developed for a large project, which bridges the gap between the two options. It utilizes the fact that even rendering items in Sitecore have a Layout field, and it merges a layout set directly on a composite layout item into the layout set on a template. I.e. a composite layout is pretty much like a sublayout, in that it allows you to group renderings and place them on a page as a unit. The exception is that all configuration is done in Sitecore and the renderings on a composite layout can be placed in all placeholders – even placeholders outside the composite layout.

Our Form pagetype is a standard document page (with the usual header, topmenu, title, leftmenu, footer, spots etc.) which renders a selected form (which is incidentally created using Webform for Marketeers) in the content area:

The DocumentPage rendering is a composite layout which is defined with the following layout:

Note that the layout has a NullLayout selected – this is merely because the Sitecore UI forces us to select a layout before saving the layout on the item. The NullLayout is naturally never rendered.

Just to make the point; in turn, here’s how what the HeaderBlocks composite layout contains:

As you can see, composite layouts uses standard Sitecore UI with no addition, and all I’ve had to do at this point is to create a Composite Layout template and add it to the insert options of the Sublayout Folder template. The template has no fields whatsoever.

So how do you get it to merge the layouts? First you create a class – let’s call it InsertCompositeLayoutRenderings – derive it from Sitecore.Pipelines.RenderLayout.RenderLayoutProcessor and insert it into the renderLayout pipeline in the web.config. The entry needs to be right below the InsertRenderings entry, as this unfolds all the renderings in the current item and fills the Sitecore.Context.Page.Renderings list.

Second, you implement the Process() method of your InsertCompositeLayoutRenderings class, run through the Sitecore.Context.Page.Renderings and detects any composite layouts in the list, parse the layout field in the composite layout item and call Sitecore.Context.Page.AddRendering for each rendering found. If you want recursive support, you merely give the renderings on each composite the same treatment.

Granted, the design has some flaws – e.g. all renderings are added to the end of the layout (theres no InsertRendering method), so you have to be careful about the placeholders you use and order of the composite layouts – but I still consider the solution to be much better than the two options first mentioned.

We could all hope Sitecore reads this post and implements something similar in a future version, but until then if anyone is interested, I’ll consider posting the code on the Sitecore shared source network.

.NET, Documentation, New releases, Sitecore

Sitecore learning portal launched

My cooworker Jimmi Lyhne Andersen and I are glad to announce that we have finally finished a project we have been working on for quite a while now; a complete learning site for Sitecore. Check it out at http://learnsitecore.cmsuniverse.net/


So what is it all about? Well we have been working with Sitecore for quite a while now, and we found that documentation was somewhat limited. Documentation revolves around SDN which is great as a reference (especially if the search functionality worked probably) and blog post by enthusiastic Sitecore developers. This leaves quite a gap, as there are no in depth article base and nowhere to go, if you want to start learning about Sitecore. Further there is only limited documentation for editors, server administrators and architects.

Therefore our vision was to create a site, which matches these target groups and goes in depth with the topics. Our mission is not to compete with SDN, as it is quite resourceful for snippets and references. Our mission is neither to compete with the blogs, as these are quite resourceful when you want biased opinions on Sitecore or new and interesting tweaks.

So in short learnsitecore.com is the place to go if you want to learn Sitecore or read in depth articles on different technologies which Sitecore uses. Right now there are a limited number of articles, but we hope to get some contributors and of cause write a lot of articles our self.


We hope you’ll find it resourceful and that you might be motivated to write an article or two.