Sitecore contact cannot be loaded, code never responds

In Sitecore, it is possible to encounter a situation where the calls identifying or locking a contact never responds, but there is no errors returned.

A call to identify:

Tracker.Current.Session.Identify(contactName);

And a call to Load a contact:

Contact contact = 
    contactRepository.LoadContactReadOnly(username);

Can both take forever without any errors or any timeout.

This situation can occur if the Contact Successor points to the original Contact in a loop. When merging a contact, Sitecore will create a new contact, the Surviving contact. The existing contact (called the Dying contact) still contains all the interaction data from before the merge, so instead of Sitecore having to update all data fields with a new ID, it creates a “Successor” pointer to the Dying Contact.

Surviving Contact

Surviving Contact

But in certain situations, the Dying Contact will also have a Successor, which points back to the Surviving Contact, creating an infinite loop:

The Dying Contact's Successor points to the surviving contact.

The Dying Contact’s Successor points to the surviving contact.

The patterns for this situation are many, but usually involves merging and changing contact identifiers, and can be reproduced like this:

  • Create a contact “A”
  • Create a new contact “B”
  • Merge contact “B” with “A”
  • Merge contact “A” with “B”

To avoid this situation, it is customary to rename the dying contact’s (“A”) identifier to an obscure name (a guid). But the renaming might fail if the dying contact is locked, leaving a contact with a reusable identifier. The “Extended Contact Repository” which I have described previously will unfortunately gladly create a new contact with an existing name.

HOW TO RESOLVE IT:

The situation needs to be resolved manually. Find the contact, open RoboMongo and search for the contact:

identifier = db.Identifiers.findOne({_id: /NAME_OF_IDENTIFIER/i});
contact = db.Contacts.find({_id: identifier.contact});

Copy the “Successor” value from the contact, and find the Successor:

successor = db.Contacts.find({_id: NUUID("b1e760d7-7c60-4b1d-818f-e357f303ebef9")});

Right click the “Edit Document” button and delete the “Successor” field from the dying contact:

Delete Successor Field from the Dying Contact, breaking the infinite loop

Delete Successor Field from the Dying Contact, breaking the infinite loop

This can be done directly in production, and the code reacts instantly when the loop have been broken.

MORE TO READ:

 

Posted in Sitecore 7, Sitecore 8 | Tagged , , , , | Leave a comment

Sitecore Media Library integration with Azure CDN using origin pull

If your Sitecore website is heavy on content from the media library you can offload your Sitecore instances by allowing images to be retrieved from a Content Delivery Network (CDN). If you use Microsoft Azure, you do not need to upload images to the CDN, as Azure support origin pull.

Origin pull is a mechanism where the CDN automatically retrieves any missing content item from an origin host if the content is missing. In Azure, even parameters to the content is supported, so if you scale images with ?w=100, these parameters are supported, and the Azure CDN will store the scaled image.

To set up origin pull in Azure CDN, you first go to your CDN profile:

Azure CDN Profile

Azure CDN Profile

Then you click the + sign to add an endpoint:

Azure CDN Add Endpoint

Azure CDN Add Endpoint

And add an endpoint with the type “Custom Origin”:

Azure CDN Endpoint with Custom Origin

Azure CDN Endpoint with Custom Origin

The “name” is the name of the endpoint. The “Origin hostname” is the URL to your public Sitecore website. And remember to specify the correct protocol. If your website is running HTTPS, the CDN should use HTTPS as well.

SETTING UP SITECORE:

The rest is configuration in Sitecore. You control the CDN properties using these settings, found in the Sitecore.config file:

<setting name="Media.MediaLinkServerUrl" value="https://myendpoint.azureedge.net" />
<setting name="Media.MediaLinkPrefix" value="-/media" />
<setting name="Media.AlwaysIncludeServerUrl" value="true" />
<setting name="MediaResponse.Cacheability" value="public" />
  • Media.MediaLinkServerUrl = The URL to the Azure CDN, as defined when creating the Azure Endpoint
  • Media.MediaLinkPrefix = The media library link URL. Together with the Media.MediaLinkServerUrl, the complete server URL is created. In the example, my url is https://myendpoint.azureedge.net/-/media/%5Bmedia library content]
  • Media.AlwaysIncludeServerUrl = Tells Sitecore to always include the server URL in the media requets
  • MediaResponse.Cacheability = Allows the cache settings of any item to be publicly available, allowing the Azure CDN to access the MaxAge, SlidingExpiration and VaryHeader parameters.

