Programming for Sitecore DMS Engagement Plans

Sitecore DMS Engagement plans allow you to control some of the specific ways in which your website interacts and communicates with the visitors to your website. Think of engagement plans as a configurable flow state engine. It allows you to push the responsibility of automation to your customer.

Engagement plans are especially usefull when you have named visitors, ie users with a username and an email.

Sample Engagement Plan

Engagement plans are controlled through the Sitecore.Analytics.Automation.VisitorManager class and the Sitecore.Analytics.Tracker class.

The Tracker class can be used for connecting a named user to the DMS visitor:

using Sitecore.Analytics;
using Sitecore.Analytics.Automation;

private void CheckAndSetTracker(string userName)
  if (Tracker.IsActive)
    Tracker.Visitor.ExternalUser = userName;

The userName is a fully qualified name, ie extranet\user.

To assign a user to an engagement plan, simply call VisitorManager.AddVisitor with the ID of the engagement plan state:

public bool AssignToEngagementPlan(User user, ID engagementPlanIdStartState)
  bool addVisitor = VisitorManager.AddVisitor(user.Name, engagementPlanIdStartState);
  return addVisitor;

The User is the Sitecore.User.

usually you would assign the user to the first step of your engagement plan, but you can in fact assign the user to any state you wish.

You can also move a visitor from one state to another:

VisitorManager.MoveVisitor(userName, source, destination);

You can also search for a specific user in an engagement plan to see is the user is alreay assigned to any state in that engagement plan:

private bool UserIsInAnyEngagementPlanState(string userName, ID engagementPlan, out ID stateId)
  var result = false;
  stateId = null;
  foreach (Item state in GetEngagementPlanItem(engagementPlan).Children)
    result = VisitorManager.GetStateVisitors(state.ID).Any(visitor => visitor.Equals(userName));
     if (result)
      stateId = state.ID;
  return result;

That’s basically it. It’s very easy to work with once you get the hang of it.



Posted in c#, Sitecore 6, Sitecore 7 | Tagged , , , , , | 7 Comments

.NET DateTime to JSON UNIX JavaScript datetime

When posting datetimes to web services or REST services, you might need to convert the standard .NET DateTime to a UNIX format.

Please note than neither REST, nor JavaScript has its own DateTime format. But some systems based on REST (Java applications for example) have a love affair with the UNIX Epoch datetime format, which is the number of seconds since 1/1/1970.

So in order to convert a standard .NET DateTime to a number of seconds, you need to calculate the TimeSpan between the current DateTime and 1/1/1970:

public string ToUnixEpoch(DateTime dateTime)
  DateTime d1 = new DateTime(1970, 1, 1);
  DateTime d2 = dateTime.ToUniversalTime();
  TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
  return ts.TotalMilliseconds.ToString("#");

The string returned contains the integer of the timespan.

In some systems you need to add /Date()/ around your timespan, so the resulting UNIX Epoch string looks like this:


To convert the UNIX datetime to a .NET DateTime you reverse the process:

public DateTime FromUnixEpoch(long epochTime)
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(epochTime);

Some systems will return the UTC time, not the time from the current timezone. To convert from UTC to the current timezone, use the TimeZone class from .NET:



Posted in c#, General .NET | Tagged , , , , | 1 Comment

Sitecore 6.6: CSRF form field is missing

In the latest version of Sitecore 6.6 (release 13.04.04) I sometimes get this error:

