How I structure Sitecore Templates

Templates are the building blocks for a Sitecore installation, they’re amazingly flexible and with capabilities such as inheritance you can produce an elegant architecture, or alternatively a complete mess. Here’s how I like to structure things:

Base Templates

BaseTemplatesFirst off I have a folder of base templates. These are the building blocks for all the fields that will end up in a component data source or an actual page via inheritance. By setting them up as a base template we can re-use the same field definition for things like headings, but more importantly it keeps them focused on a specific purpose rather including details of the entire eventual item.

One additional rule I have for base templates is that they should only contain one data section within them. This in turn helps keep them focused on a specific purpose.

Page Templates

PageTemplatesNext we have pages. You guessed it, a page template is what a content editor will create an instance of when they make a page. It’s responsibility is to bring together default presentation details, the set of fields on the page and insert options for the pages beneath it.

All fields are inherited from base templates and standard values are used to define the defaults for the page.

Additionally to make the CMS experience as easy as possible for the content editors an icon should be set so that a page type can be visually identifiable.

Component Templates

ComponentTemplatesA component template is the equivalent of a page template but for data sources.

Like page templates all the fields are inherited from base templates and standard values are used to define the defaults for the page. An icon should also be set to make content types easily identifiable by content editors.

Folder Templates

FolderTemplatesFolder templates are often overlooked but they are an essential part of creating a decent user experience.

Folder templates are created to define the insert options for components and site settings rather than having them set on the site content tree.

Where relevant a folder template should also include itself as one of the insert options so that content editors can organise their content into sub-folders.

Parameter Templates

ParameterTemplatesWhen a component needs some config to customise its look and feel that is not content, it can be better to use Rendering Parameters rather than a data source.

Site Setting Templates

SettingsTemplateA Site configuration template is useful to contain various global settings for a site. This could include things such as the Site Logo, Google Analytics account details etc. Settings should be segmented into logical sections that have been defined in Base Templates and then inherited.

It can also be useful to separate some settings into their own template item depending on the scenario of what the setting is for.

Group Into Folders

With each these template types created, you’ll end up with a tree structure that looks something like this.


Pipelines – remember the big picture

Sitecore pipelines are great. With them you can relatively easily add and remove functionality as you wish. Pipelines like httpRequestBegin, httpRequestProcessed and mvc.beginRequest are also really useful if you need some logic to run on a page load that shouldn’t really be part of a rendering. This could be anything from login checks to updating the way 404 pages are returned. However you do need to remember the big picture of what you are changing.

Pipelines don’t just effect the processes of the website your building, Sitecore uses them too. That means when you add a new processor to the httpRequestBegin pipeline, that’s going to effect every request in the admin cms too. Just checking the context item also isn’t enough as some things. e.g. opening a node in a treeview, will have the context of the node you clicked on!

Adding this snippet of code to the begining of your process should keep you safe though.

using Sitecore.Diagnostics;
using Sitecore.Pipelines.HttpRequest;
using Sitecore;
using Sitecore.SecurityModel;

namespace CustomPiplelineNamespace
    public class CustomPipeline : HttpRequestProcessor
        public override void Process(HttpRequestArgs args)
            //Check args isn't null
            Assert.ArgumentNotNull(args, "args");
            //Check we have a site
            if (Context.Site == null)
            //Check the sites domain isn't one for sitecore
            if (Context.Site.Domain != DomainManager.GetDomain("sitecore"))
            //Check that we're not in a redirect
            if (args.Url.FilePathWithQueryString.ToUpperInvariant().Contains("redirected=true".ToUpperInvariant()))
            //Check that we're not in the page editor
            if (Context.PageMode.IsPageEditor)

            // DO CODE

Sitecore xDB – How to get count of interactions

If you need to rebuild your Path Analyzer maps, Sitecore have a knowledge base article on how to do it here –

In the FAQ section it gives some info on how long you should expect it to take

Depending on the processing power of your server, your XDB configuration, this could take from minutes to hours. Most of the time is spent on bringing over and de-serializing XDB interaction data on the Processing Server.

For the reference, it takes approximately 2 hours on XDB with 7M interactions, running on a single server.

What it doesn’t tell you though is how you find out how many interactions your site has to process. The data is stored in analytics collection in your Mongo DB, so go there an then run…


Data Source vs Rendering Parameters

Control Properties

On the face of it being able to specify Rendering Parameters, or a Data Source on a control achieves a very similar goal. You want to componentise your page and not fill up your page type item with fields for specific renderings. Everything should be isolated in it’s own little compartment.