DRAWBACKS OF USING A CDN:

  • Your website needs to be public. When developing and testing you need to disable the CDN settings as the Azure CDN cannot read from a non-public website. Testing is therefore in production as the website runs.
  • Security settings on media library items cannot be used. Once a media library item is on the CDN it is public to everyone.

MORE TO READ:

 

Posted in Sitecore 8 | Tagged , , , , , , , | 3 Comments

Sitecore ContentSearch – Get items from SOLR or Lucene – A base class implementation

Reading items from Sitecore is pretty straight forward:

Sitecore.Data.Items.Item item = 
   Sitecore.Context.Database.GetItem("/sitecore/context/.../...");

And it is fast, unless you need to retrieve items from many paths, or need to retrieve every child of a certain base class. In these situations you resolve to using the built in ContentSearch, which is a Lucene or SOLR index.

When working with objects from the ContentSearch API you will have to create your own model classes that maps the indexed fields to class properties. This is done using an IndexFieldAttribute to the properties of the class that will represent the indexed data:

[IndexField("customerpage")]
public ID CustomerPageId {	get; internal set; }

[IndexField("customername")]
public string CustomerName { get; internal set; }

The default indexes called sitecore_core_index, sitecore_master_index and sitecore_web_index is born with a long list of default properties that is useful for every class. Because of this it makes sense to let every one of your model classes inherit from a base class that maps these fields for you.

So let’s code.

STEP 1: CREATE A BASE CLASS

This base class maps the most common fields. There are many more for you to explore, but this particular class have been the base class of a huge project that I have been working on for the past 4 years:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Sitecore.Configuration;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Converters;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;

namespace MySearch
{
  [Serializable]
  public abstract class SearchResultItem
  {
    [NonSerialized]
    private Item _item;

    // Get the actual Sitecore item. Beware that using this property 
    // will substantially slow your query, as it looks up the item
    // in Sitecore. Use with caution, and try to avoid using it in
    // LINQ or enumerations 
    public virtual Item Item
    {
      get { return _item ?? (_item = GetItem()); } set { _item = value; }
    }

    // Returns the Item ID (in SOLR this is stored as a short GUID in the _group field)
    [IndexField(Sitecore.ContentSearch.BuiltinFields.Group)]
    [TypeConverter(typeof(IndexFieldIDValueConverter))]
    public virtual ID ItemId
    {
      get; set;
    }

    // This is a combined key describing the Sitecore item in details
    // For example: sitecore://web/{7102ee6b-6361-41ad-a47f-832002082a1a}?lang=da&ver=1&ndx=sitecore_web_index
    // With the ItemUri class you can extract the individual values like database, id, language, version
    [IndexField(Sitecore.ContentSearch.BuiltinFields.UniqueId)]
    [TypeConverter(typeof(IndexFieldItemUriValueConverter))]
    public virtual ItemUri ItemUri
    {
      get; set;
    }

    // Return the item language
    [IndexField(Sitecore.ContentSearch.BuiltinFields.Language)]
    public virtual string Language
    {
      get; set;
    }

    // Returns true if the item is the latest version. When reading from the
    // web database index, this will alwaus be true.    
    [IndexField(Sitecore.ContentSearch.BuiltinFields.LatestVersion)]
    public bool IsLatestVersion
    {
      get; set;
    }

    // Returns the ID's of every parent sorted by top parent first
    [IndexField(Sitecore.ContentSearch.BuiltinFields.Path)]
    [TypeConverter(typeof(IndexFieldEnumerableConverter))]
    public virtual IEnumerable<ID> ItemAncestorsAndSelf
    {
      get; set;
    }

    // Returns the updated datetime
    [IndexField(Sitecore.ContentSearch.BuiltinFields.SmallUpdatedDate)]
    public DateTime Updated
    {
      get; set;
    }

    // Returns every template that this item implements and inherits
    [IndexField(Sitecore.ContentSearch.BuiltinFields.AllTemplates)]
    [TypeConverter(typeof(IndexFieldEnumerableConverter))]
    public virtual IEnumerable<ID> ItemBaseTemplates
    {
      get; set;
    }

