Sitecore custom sublayout cache key

Out the box, sitecore offers several options for caching the output of sublayouts. Some of the options you have for this are things like ‘vary by querystring’ and ‘vary by data’. This post will demonstrate how to setup custom sublayout cache keys.

Behind the scenes Sitecore builds up a cache key by appending together information from the current request based on the parameters selected in the caching options. The result of this being the cache key is longer, the more permutations you select.

For typical builds, the out the box options cover all scenarios however what do you do if you need to customise this?

In a recent project we exploited * (or wildcard) items so we could accomodate data fed from an external api. This would map known url patterns to one node in the tree, allowing the presentation components on the page to be set in sitecore but the data in the body content be fed from and external system. The mvc routing dll solves the same problem in a similar fashion.

With the default cache options we ran into the issue that the cache key for each wildcard page would always be the same since the ‘vary by data’ option used the items id, rather than the dynamic url we were assigning. Essentially every page would share the cache key for the * node.

Solution
There are only two steps needed for this implementation:

  1. Create custom implementation of a sublayout
  2. Create custom sublayout factory

Custom sublayout

To use this on the front end, you would then embed in the markup using:

If you want sublayouts instantiated from Sitecore to make use of your new type, you need to update the sublayout renderingControl in the config:

And finally the new rendering type:

In the example above the new sublayout is used for wildcard items as well as items which match an MVCRoute – this is some new functionality currently being developed by Steven Pope @ Sitecore UK.

Sitecore and RegisterClientScriptInclude / RegisterClientScriptBlock / RegisterClientScriptResource

One of the common issues when using Sitecore HTML Caching is how to execute dynamic scripts based on code behind actions when the control front end is being cached.

The solution listed below defines the theory behind the approach rather than the concrete implementations.

Consider the following scenario:
You need to display the date to the user using javascript. To solve the issue, you decide to make use of either RegisterClientScriptBlock or RegisterStartupScript and register some javascript to write out alert(‘DateTime.Now’) [psuedo code].

This works fine during development since you are building your project a lot and the full use of caching isnt implemented. Down the line, you tune up / turn on caches and the date is only shown the first load after the caches are emptied 🙁

Do not fear, there is a solution to the issue and that is to make use of Sitecore Html Cache. Rather than calling asp.net RegisterClientScriptInclude(Block, Resource), setup your own methods (for the demo, these are exposed off SScriptManager):

In your master page, add another control (for the demo, known as SScriptManager).

When you register the script includes / blocks, store this information in the html cache remembering to build the cache key from current item, current language and script key.

During the Render/PreRender phase of the page lifecycle, the SScriptManager can then iterate through all keys in html cache and if the keys match the current page, relay on the script calls to the page.

Adding functionality to interfaces with extension methods

When building large scale applications a very useful design pattern to adopt is dependency injection. An example of this is programming to interfaces such that the implementation of each interface can be interchanged.

In this post I will demonstrate some examples of how you can go about adding functionality to interfaces with extension methods.

Consider the following example with some demo interfaces and classes:

This is all well and good – the user can write log entries with the following line:

So, how can we achieve:

The interface cannot contain any implementation. One solution would be to use abstract classes for the base class however that goes against the principal of programming to interfaces.

How about extension methods? Using the following examples we can add these shorthand methods to our ILog hiding some of the complexity / repeated code:

If you setup the extension methods in the same namespace as your interface, you will now have available:

Common mistakes when programming with Sitecore pt1

The aim of this post is to highlight some pitfalls I have run into in the past when working with the Sitecore API. Hopefully some ideas demonstrated here will help people avoid some common mistakes when programming with Sitecore.

Over time I’d like this list to grow so if anyone has any feedback or suggestions for more items, please let me know.

For each item I will highlight some examples of where I have seen the mistakes and how they can best be avoided.

  1. Direct database access
  2. Expensive content queries

1. Direct database access
There are several ways to get a reference to a Sitecore database. Note, these are defined within the config (<databases>). In the following example, the first 2 items get a specific database, the last the context database.

Why is this bad?
In larger Sitecore builds one of the common tasks is to run through the ideas stored in the following guides on the sdn: security hardening and configuring production environments.

One of key steps in these documents is that the content delivery site only has a reference to the web database. Typically you would have an independent content authoring environment which has references to core, master and web. In this setup, if your code has a direct reference to master, you will get an exception since master doesnt exist.

When might you want to do this?
It may be that in certain circumstances you do want to target a specific database. Consider an import routine. In this example you would want to ensure that new items are only added to master – note you would need to ensure the import routine is run from an environment which can access the master database.

2. Expensive content queries
Sitecore.Data.Items.ItemAxes exposes a set of methods which can be used to drill up and down through the content tree. Some examples of this are:

Within your sublayouts you could then call eg:

Why is this bad?
If your content tree contains thousands of content items and you call GetDescendants from the root node – you will effectively be loading every single item in the tree – I can guarantee the bigger the tree, the slower this will go!