Linking a rendering control to a Data Source does this by moving all your data to a completely separate item, that can be re-used over multiple pages and even swapped out to do personalization or A/B testing.

Equally, using Rendering Parameters does this just as well. Just like a Data Source, you can create a template for the fields that need to be entered, and the data is kept in the same place that a link to a Data Source would be specified.

But what should I use?

The easiest way I can describe it is by asking, are you storing content or something else?

If the answer is content then you most likely want a data source. Alternatively, if it’s something else like some config for a filter, or a background colour you will most likely want a rendering parameter (but there could be exceptions).

Data Sources

Data Sources have some distinct advantages over a Rendering Parameter including:

  • Data can be edited in the Experience Editor inline in your page
  • Language versions are very easy to understand by content editors
  • Easily used for personalization and testing
  • Can be reused on as many controls as you like

These things all make a Data Source a perfect option for anything content related. Without them you loose some big features related to content and ease of use. There are times non-content is also a good option. e.g. A hero banner on a page could be used across multiple pages and as well a reusing the text, if a background colour is also customizable you would want to be re-using that too.

Rendering Parameters

Likewise Rendering Parameters also have there benefits:

  • Doesn’t create an extra item to publish. You just have to publish the page your editing, not the related data source
  • Easy to access in the control properties of the item your looking at, without having to find the related data source

These features make Rendering Parameters ideal for the non-content config of a control and removes non-content fields from your item templates. The thing to be aware of though is you can’t easily do A/B testing or personalization with a rendering parameter, so while it’s nice for your items to only contain content, that might not be the only thing that’s being tested.

How about both?

There is also nothing to stop you using a Rendering Parameter and a Data Source at the same time.

You could have a situation when a Data Source is being used to populated the content on multiple different controls. Each control may have some additional config needed, such as text colour or text size. Keeping this data in the data source might become problematic as on one rendering your text may need to be black, whereas on another it may need to be white. By moving these fields to Rendering Parameters, you keep the benefit of a shared Data Source for content, while the Rendering Parameter takes care of the presentation config.

Sitecore html cache not clearing on publish

So you’ve got separate content management and content delivery servers, but when you publish the change is only visible on the content management box.

A likely cause is that you’ve enabled some caching but haven’t updated the config files to clear the cache on your content delivery server.

Sitecores config files contain a list of handlers for what should happen when the event publish:end and publish:end:remote are triggered. Publish end is for the content management server, whereas publish end remote is for your delivery servers. The handler we’re interested in is Sitecore.Publishing.HtmlCacheClearer which contains a list of sites to have the cache’s cleared on.

By default this will contain one entry for website, the default name given to your site in the sites config when you install sitecore. However you will have changed this if your solution supports multiple sites, or if you changed it as part of some future planning to support multiple sites. If your site is missing, just add it to the live (via a patch file of course)

<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">
<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end:remote">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">

Note: in the sample above I have removed all other handlers to simplify the example. You should not remove these from your solution.

For more info on cache clearing and optimising it, see John Wests blog series on the subject here

Displaying the cost of a uCommerce custom IShippingMethodService

I just found this bog post on how to get the shipping cost for a custom shipping method you may have implemented using IShippingMethodService and thought I would share it here.

A common requirement when displaying shipping methods is to show the price against each, and for the built in uCommerce shipping methods there’s a handy GetPriceForCurrency() method on the shipping method object. However if that shipping method is a custom one, it just returns 0.


var allShippingMethods = TransactionLibrary.GetShippingMethods(country);
var currency = purchaseOrder.BillingCurrency;

foreach (var shippingMethod in allShippingMethods)
	var cost = shippingMethod.GetPriceForCurrency(currency);

The correct way to get your shipping price is to manually call your service to get the price to be calculated.

As we don’t know which implementation of IShippingMethodService will be used we first need to call GetShippingMethodService() to get it.

After that we just need to populate a new Shipment object we the details our custom method needs and then call the CalculateShippingPrice method.

var purchaseOrder = TransactionLibrary.GetBasket().PurchaseOrder;
var allShippingMethods = TransactionLibrary.GetShippingMethods(country);