    private Item GetItem()
    {
      Assert.IsNotNull(ItemUri, "ItemUri is null.");
      return Factory.GetDatabase(ItemUri.DatabaseName).GetItem(ItemUri.ItemID, ItemUri.Language, ItemUri.Version);
    }
  }
}

STEP 2: CREATE A MODEL CLASS FOR A SPECIFIC TEMPLATE

This example inherits from the SearchResultItem base class, and encapsulates a Customer template containing 2 fields, CustomerPage and CustomerName.

namespace MySearch
{
  [DataContract]
  [Serializable]
  public class CustomerModel : SearchResultItem
  {
    [DataMember]
    [IndexField("customername")]
    public string CustomerName { get; internal set; }

    [IndexField("customerpage")]
    public ID CustomerPageId { get; internal set; }
  }
}

STEP 3: USING THE BASE CLASS TO SEARCH USING PREDICATES

A Predicate are a Latin word for “making search soo much easier”. Predicates defines reusable static functions. When run, Predicates become part of the index query itself, further improving performance. So let’s start by making 3 predicates:

namespace MySearch
{
  public static class Predicates
  {
    // Ensure that we only return the latest version
    public static Expression<Func<T, bool>> IsLatestVersion<T>() where T : SearchResultItem
    {
      return searchResultItem => searchResultItem.IsLatestVersion;
    }

    // Ensure that the item returned is based on, or inherits from the specified template
    public static Expression<Func<T, bool>> IsDerived<T>(ID templateID) where T : SearchResultItem
    {
      return searchResultItem => searchResultItem.ItemBaseTemplates.Contains(templateID);
    }

    // Ensure that the item returned is a content item by checking that the 
    // content root is part of the item path 
    public static Expression<Func<T, bool>> IsContentItem<T>() where T : SearchResultItem
    {
      return searchResultItem => searchResultItem.ItemAncestorsAndSelf.Contains(ItemIDs.ContentRoot);
    }
  }
}

With these predicates in place, I can create a repository for my Customer items:

namespace MySearch
{
  public class CustomerModelRepository
  {
    private readonly Database _database;

    public CustomerModelRepository() : this(Context.Database)
    {
    }

    public CustomerModelRepository(Database database)
    {
      _database = database;
    }

    public IEnumerable<CustomerModel> GetAll()
    {
      return Get(PredicateBuilder.True<CustomerModel>());
    }

    private IEnumerable<CustomerModel> Get(Expression<Func<CustomerModel, bool>> predicate)
    {
      using (IProviderSearchContext context = GetIndex(_database).CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
      {
        return context.GetQueryable<CustomerModel>()
          .Where(Predicates.IsDerived<CustomerModel>(new ID("{1EB6DC02-4EBD-427A-8E36-7D2327219B6C}")))
          .Where(Predicates.IsLatestVersion<CustomerModel>())
          .Where(Predicates.IsContentItem<CustomerModel>())
          .Where(predicate).ToList();
      }
    }
    
    private static ISearchIndex GetIndex(Database database)
    {
      Assert.ArgumentNotNull(database, "database");
      switch (database.Name.ToLowerInvariant())
      {
        case "core":
          return ContentSearchManager.GetIndex("sitecore_core_index");
        case "master":
          return ContentSearchManager.GetIndex("sitecore_master_index");
        case "web":
          return ContentSearchManager.GetIndex("sitecore_web_index");
        default:
          throw new ArgumentException(string.Format("Database '{0}' doesn't have a default index.", database.Name));
      }
    }
  }
}

The private Get() method returns every index item following these criteria:

