Avoid the use of Sitecore.Context.Item

Or: How Sitecore DMS and Personalization killed the Sitecore.Context.Item. This post is about how to properly ensure that you get data from the correct item when you develop websites that can be personalized.

The Sitecore.Context.Item returns the current item, i.e. the item that corresponds with the URL that the user has entered. Old Sitecore developers like me has been used to adding the fields of a page to the current item, and then accessing these fields directly using the sc:FieldRenderer:

<%@ Register TagPrefix="sc" 
    Namespace="Sitecore.Web.UI.WebControls" 
    Assembly="Sitecore.Kernel" %>

<sc:FieldRenderer ID="MyField" runat="server" 
FieldName="NameOfMyField"  />

This approach is no longer a good approach, as the the customer have been given access to DMS and personalization. Now you no longer know if the content that the usercontrol need, is part of the current item, or another item.

Personalize the Component

Personalize the Component

The customer can now acces any component he likes, and use personalization to alter the data source (or even the component itself). This breaks the pattern of assuming that content is part of the current item.

So what can we do?

Before we grab any field, we need to go through these steps:

  • Check the datasource of the current sublayout
  • If the datasource is set, use the item from the datasource
  • If not, use the current item

These 2 extension methods ease the process:

namespace SitecoreExtensions
{
  public static class SublayoutExtensions
  {
    public static Item GetDataSourceItem(this Sublayout sublayout)
    {
      string dataSource = sublayout.DataSource;
      if (string.IsNullOrEmpty(dataSource))
        return (Item) null;
      return Context.Database.GetItem(dataSource);
    }
  }

  public static class UserControlExtensions
  {
    public static Item GetDataSourceItem(this UserControl control)
    {
      Sublayout sublayout = control.Parent as Sublayout;
      return sublayout == null ? (Item) null : SublayoutExtensions.GetDataSourceItem(sublayout);
    }

    public static Item GetDataSourceOrContextItem(this UserControl control)
    {
      return UserControlExtensions.GetDataSourceItem(control) ?? Context.Item;
    }
  }
}

The SublayoutExtensions extend the Sitecore Sublayout. The GetDataSourceItem returns the item that the datasource points at, or null if the datasource is not set.

The UserControlExtensions extend the .NET UserControl (that really is the base of a Sitecore Sublayout). The GetDataSourceOrContextItem returns the datasource item, with a fallback to Sitecore.Context.Item.

To use the method, you must add the function to the item property of the sc:FieldRenderer:

<sc:FieldRenderer ID="MyField" runat="server" 
FieldName="NameOfMyField" 
Item="<%# this.GetDataSourceOrContextItem() %>" />

And you must remember to call DataBind().

This pattern is good because you never end up with a NULL item, as sc:FieldRenderer will crash if you feed it with a NULL value in the item property. There is no reason to crash the entire page just because one component is not configured correct.

From code-behind you simply replace Sitecore.Context.Item with this.GetDataSourceOrContextItem:

var text = Sitecore.Context.Item["NameOfMyField"]; // old way
var text = this.GetDataSourceOrContextItem()["NameOfMyField"]; // new way

I would not be surprised if Sitecore in the future would build these functions into sc:FieldRenderer, but untill then we have to do it ourselves.

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

Custom rules and conditions for Sitecore personalization

In Sitecore it is possible to change the sublayouts or data sources on a page depending on conditions. This means that users can see the same page differently, depending on a set of rules. Sitecore comes standard with a set of standard rules (The user’s geographic place, has the user met any goals, has the user been referred etc.).

As always with Sitecore (well, except for the page editor) you can extend Sitecore’s functionality by creating your own rules.

THE EXAMPLE: QUERY STRING CONDITION

This is an example of a rule that checks for a certain QueryString (in this case a ZipCode). If the querystring contains a certain value, the condition is met.

First you need to set up the condition. Conditions are defined in folders below /sitecore/system/Settings/Rules/Segment Builder/Conditions:

My Custom Condition

My Custom Condition

The cryptic text attribute is used to explain and configure the condition at the same time:

Where the querystring parameter zipcode [operatorid,Operator,,compares to] [value,,,value]

The string is case sensitive. [operatorid,Operator,,compares to] gives you the options “equal to, not equal to, less than, greater than, …”, and [value,,,value] gives you the possibility to enter a value.

Then you need to write the code. This condition compares integers, so I inherit from the IntegerComparisonCondition. There are other conditions to inherit from as well, like the OrCondition, NotCondition, AndCondition, OperatorCondition, BinaryCondition etc.