Exception: Sitecore.Security.AntiCsrf.Exceptions.PotentialCsrfException
Message: CSRF form field is missing.
Source: Sitecore.Security.AntiCsrf
at Sitecore.Security.AntiCsrf.SitecoreAntiCsrfModule.RaiseError(Exception ex, HttpContext context)
at Sitecore.Security.AntiCsrf.SitecoreAntiCsrfModule.PreRequestHandlerExecute(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

The issue seemes to be related to an implementation of AntiCSRF, a Microsoft Public License library that prevents Cross Site Request Forgery.


The fix is easy. Clear your cookies, clear the browser cache, close the browser and try again.


The clever guys at Sitecore Support have come up with this (untested) quick fix that you can try:

Please add these lines to the Sitecore.AntiCsrf.config file (website/app_config/include/Sitecore.AntiCsrf.config):

<ignore wildcard="/sitecore/shell/*Applications/Security/User*Manager*?*Cart_Users_Callback=yes"/>
<ignore wildcard="/sitecore/shell/*Applications/Security/Role*Manager*?*Cart_Roles_Callback=yes"/>
<ignore wildcard="/sitecore/shell/*Applications/Security/Domain*Manager*?*Cart_Domains_Callback=yes"/>
<ignore wildcard="/sitecore/shell/~/xaml/Sitecore.Shell.Applications.Security.SelectAccount*Cart_*_Roles_Callback=yes"/>
<ignore wildcard="/sitecore/shell/~/xaml/Sitecore.Shell.Applications.Security.SelectAccount*Cart_*_Users_Callback=yes"/>


The tough guy could choose to disable AntiCSRF completely. Add the following line in the /App_Config/Include/Sitecore.AntiCSRF.config file:

<?xml version="1.0"?>
        <rule name="shell">
          <!-- Ingore AntiCSRF completely -->
          <ignore wildcard="/sitecore/*"/>
Posted in Sitecore 6 | Tagged , , , | 10 Comments

Sitecore 7 is coming: My wish list for Sitecore 7.01

The next big release of Sitecore 7 is on it’s way. This time Sitecore have listened to many MVP’s and have adressed some technical issues.

Most of this release revolves around scalability and indexing. The Lucene index have been updated to allow even more impressive performance and even higher scalability. The old Sitecore 6 would easily swallow 1.000.000 items. Sitecore 7 have almost no limitations. Even on folder level, where the old Sitecore 6 stalled at around 200 items at the same level; Sitecore 7 implements a revamped version of Sitecore Item Buckets, allowing you to have an infinite amount of items at the same level.

So what’s next on my wish list? Could I ask for more? Of course. More wants more. Here is the areas where I would like Sitecore to focus on for the first update of Sitecore 7:



We need the Sitecore Page Editor to be extensible, like the rest of Sitecore.

If you wish to add a new field to the Sitecore shell, you write some code, put it in a DLL and points to the field. No modifications to Sitecore itself.

In the Page editor, you need to modify one of Sitecore’s own Javascript files (FieldChromeType.js). This file changes with every version of Sitecore, and you cannot just append your modifications, as you need to modify namespaces and switch statements.

This is bad and very Sitecore-unlike behavior. Sitecore is a platform. You never modify the platform. You extend it. Except for the page editor. Sigh.


If you would like to have a link popup box in the page editor, you must have a general link field. The page editor should have a popup for all lookup fields, so you can have fields where only internal links are allowed.


A button that opened the media library would be nice please. It’s 10 lines of code. I can give you the code.


Not all fields are visible. But you should be able to edit them anyway. Thomas Stern made a solution. This should be standard.


The publish button on the page editor will only publish the current item (and it’s subitems). But most pages have included components. These components are not stored on the item, and often not as children to the current item. When publishing from the page editor, these components should be published as well. Otherwise you cannot publish them from the Page Editor at all.


This is not a no-brainer. The Page Editor is the coolest thing since sliced bread. Customers are requesting page editable websites more and more often.

Unfortunately, if you are aiming at building a page-editor only website (a website that is edited completely using the page editor) costs explode. The number of lines explode, as you have to consider many more states and exceptions.

You have to add code to allow fields that is hidden if empty to be shown, only in page edit mode. And how do you make a carrousel page editable? And what about the metadata fields?

How do you allow the customer to version pages, if the page consists of components?

All of these simple, little decisions complicate your code, making it more expensive to develop, and more expensive to test.



If you wish to use the Sitecore DMS in it’s full extent you are bound to make a Page Editable website. Why? Because the Page Editor is the only place where you can add components to a page. Components are necessary if you would like to use A/B Testing and Real Time Personalisation.

We need the dialogs for adding components to a page available in the Sitecore Shell.

I would expect the Sitecore Shell to contain the full set of functions, and the Page Editor to be a subset of functionality.

Yes I know that I can use the Presentation->Details button to open the Layout Details and from there I can add my components. But my customer cannot. It’s a developer tool and way too complicated to use.

Please make a user friendly way of adding components to a page from the Sitecore Shell.



The sc:FieldRenderer should be able to get a NULL item without crashing. This would remove half of my code lines in my components.


The sc:Link should be able to use lookup fields and not only the general link field.


The sc:EditFrame should accept a Sitecore item instead of a Item path in the DataSource property.

Posted in Sitecore 6, Sitecore 7 | Tagged , | 3 Comments

The URL-encoded form data is not valid error in Sitecore Page Editor

In ASP.NET 3.5 you may encounter one of the following error messages:

“Operation is not valid due to the current state of the object”


“The URL-encoded form data is not valid”


Microsoft released a Security update at dec 29 2012. The update contained (amongst other features) an upper bound to the number of simultaneous HTTP form elements that can be posted. The new limit is 1000.

In the Sitecore Page Editor you may experience that for large pages you have more than 1000 form elements.


To fix this you should add the following to the web.config:

In the <appSettings> of the web.config add the following:

<add key=”aspnet:MaxHttpCollectionKeys” value=”value greater than 1000” />

Thanks to Alin Parjolea for the tip.

Posted in General .NET, Sitecore 6 | Tagged , , | Leave a comment

Sitecore 404 without 302

It’s a well known issue that when Sitecore displays a 404 page, it’s done by doing a 302 redirect to the 404 page, hence the 302 status code is thrown before the 404.

The behavior is partially because of the way .net handles redirects internally. But fortunately you can overcome it pretty easily.

My colleague Anders Laub came up with this extension to the Sitecore httpRequestBegin pipeline.

By adding a processor to the pipeline you can switch the missing item with a 404 item inside Sitecore. The item in Sitecore will then have a sublayout that will throw the 404. In effect, Sitecore (or .net) will not know that there is a page missing and will continue the business as usual. It’s up to us developers to handle the 404. Just like we like it.

First the httpRequestBegin processor:

  <processor type="Sitecore.Pipelines.PreprocessRequest.CheckIgnoreFlag, Sitecore.Kernel" />
  <processor type="Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel" />
  <processor type="MyCode.Custom404ResolverPipeline, MyDll" />

The processor is added just after the ItemResolver. The ItemResolver returns null if the item is not found.

We then switch the missing item with our 404 item:

public class Custom404ResolverPipeline : HttpRequestProcessor
  public override void Process(HttpRequestArgs args)
    Assert.ArgumentNotNull(args, &quot;args&quot;);

    // Do nothing if the item is actually found
    if (Sitecore.Context.Item != null || Sitecore.Context.Database == null)

    // all the icons and media library items 
    // for the sitecore client need to be ignored
    if (args.Url.FilePath.StartsWith(&quot;/-/&quot;))

    // Get the 404 not found item in Sitecore.
    // You can add more complex code to get the 404 item 
    // from multisite solutions. In a production 
    // environment you would probably get the item from
    // your website configuration.
    Item notFoundPage = Sitecore.Context.Database.GetItem(&quot;{DFE03D7A-00B9-4C15-8AB7-482D82B3484E}&quot;);
    if (notFoundPage == null)

    // Switch to the 404 item
    Sitecore.Context.Item = notFoundPage;

The page we switched to needs to have a sublayout that will do the actual 404 return code:

public partial class _404 : System.Web.UI.UserControl
  protected void Page_Load(object sender, EventArgs e)
    HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
    HttpContext.Current.Response.TrySkipIisCustomErrors = true;
    HttpContext.Current.Response.StatusDescription = &quot;Page not found&quot;;

Remember to set the TrySkipIisCustomErrors or your 404 page will be ignored by IIS 7.5.


Posted in c#, General .NET, Sitecore 6 | Tagged , , , , , | 12 Comments

Create components for Sitecore Page Editor

This quick tutorial will guide you trough your first Sitecore Page Editable Component.

The Sitecore Page Editor is build around the concept of components. A component is a reusable piece of data that is parred with a sublayout and placed in a placeholder.

Sitecore Page Editor

Sitecore Page Editor’

This tutorial will create a very simple component: Adding an Image.

To create components you must go through a series of steps.


First you need a Sitecore Template where you store the data. My component must show an image, so all my template contains is an image field called “DocumentImage”:

Document Image Template

Document Image Template


Next step is to define a place in your web site structure where you will store templates of this type. Templates of different types can share a folder, or you can create a folder specifically for this type.

You will need the folder in a few steps.


Now you need a sublayout that will present the data from the template.

Document Image Sublayout

Document Image Sublayout

When creating the sublayout you must determine the contents of these fields:

  • Editable: Check this box. If unchecked, the sublayout is not editable and cannot be used in the Page Edittor as a component.
  • Datasource location: Select the folder you chose in STEP 2. When the component is added to a page, this is where the data will be stored.
  • Datasource template: Select the template you created in STEP 1. When the component is added to a page, this is the template that is created.


Each placeholder that is capable of having controls added must be defined in the folder /sitecore/layout/Placeholder Settings.

Select the placeholder setting where you would like to allow your control to be added and add it to the “Allowed controls” field:

Placeholder setting

Placeholder setting

Read more about placeholder settings here.


When a component is added to a page it is parred to a item through the “datasource” parameter on the layout. This means that you cannot get the data for your component with Sitecore.Context.Item. Sitecore.Content.Item will point to the actual page where the component is added, not the item assigned to the component.

The following method will get the item from the “datasource”, with a fallback to the current item. The fallback is a safety mechanism that ensures that the item returned is never null, as this will crash the entire web page.

protected Item CurrentContextItem
    Sublayout thisSublayout = (Parent as Sublayout);
    if (thisSublayout == null)
      return Sitecore.Context.Item;
    if (string.IsNullOrEmpty(thisSublayout.DataSource))
      return Sitecore.Context.Item;
    string dataSource = thisSublayout.DataSource;
    Item dataSourceItem = Sitecore.Context.Database.GetItem(dataSource) ??
    if (dataSourceItem == null)
      return Sitecore.Context.Item;
    return dataSourceItem;

(This method of getting the datasource has not changed the last 5 years).

You now assign the Item parameter of the sc:Image webcontrol to CurrentContextItem, and the control will take its data from that item:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DocumentImage.ascx.cs" Inherits="PT.Document.DocumentImage" %>
<%@ Register TagPrefix="sc" Namespace="Sitecore.Web.UI.WebControls" Assembly="Sitecore.Kernel" %>

<div class="Image">
  <sc:Image field="DocumentImage" id="Image" runat="server" Item="<%# CurrentContextItem %>" MaxHeight="200" />

If your component uses an EditFrame you need to get the actual value from the datasource, not the item it points to. In this case you need another method:

protected string DataSourceValue()
  Sublayout sublayout = (Parent as Sublayout);
  return (((sublayout == null) || string.IsNullOrEmpty(sublayout.DataSource)) ? string.Empty : sublayout.DataSource);

You can now use this method to ensure your EditFrame uses the correct item:

<sc:EditFrame runat="server" ID="editFrame" Buttons="???" DataSource="<%# DataSourceValue %>">

That’s all there is to it. Happy coding.

More reading:

Posted in c#, Sitecore 6 | Tagged , , , , | 3 Comments

Sitecore media library missing PDF icons

When uploading PDF (or Word/Excel/…) documents to the Sitecore media library, the PDF icon is not shown:

PDF icon Missing

PDF icon Missing

In this case it is only my test server that is not showing the icons. My local development machine (my own laptop) displays the icons perfectly:

PDF icon Shown

PDF icon Shown on my laptop

The reason is that Siteore use the associated icon from the OS. Acrobat Reader is installed on my laptop, not on my test server. So the test server displays a default icon instead.


You can specify which static file to use for which extension in the web.config. To add the PDF icon, do the following:

Download a .pdf icon from the Adobe Website (due to licensing restrictions, Sitecore is not shipped with an Acrobat Reader icon). Place the icon wherever you wish.

Go to the web.config and find the <mediaType name=”PDF file” extensions=”pdf”> section.

Add the following:

<mediaType name="PDF file" extensions="pdf">
  <!-- New section -->
    <generator type="Sitecore.Resources.Media.MediaThumbnailGenerator, Sitecore.Kernel">
    <staticFile>File location. For example /sitecore/shell/Themes/pdficon_large.png</staticFile>
  <!-- end:New section -->

Clear the following folders:

  • /temp/ folder (at least all files named “fileIcon”)
  • The Sitecore media cache (default located at /app_data/mediacache/)

Clear your browser cache.

Restart the website.

That’s it. You now have PDF icons in Sitecore.


Posted in Sitecore, Sitecore 6 | Tagged , , , , | 2 Comments

Sitecore Save Dialog appears for unchanged content

Have you ever experienced that Sitecore keeps popping the “Do you want to save the changes to the item?” dialog box, even when you have made no changes to the item? And the box keeps appearing, even when you have chosen “yes”?

Save Dialog

Save Dialog

This scenario can occur if the contents of any multiline field or textbox field contains new lines \n or carriage returns \r.

Memo Box with \r or \n

Memo Box with \r or \n

In rare situations, the browser will interprete \n and \r differently from Sitecore, thus telling Sitecore that the contents in the box differs from the contents in the Sitecore database.

The situation rarely occurs with manually entered text, but if you have programatically added the text to the box, the \n and \r might misalign.

So if you add text to the multiline field (or textbox field) you should ensure that any \n and \r are removed before adding the text.

I made this string extension method to remove all new lines, carriage returns, tabs and strange \xA0’s (which looks like a space but isn’t):

public static string CleanNewLinesTabsAndOtherStuff(this string s)
  return s.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Replace("\t", " ").Replace('\xA0', '\x20');

I replace all of them with spaces, but in other situations you could replace them with string.Empty.

Posted in c#, Sitecore 6 | Tagged , , , , , | 4 Comments