  • Must implement or derive from the template with the specified GUID (the GUID of the Customer template) = Predicates.IsDerived
  • And must be the latest version = Predicates.IsLatestVersion
  • And must be a content item = Predicates.IsContentItem

The repository is used like this:

CustomerModelRepository rep = new CustomerModelRepository(Sitecore.Context.Database);
IEnumerable<CustomerModel> allCustomers = rep.GetAll();
foreach (CustomerModel customer in allCustomers)
{
  // do something with the customer
  customer.CustomerName;
}

I hope this introduction will help you create your own base class implementation and start making fast content searches.

MORE TO READ:

For more SOLR knowledge, you should read my colleague Søren Engel‘s posts about SOLR:

These resources could also be helpful:

 

Posted in .net, c#, General .NET, Sitecore 7, Sitecore 8 | Tagged , , , , , , | Leave a comment

Sitecore user:created event not fired on Membership.CreateUser

Sitecore have since 7.5’ish fired events each time you manipulate the users in the .NET Membership database:

<event name="user:created"></event>
<event name="user:deleted"></event>
<event name="user:updated"></event>
<event name="roles:usersAdded"></event>
<event name="roles:usersRemoved"></event>

But I noticed that the user:created event was not fired. This is because I call the .NET Membership provider directly:

string userNameWithDomain = "extranet\\myuser";
string password = "somepassword";
string email = "myuser@somewhere.com";
Membership.CreateUser(userNameWithDomain, password, email);

This call to Membership is not handled by Sitecore, thus no event is executed. To fix this I have found 2 solutions, one is not good and the other one is not good either.

SOLUTION 1: CALL THE SITECORE MEMBERSHIP PROVIDER DIRECTLY

This solution ignores the web.config settings and assume that you have not switched or overwritten the Membership Provider yourself. But it will fire the event though:

Sitecore.Security.SitecoreMembershipProvider provider = new Sitecore.Security.SitecoreMembershipProvider();
MembershipCreateStatus status = MembershipCreateStatus.Success;
provider.CreateUser(usernameWithDomain, password, email, "", "", true, null, out status);
if (status != MembershipCreateStatus.Success)
  throw new MembershipCreateUserException(status);

SOLUTION 2: RAISE THE EVENT YOURSELF

This solution requires you to raise the event yourself. You need encapsulate the call to create a user in your own class, and instruct everyone to never call Membership.CreateUser() directly:

MembershipUser user = Membership.CreateUser(usernameWithDomain, password, email);
Event.RaiseEvent("user:created", user);

I can see from other blog posts that the user events are not the most widely used events in the Sitecore toolbox. If you have found another solution to this problem please let me know.

MORE TO READ:

Posted in .net, c#, General .NET, Sitecore 7, Sitecore 8 | Tagged , , , , , , , , | Leave a comment

Sitecore ContentSearch Get Latest Version

The Sitecore ContentSearch API allows you to index content in either .NET Lucene or SOLR, dramatically speeding up retrieval of content, especially when querying items that are scattered across your content tree.

Content retrieved from the ContentSearch API is not Sitecore Content Items (of type Sitecore.Data.Items.Item), they are objects that you have defined yourself. This is why you will experience that when querying from the MASTER database index (SITECORE_MASTER_INDEX), you will receive one result per version (and one result per language) rather than one Item object containing all versions and languages.

To overcome this issue, Sitecore have added a few nifty fields to the index, for example the _latestversion field:

Latest Version Field from SOLR

Latest Version Field found in my SOLR index

So when querying the index, you can add the _latestversion field:

query = query.Where(item => item["_latestversion"].Equals("1")); 

BTW, _latestversion is defined in a constant value in Sitecore:

Sitecore.ContentSearch.BuiltinFields.LatestVersion;

MORE TO READ: 

Posted in .net, c#, General .NET, Sitecore 7, Sitecore 8 | Tagged , , , , , | 1 Comment

Sitecore Caching – Clear caches individually

The Sitecore caching engine is a simple yet powerful tool where Sitecore not only stores it’s own data for fast retrieval, but allows you to store your own data of any kind. Sitecore have a built in overview of the contents of the caches, but the overview lacks the possibility to clear caches individually.
The cache admin is located on the /sitecore/admin/cache.aspx URL, and as you can see, you can only clear all caches:

Sitecore Cache Overview

Sitecore Cache Overview

Clearing one cache at a time is very easy:

Sitecore.Caching.Cache cache = Sitecore.Caching.CacheManager.FindCacheByName("name of cache");
cache.Clear();

So it is not that hard to create your own cache admin page that can clear each cache individually:

Your own Cache Overview Page

Your own Cache Overview Page

This is a simple .aspx page that lists all caches, displays some nice cache stats, and sports a nice “Clear Cache” button that clears that specific cache. The code is simple:

<%@ Page language="c#" EnableEventValidation="false" AutoEventWireup="true" EnableViewState="false" %>
<%@ Import Namespace="System.Security.Permissions" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Security.Principal" %>

<script runat="server">
  void Page_Load(object sender, System.EventArgs e)
  {
    Response.Buffer = false;
    Response.BufferOutput = false;
    DataBind();
  }