When might you want to do this?
If you are comfortable that the result of a descendants call will expose a controlled set of nodes then you may find them more useful than querying direct children. An example of this is if folders are used in the structure you are querying.

Where might you make this mistake?
A typical place I have seen this implemented is building footer navigation. Consider the following: ‘A developer understands your template structure and sees there is a common base template for each page so adds a new checkbox ‘Show in footer navigation’. In the footer control they then start at the home node calling GetDescendants, checking each item for the new checkbox.

What can I do instead?
In the footer example, try to consider alternative solutions for defining which items should be shown in the footer. How about a configuration area of the content tree where the footer navigation is defined as its own node (and children if needed). Your descendants call could then target these specific items.

Other alternatives are using shallower axes for your queries for example: direct children or siblings.

Create a version of an item in all languages in the Sitecore client

This post aims to demonstrate how to add new versions for all languages if they dont exist in the cms.

When you click buttons within the Sitecore client, typically Sitecore commands are used to map these actions to c# code. This link is defined in /App_Config/Commands.config. Some sample entries here are:

If you want to add your own commands you can either edit this file or setup a patch file in /App_Config/Include. Note the patch file is the preferable option.

The code used for this example is:

This then needs to be added into the commands section of the config with the following patch file:

If you want this functionality available from a cms button, you need to wire up the button to the command. To do this, switch to the core database.

In this example we will add to the Language chunk of the ribbon (/sitecore/content/Applications/Content Editor/Ribbons/Chunks/Language). You need to create a new button and then setup the data section paying close attention to the Command field. This wants to be the same value as set in the patch file (item:addversiontoalllanguages).

Debugging Sitecore pipelines

A quick tip for checking data flowing through the Sitecore pipelines is to setup empty processors and then move them sequentially through the required pipeline.

An example for the pipeline:

Then add your debug point and dig into the args.

Some example usage for checking which site has been resolved:

Sitecore Gutters for updated presentation

Sitecore gutters are a great way of seeing quick summaries of content within the tree. Some existing gutter options include Locked Items, Workflow State, Missing Versions and more. These can be toggled by right clicking in the left column of the content editor.

Its easy to build custom gutters – in the example above we have a new item available – ‘Custom Presentation’. When this is active on an item it shows:

Behind the scenes there is very little code to achieve this:

Gutters then need to be added to the core database at ‘/sitecore/content/Applications/Content Editor/Gutters

Setup custom Sitecore MediaProvider

One of Sitecore’s most useful features is the plug-ability of functionality via the configuration factory. Its very easy to add or update custom implementations where necessary.

A typical programming model used throughout this is the Provider model – Membership, Roles, Item, Proxy… the list is endless. Unfortunately one provider thats not exposed in the config factory is the MediaProvider.

No problem, thanks to some help from support they suggested a way to get around this, you can tap into the initialise pipeline. Here is the patch file to enable this:

This pipeline runs as the application intializes. Next you need the implementation of the pipeline processor:

And finally the custom implementation:

Our customization allowed us to push certain media extensions to known file types.

Take control of your sublayouts

There are several options available when setting up which data feeds into your sublayouts or renderings within Sitecore. Typically we work with sublayouts since they fit the programming style used in-house.

When you add a presentation component to a page you can configure data in a manner of ways:

In this example we have setup rendering parameters for ‘Section Image Header’ (the items that feed this dropdown are content items elsewhere in the content tree). Alternatively you can explicitly set the ‘Data Source’.

When coding your sublayouts, its simple to extract information from either the rendering parameters or the ‘Data Source’ field using the following examples.

To then access the ‘Section Image Header’ rendering parameter you could query:

One disadvantage with using parameters to setup the data into sublayouts is that the links database doesnt honour the relationship. See where is shared content used for help with this.

Rather than needing the code shown above in every sublayout you can create a base classes to expose the data source and parameters as properties and methods:

Another tip to consider, you can setup your sublayouts with an attribute to automatically use the rendering parameters as the sublayouts data:

In this example the sublayout will know to take its data from the item related in the ‘Section Image Header’ rendering parameter.

Add ITemplate content to a controls markup

When building web controls, a common scenario is how to cascade control parameters to the control from the markup (or code-behind). Within Sitecore controls this is typically the Field you want to render.

This approach to programming controls works very well until the set of parameters becomes very long or the control doesnt need to know about each parameter. Consider embedding a flash movie, the number of parameters to code could be huge.

In the flash example, often the parameters aren’t needed by your c# code, instead they just to be rendered to the markup.

One useful tip is that you can get information from your code behind into the template markup eg

To build the control you need to add the following attribute:

And then the template you want to use:

The content of the template can be extracted as a string with the following:

Note, based on the chosen implementation, you may not need the content of the template as a string. Instead you could simply instantiate to the control’s child controls