foreach (var shippingMethod in allShippingMethods)
  // Get the IShippingMethodService for this ShippingMethod
  var shippingService = shippingMethod.GetShippingMethodService();

  // Construct a fake shipping method to call the service with
  var shipment = new Shipment
	  ShippingMethod = shippingMethod,
          OrderLines = purchaseOrder.OrderLines,
	  PurchaseOrder = purchaseOrder,
	  ShipmentAddress = purchaseOrder.BillingAddress

  var shippingMethodPrice
 	 = shippingService.CalculateShippingPrice(shipment);

Sitecore: Programmatically adding contacts to a list

From Sitecore 8 the EXM module now uses lists to manage mailing lists rather than roles against a user. The built in Subscription form control that comes with EXM has also been updated to add contacts to this list. However the subscription control remains WebForms only, so if you implementing an MVC solution you’re going to need to write your own. There’s also many other scenarios where you may want to programmatically create and add a contact to a list.

Under the hood, contact lists aren’t even a list at all. Rather they are actually just a Facet on the Contact record that contains the list id’s for all the lists the contact is a part of. You can see this by looking in the contacts collection in the analytics mongo db.

List Tag on Contact

Or in the Contacts table in the Reporting SQL db.

List Tag on Contact SQL

If you wanted to add a contact to a list you could in theory just add the relevant tag to the contact record like this:

public void AddContactToList(Contact contact, Item list)
   using (new SecurityDisabler())
      contact.Tags.Set("ContactLists", list.ID.ToString());

But I wouldn’t. The problem with this approach is your going to miss out any logic that will handle updating the counts of contacts in contact lists. Best to use one of the provided list api’s instead.

Adding a contact to a list

Sitecore has a ContactListManager object that has a method to associate contacts with lists. All you need to do is create an instance of it and pass it a list of contacts.

public void AddContactToList(ContactData contact, ContactList list)
    ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;

    List<ContactData> contactList = new List<ContactData>();

    listManager.AssociateContacts(list, contactList);

Removing  a contact from a list

Just like adding a contact, there’s also a handy method for removing one too.

public void RemoveContactFromList(ContactData contact, ContactList list)
    ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;

    List<ContactData> contactList = new List<ContactData>();

    listManager.RemoveContactAssociations(list, contactList);

What’s that ContactData object?

Chances are you don’t have a ContactData object (Sitecore.ListManagement.ContentSearch.Model.ContactData) and instead probably have a tracking contact (Sitecore.Analytics.Tracking.Contact). For the purposes of adding and removing a contact from a list, all your ContactData object really needs is its identifier, which you can do with the following:

public ContactData ConvertContactToContactData(Sitecore.Analytics.Tracking.Contact contact)
    return new ContactData()
        Identifier = contact.Identifiers.Identifier

Intro to Unicorn

Unicorn is a utility for Sitecore that solves the issue of moving templates, renderings, and other database items between Sitecore instances.

This video gives a great introduction to what it is and how it works. It’s for Unicorn 2 and Unicorn in now on version 3, but it’s still a good starting point.

More information on unicorn can be found at.

Sitecore contact facets – Create your own facet

Brian Pedersen's Sitecore and .NET Blog

This article describes how to create a simple Sitecore facet consisting of a DateTime and a list of strings.

A contact is made up of facets. Here are all the facets Sitecore uses (you will find the facets in App_ConfigIncludeSitecore.Analytics.Model.Config):

In this example I will add a facet that consists of a date and a list of strings. I will call it “AvailablePublishers“.

This is a real-life example where I needed to store a list of publishers that were available the last time the user was online. Each publisher is just an ID (a string) and I store these as a list on the Contact:

Available Publishers Facet Available Publishers Facet

It sounds simple, and it is – but there is a lot of code involved. So hang on, lets code.


The “AvailablePublishers” is a Facet, the list below consists of Elements. So I need…

View original post 387 more words

Sitecore: Sharing field data across languages

This is the third in a series of blog posts covering everything you should need to know for building a multilingual website in Sitecore.

Part 1 – Adding languages for a multilingual site
Part 2 – Translating text in your presentation

In the first two parts to this series I concentrated on how you can setup Sitecore to allow different language versions of content to be entered. In some instances though your content will contain fields which should remain the same across all language versions. This could be for product sku’s, dimensions of an object or possibly image fields.

To make a field share it’s values over multiple languages, in the template definition tick the shared checkbox against the field.


It’s worth noting though that as well as making the field value the same across all languages, it will also be shared between all versions within the language.

Although the interface gives the impression that a field can be the default (versioned), unversioned, shared or unversioned and shared. The value of the unversioned checkbox actually become meaningless once shared has been ticked and there really are only 3 options; Versioned, Unversioned and Shared.