  IEnumerable<Sitecore.Caching.Cache> Caches
  {
    get
    {
      return Sitecore.Caching.CacheManager.GetAllCaches().OrderBy(c => c.Name);
    }
  }

  double PercentageUsed(Sitecore.Caching.Cache cache)
  {
    if (cache.MaxSize == 0)
      return 0;
    return Math.Round(((double)cache.Size/(double)cache.MaxSize*100), 0);
  }

  string PercentageColor(double percentage)
  {
    if (percentage >= 0 && percentage <= 50)
      return "green";
    if (percentage >= 50 && percentage <= 75)
      return "orange";
    return "red";
  }

  private void repCaches_Command(object source, RepeaterCommandEventArgs e)
  {
    switch (e.CommandName)
    {
      case "ClearCache":
        string cacheName = e.CommandArgument as string;
        Sitecore.Caching.Cache cache = Sitecore.Caching.CacheManager.FindCacheByName(cacheName);
        cache.Clear();
        repCaches.DataBind();
        break;
    }
  }

  long TotalMaxSize()
  {
    long ac = 0;
    foreach (var cache in Caches)
      ac = ac + cache.MaxSize;
    return ac;
  }

  long TotalSize()
  {
    long ac = 0;
    foreach (var cache in Caches)
      ac += cache.Size;
    return ac;
  }

  double TotalPercentageUsed()
  {
    if (TotalMaxSize() == 0)
      return 0;
    return Math.Round(((double)TotalSize()/(double)TotalMaxSize()*100), 1);
  }
</script>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>Cache Plus</title>
    <style type="text/css">
      body {
        font: normal 12pt arial, verdana;
        padding:20px;
      }

      .box {
        padding:20px;
        margin:20px;
        border: solid 1px black;
        background-color:#efefef;
      }

      input {
        height: 30px;
        width: 100px;
      }

      td {
        border-bottom: solid 1px #aaa;
        padding-right: 20px;
        padding-left: 5px;
        padding-top: 5px;
        padding-bottom: 5px;
      }

      table {
        width:100%;
      }

      thead td {
        font-weight: bold;
        border-bottom: solid 1px #aaa;
        padding-right: 20px;
      }
    </style>
  </head>
  <body style="font-size:14px">
    <form runat="server">
      <div style="padding:20px; background-color:#eaeaea; border-bottom: solid 1px #777777; font-size:16px">
        <%# Sitecore.StringUtil.GetSizeString(TotalSize()) %> of <%# Sitecore.StringUtil.GetSizeString(TotalMaxSize()) %> used <strong>(<%# TotalPercentageUsed() %>%)</strong>
      </div>
      <asp:Repeater ID="repCaches" runat="server" EnableViewState="false" OnItemCommand="repCaches_Command" DataSource="<%# Caches %>">
        <HeaderTemplate>
          <table>
            <thead>
            <tr>
              <td>Name</td>
              <td></td>
              <td>Size</td>
              <td>MaxSize</td>
              <td>% Used</td>
            </tr>
            </thead>
        </HeaderTemplate>
        <FooterTemplate>
          </table>
        </FooterTemplate>
        <ItemTemplate>
          <tr>
            <td style="width:250px">
              <%# (Container.DataItem as Sitecore.Caching.Cache).Name %>
            </td>
            <td style="width:100px">
              <asp:Button ID="btnClearCache" runat="server" CommandArgument="<%# (Container.DataItem as Sitecore.Caching.Cache).Name %>" CommandName="ClearCache" text="Clear Cache"/>
            </td>
            <td style="text-align: right; width:80px">
              <%# Sitecore.StringUtil.GetSizeString((Container.DataItem as Sitecore.Caching.Cache).Size) %>
            </td>
            <td style="text-align: right; width:80px">
              <%# Sitecore.StringUtil.GetSizeString((Container.DataItem as Sitecore.Caching.Cache).MaxSize) %>
            </td>
            <td>
              <div style="width:<%# PercentageUsed((Container.DataItem as Sitecore.Caching.Cache)) %>%; height:30px; background-color:<%# PercentageColor(PercentageUsed((Container.DataItem as Sitecore.Caching.Cache))) %>; float:left;"></div>
              <div style="width:<%# (100 - PercentageUsed((Container.DataItem as Sitecore.Caching.Cache))) %>%; height:30px; background-color:#ccffcc; float:left;"></div>
            </td>
          </tr>
        </ItemTemplate>
      </asp:Repeater>
    </form>
  </body>
</html>

Copy the code to a file named .aspx, and put the file in /sitecore modules/shell.

MORE TO READ:

Thanks to Richard Hauuer @richardhauer for the inspiration to write this article.

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

Sitecore and Feature Flags using LaunchDarkly

Feature flags are a software development best practice of gating functionality. Functionality can be deployed “off”, then turned on via the feature flag, separate from deployment. With feature flags, you can manage the entire lifecycle of a feature.