namespace MyCode.Infrastructure
{
  public class CheckQuerystringCondition<T> : IntegerComparisonCondition<T> where T : RuleContext
  {
    protected override bool Execute(T ruleContext)
    {
      Assert.ArgumentNotNull(ruleContext, "ruleContext");
      var zipCodeQuerystringValue = HttpContext.Current.Request.QueryString["zipcode"];
      int zipCode;
      if (string.IsNullOrEmpty(zipCodeQuerystringValue))
      {
        return false;
      }

      if (!int.TryParse(zipCodeQuerystringValue out zipCode))
      {
        return false;
      }

      return Compare(zipCode);
    }
  }
}

The condition is now ready to be used.  To use it you need to find the layout of the page you wish to personalize. You can see if there is conditions on a layout by the little number mark:

Layout Details

Layout Details

Select the control to personalize and start personalizing. In this example I choose between 2 diferent sublayous depending on the condition. You can also choose to switch the data context (i.e. where the component gets its data from).

Personalize The Component

Personalize The Component

The personalization is pretty straight forward, and reminds of the way you would set up rules in Microsoft Outlook:

Rule Set Editor

Rule Set Editor

Thanks to Emil Klein for the code.

READ MORE:

Posted in .net, c#, Sitecore 6, Sitecore 7 | Tagged , , , , | 4 Comments

(System.Web.UI.HtmlControls.HtmlIframe) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl)

Yesterday I got the following error:

Parser Error Message: The base class includes the field ‘IFrame’, but its type (System.Web.UI.HtmlControls.HtmlIframe) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).

Source Error:

Line 14: <iframe id=”IFrame” frameborder=”0″  runat=”server” visible=”false”/>

Reason:

The code was written using .NET 3.5 but executed in the .NET 4.5 runtime. From .NET 4.5, Microsoft decided to change the iframe from a HtmlGenericControl to its own control, a HtmlIframe.

They did this with a wide range of controls for example System.Web.UI.HtmlControls.HtmlTableCell and System.Web.UI.HtmlControls.HtmlAnchor.

Solution:

You need to recompile the code using the .net 4.5 runtime.
And when doing this, you need to change the *.designer.cs file reference from:

protected global::System.Web.UI.HtmlControls.HtmlGenericControl IFrame;

To:

protected global::System.Web.UI.HtmlControls.HtmlIframe IFrame;

A bug has been reported that the VS2012 does not make this change itself, but all I had to do was to rename the ID of the IFrame control, and VS figured it out for me.

More information:

Posted in .net, c#, General .NET | Tagged , , , | 5 Comments

A potentially dangerous Request.QueryString value was detected from the client

One of my colleagues encountered this error in Sitecore 6.6:

A potentially dangerous Request.QueryString value was detected from the client

You might think that this error was caused by the Microsoft AntiCSRF implementation by Sitecore.  But it is not, it’s actually caused by .NET 4.0:

According to Microsoft, they have changed the ASP.NET Request validation:

In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request. Source: http://www.asp.net/whitepapers/aspnet4/breaking-changes#0.1__Toc256770147

If you encounter this error, you need to switch the RequestValidationMode back to the good old mode:

<httpRuntime requestValidationMode="2.0" />

Read more here:

Thanks to Anders Laub Christoffersen for the tip.

Posted in .net, General .NET, Sitecore 6, Sitecore 7 | 1 Comment

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;
      break;
    }
  }
  return result;
}

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

READ MORE:

 

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:

/Date(1234567891234)/

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:

TimeZone.CurrentTimeZone.ToLocalTime(yourutctime)

 

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.

HOW TO FIX IT:

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

UPDATE:

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"/>

UPDATE 2:

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"?>
<configuration>
  <sitecore>
    <AntiCsrf>
      <rules>
        <rule name="shell">
          <!-- Ingore AntiCSRF completely -->
          <ignore wildcard="/sitecore/*"/>
        </rule>
      </rules>
    </AntiCsrf>
  </sitecore>
</configuration>
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:

SITECORE PAGE EDITOR

AN EXTENSIBLE PAGE EDITOR

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.

PAGE EDITOR LINK FIELD TYPE NEEDS TO ALLOW LOOKUP FIELDS

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.

PAGE EDITOR SHOULD HAVE A BUTTON FOR THE MEDIA LIBRARY

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

PAGE EDITOR SHOULD BE ABLE TO EDIT NON-VISUAL FIELDS

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

PAGE EDITOR SHOULD BE ABLE TO PUBLISH EVERYTHING THAT’S INCLUDED ON THE PAGE

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.

PAGE EDITOR SHOULD BE CHEAPER TO DEVELOP FOR

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.

SITECORE SHELL

ADDING COMPONENTS USING THE SHELL

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.

CODING

SC:FIELDRENDERER

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

SC:LINK

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

SC:EDITFRAME

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”

or:

“The URL-encoded form data is not valid”

WHY?

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.

WHAT TO DO?

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