  • Launchdarkly.com

In essence, a feature flag is a if..then..else statement, where the outcome of the statement is controlled by feeding a flag into a feature flag system:

if (GetFeatureFlag("feature-flag") == true)
{
  // enable my feature
}
else
{
  // disable my feature
}

Feature flags are user specific and can be used cross platform, and is therefore a great way to release new features:

  • At the same time on all platforms
  • To 10% of all users
  • To all users from a specific segment
  • To website only

Feature flags should not be confused with Sitecore Personalization, although they both share similarities. The purpose of Personalization is to tailor the user experience to the end users needs, whilst feature flags (or feature toggling) is enabling or disabling features based on rules separate from deployment or code.

A feature flag is often short-lived, and the flag is removed when the gated feature is considered stable.

 

ABOUT THE FEATURE FLAG PLATFORM

I have lately worked with a feature flag platform called “Launchdarkly“. They offer API’s for every possible programming language and for every possible platform. Their code is blazingly fast, and you do not notice any performance loss when checking for a flag.

Feature Flags Overview

Feature Flags Overview

In Launchdarkly, you can enable features by flipping a switch, or by segmenting on user data:

Feature Flags Targeting

Feature Flags Targeting

 

IMPLEMENTING LAUNCHDARKLY IN SITECORE

In order to check for a feature flag, we need to send user data and a feature flag name to Launchdarkly. The Launchdarkly API uses a Launchdarkly.Client.User and you can fill any property from your Sitecore User to the Launchdarkly Client User.

This is a simple example where I create a Launchdarkly user containing a unique ID, the email address and a name:

using System;
using LaunchDarkly.Client;

namespace MyNamespace
{
  static internal class LaunchDarklyFactory
  {
    static internal User CreateUser()
    {
      var user = Sitecore.Context.User;
      var key = user.IsAuthenticated ? user.Name : Guid.NewGuid().ToString();
      var ldUser = User.WithKey(key).AndAnonymous(!user.IsAuthenticated).AndEmail(user.Profile.Email).AndFirstName(user.Profile.FullName).AndLastName("."); //LaunchDarkly won't update display name unless both first and last is set.
      return ldUser;
    }
  }
}

With the user in hand it is easy to create a feature flag repository:

using System;
using LaunchDarkly.Client;
using Sitecore.Configuration;
using Sitecore.Diagnostics;

namespace MyNamespace
{
  public static class LaunchDarklyRepository
  {
    // My Launchdarkly key is stored in a setting in a config file
    private static readonly LdClient _client = new LdClient(Settings.GetSetting("LaunchDarkly.Client"));

    public static bool GetFeatureFlag(string flag, bool defaultValue)
    {
      try
      {
        var ldUser = LaunchDarklyFactory.CreateUser();
        return _client.BoolVariation(flag, ldUser, defaultValue);
      }
      catch (Exception ex)
      {
        Log.Error(typeof (LaunchDarklyRepository) + ".GetFeatureFlag() failed to get feature flag '" + flag + "', returning default value " + defaultValue + ". Message:" + ex.Message, typeof (LaunchDarklyRepository));
        return defaultValue;
      }
    }
  }
}

The repository can now be used to enable or disable features:

if (LaunchDarklyRepository.GetFeatureFlag("my-feature-flag", false))
{
  // feature enabled
}
else
{  
  // feature disabled
}

 

INTEGRATING LAUNCHDARKLY INTO THE EXPERIENCE EDITOR

Experience Editor

Experience Editor

With the new feature flag framework in place, it could be nice with a Sitecore Rule. This rule will allow me to enable and disable components on my website by flipping a feature flag switch. The rule itself is very simple:

using System;
using Sitecore.Diagnostics;
using Sitecore.Rules;
using Sitecore.Rules.Conditions;

namespace MyNamespace
{
  public class FeatureFlagHasBoolVariation<T> : WhenCondition<T> where T : RuleContext
  {
    public string FeatureFlag
    {
      get;
      set;
    }

    public bool BoolVariation
    {
      get;
      set;
    }

    protected override bool Execute(T ruleContext)
    {
      try
      {
        LaunchDarklyUser user = LaunchDarklyUserFactory.GetLaunchDarklyUser();
        var boolVariation = LaunchDarklyRepository.GetFeatureFlag(FeatureFlag, false);
        return boolVariation == BoolVariation;
      }
      catch (Exception ex)
      {
        Log.Error(string.Format("{0}: {1} ", GetType(), ex.Message), ex, this);
        return false;
      }
    }
  }
}

To enable the rule in Sitecore, add an item under /sitecore/system/Settings/Rules/Definitions/Elements/…

Feature Flag Personalisation Rule

Feature Flag Personalization Rule

The rule can now applied to a component:

Rule Set Editor

Rule Set Editor

And the component can be visible if the flag is set:

Personalize Content

Personalize Content

MORE TO READ

Posted in c#, General .NET, Sitecore, Sitecore 8 | Tagged , , , , | Leave a comment

Sitecore how to configure SSL (HTTPS) in your Sitecore config files

SSL and HTTPS have been the hot topic since Google began to use HTTPS as a signal in their search rankings.

Fortunately, Sitecore really does not care if it runs in HTTP or HTTPS, so most of the configurations are purely .NET related. Here is what you do if you have a single domain Sitecore installation, or a Sitecore installation that shares the root domain (en.mydomain.com/de.mycomain.com/…).

STEP 1: OBTAIN A SSL CERTIFICATE AND INSTALL IT ON YOUR SERVER

This usually involves a hosting company. If you are lucky enough (as I am) to know a hosting company that takes responsibility and provide a great service, this requires sending a mail and wait for the answer. If not you can follow one of the many guides online on how to obtain and install the SSL certificate.

STEP 2: MODIFY FORMS AUTHENTICATION

In web.config, add your domain to the forms authentication. This is pure .NET, nothing to do with Sitecore. Replace the MYCOMAIN.COM with your own domain.

<authentication mode="None">
  <forms domain=".MYDOMAIN.COM" timeout="43200" slidingExpiration="true" name=".ASPXAUTH" cookieless="UseCookies" />
</authentication>

STEP 3: MODIFY HTTPCOOKIES

In web.config, add your domain and set requireSSL in the httpCookies property. Again, this is .NET, not Sitecore specific. This binds any cookies to the root domain we specify, and secures the cookie (no cookies are sent to the server unless the connection is secure (HTTPS)).

<httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" domain=".YOURDOMAIN.COM" />

STEP 4: CHANGE THE SCHEME PROPERTY IN THE SITES SECTION

In Sitecore.config, set the scheme=”https” in your sites section. This is used by Sitecore when URL’s are generated, and ensures that when a fully qualified URL is generated, the URL is prefixed with https://

<site name="website" 
      scheme="https"
      hostName="YOURDOMAIN.COM" 
      targetHostName="YOURDOMAIN.COM" 
      ... ... 
/>

STEP 5: ALLOW YOUR IIS OR LOAD BALANCER TO REDIRECT ALL REQUESTS FROM HTTP TO HTTPS

The site as configured now will still serve pages using the HTTP protocol. But any cookies will not be persisted unless we use the proper domain and proper scheme. So you need to redirect any HTTP request to HTTPS. This is always a fun coding project, but can also be achieved by configuring the load balancer, or using the IIS URL Rewrite Module.

MORE INFO

 

Posted in Sitecore 6, Sitecore 7, Sitecore 8 | Tagged , , | 1 Comment

Sitecore Hiding items: Clean up the cluttered content tree

As a followup to a question from Derek Dysart on my previous post, How to make the experience editor a great experience for your editors I will explain how you can clean up the Sitecore content tree by hiding system items.

A common system item is the “components” (or whatever you call it) folder containing the data sources for components belonging to a certain content item. This folder is usually placed below your content item. The folder have no presentation, no URL, and does only exist because we like to build pages from many data sources in order to be able to personalize every component of a page.

Components Folder

A Components folder below the content item

This is not something the editors should see. Their tree should only contain the actual contents of the website.

A tree containing content only

A tree containing content only

All you have to do to is to select the “components” folder on your master, go to the “Configure” tab and select “Hide item“:

Hide Item

Hide Item

When the item is hidden, the button text changes:

Hidden Item

Hidden Item

Hiding items does only mean that the item is gone from the content tree. The item is still fully available from Sitecore, and also from the Experience Editor:

Hidden folder visible in the Experience Editor

Hidden folder visible in the Experience Editor

Also, as an administrator you can still see the item, provided you check the “Hidden Items” on the “View” tab:

View Hidden Items Enabled

View Hidden Items Enabled

MORE TO READ:

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

Sitecore how to make the experience editor a great experience for your editors

In Sitecore it is very easy to toss in a few renderings on a page, set the renderings flag to “editable”, and voila, the page is editable using the Sitecore Experience Editor.
But that kind of laziness often ends up being a pain for the people using the Experience Editor. Just image that it is you who gets this screen when selecting a rendering:

Select a Rendering - the bad way

Select a Rendering – hmm what to choose?

Wouldn’t you prefer a screen like this:

Select a rendering - the better way

Select a rendering – with images and translated text

Stuff like this takes more time that knowledge to do. So here is a quick guide on how to set up Sitecore so your renderings are presented properly in the experience editor.

 

SETTING UP YOUR RENDERING OR SUBLAYOUT

I still use sublayouts, the webform (.ascx) based renderings, but the techniques are the same for MVC based renderings. I will use the term “rendering” to cover both technologies.

THE DISPLAY TITLE

First of all, you need to set a display title for your renderings, as this is what Sitecore displays below the image. Remember that the language used for the display title is not the language you are editing, but the language in which Sitecore is running – exactly the opposite of what the Sitecore Shell does.

A rendering with a display title

All renderings with a display title, here in Danish

THE DATASOURCE LOCATION AND DATASOURCE TEMPLATE

In my project I save all data sources in a hidden folder below my item. This means that they are not shareable between items. A small trade off for a better overview of which components are placed on the page (this is only half the truth – some renderings are in fact shared but for the most part they are not. You should carefully decide what content is shareable and what is not). Setting up the data source location is done using a Sitecore query pointing to the folder below the current item:

Datasource Location and Template

Datasource Location and Template

When the user is seeing the “Select the Associated Content” window, only the components on the page is displayed. Also note that I have given each of my templates their own icon. This helps also.

Select the Associated Content

Select the Associated Content window

THE IMAGE

The field for the image shown in the “Select a Rendering” window is hidden in the appearance section of Sitecore, so you must enable the “Standard Fields” to find it. It is the field called “Thumbnail“.
Now, I know that the field have a “Take screenshot” function, the thumbnail is only 128×128 pixels, making a screenshot very small. I always make a stylized image, upload it to the media library in my own “System” folder and use that instead.

Thumbnail

Thumbnail

When moving the rendering to production you must remember to include the image in your package.

 

SETTING UP YOUR TEMPLATE

The template needs to be user friendly too. Here is what you can do:

THE ICON

Sitecore contains 16.000+ icons, and yes, none of these match your needs. However, spend a few minutes to see if you can find an icon that matches as close as possible. The icon is presented in the “Select the Associated Content” window so although it is not the most important part of your user experience, it is cheap to implement.

Templates with icons

Templates with icons

THE FIELD TITLE

Remember to set a title for your field. My field names are namespaced and rather technical. The user should not be aware of my strange naming. Use the field “Title” and again, remember that it is the language of the Sitecore instance that is displayed, not the language of your content – the exact opposite of what the Sitecore Shell does.

Editing the title

Editing the title – here with a translated text for the field

 

SUMMARY

Setting up the renderings for the experience editor requires more time than knowledge. Be lazy and the end user will hate you. Be thorough and your end user will love you.

 

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