Applying Datasources to Sitecore Controls – The Easy Way

Following on from my post The Importance of Datasources I thought I’d show a neat little trick to ensure Datasources are bound to all Sitecore controls within any component/Sublayout that you create.

The approach I normally take to binding Datasources is to firstly inherit from a base class, and get the base class to expose a DataSourceItem property which returns the Datasource, or if one isn’t provided return the context item:

public Item DataSourceItem
        // Ensure at the very least Context Item is returned as a fallback
        Item returnItem = Sitecore.Context.Item;

        if (Sublayout != null)
            string dataSourceString = Sublayout.DataSource;

            if (!string.IsNullOrEmpty(dataSourceString))
                Item dbItem = Sitecore.Context.Database.GetItem(dataSourceString);

                if (dbItem != null)
                    returnItem = dbItem;

        return returnItem;

(You can get the full base class I use from GitHub at

Then in my Component, bind the DatasourceItem to each Sitecore control that is contained within the component:

scTextField1.Item = DatasourceItem;

scTextField2.Item = DatasourceItem;

scImage1.Item = DatasourceItem;

Doing this in every component is a bit of a chore, especially when there are many Sitecore controls contained within the component. So I’ve created a function that will do this for us:

        public void BindDatasourceToSitecoreControls()

        public void BindDatasourceToSitecoreControls(Item dataSource)
            if (Controls.Count > 0)
                BindControls(this.Controls, dataSource);

        private void BindControls(ControlCollection controls, Item dataSource)
            foreach (Control control in controls)
                if (control is FieldControl)
                    var fieldControl = control as FieldControl;
                    fieldControl.Item = dataSource;

                if (control is FieldRenderer)
                    var fieldRenderer = control as FieldRenderer;
                    fieldRenderer.Item = dataSource;

                if (control.Controls.Count > 0)
                    BindControls(control.Controls, dataSource);

The BindControls function can be used to recursively traverse through any control collection and when it encounters a control which is of type FieldRenderer or FieldControl (which covers most of the Sitecore controls) it will assign the Datasource that you pass into the function.

There are also two additional functions

  • BindDatasourceToSitecoreContrls() – This function will simply bind the Datasource that is available to any Sitecore controls it finds. This is part of my SublayoutBase.cs base class (as part of the Sitecore Toolbox) and inherits from System.Web.UI.Control so utilises the control collection that is available. You can simply call BindDatasourceToSitecoreControls() from you Page_Load() when inheriting from SubloayoutBase.
  • BingDatasourceToSitecoreControls(Item dataSource) – This function override can be used if a specific Item is used as a Datasource

The above code is included in the SitecoreToolbox on GitHub:

Hopes this helps when using Datasources.

Feel free to leave a comment if you have any questions 🙂

Sitecore Services Client – Creating a Custom Authorisation Filter

Recently I’ve been looking into the Sitecore Services Client with interest. Sitecore Services Client was developed to provide a consistent way of integrating Client applications with Sitecore. There are many applications for this. You may have a client application (A SPEAK application, or a Single Page Application on a website) or even other systems acting as a “client” which requires to call Sitecore for information.

Sitecore Services Client is very extensible. The aspect I’m going to touch upon in this post in authorisation of requests.

The scenario I’m going to use for this is “Only authorise Sitecore Services Client if the IP address of the caller is the same as Sitecore itself”. This scenario could be useful if you had a bunch of services that are only designed to be available from applications that execute on the same box.

To do this, I’m going to create a LoopbackAuthorisationFilter which is designed to only authorise requests that origniate from the same IP address.

Firstly, create your class, inheriting from AuthorisationFilterAttribute (in the System.Web.Http.Filters namespace) and override the OnAuthorization function.

public class LoopbackAuthorisationFilter : System.Web.Http.Filters.AuthorizationFilterAttribute
        public override void OnAuthorization(HttpActionContext actionContext)
            // Play nicely with the base class

            // If the request does not originate from this machine
            if (!System.Web.HttpContext.Current.Request.IsLocal)
                // Create an Unauthorised Access response
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorised Access");

What I’m doing here is ensuring that the original request originates from the local machine (with the same IP address). If the originating request is different, create a HTTP Unauthorized response back to the caller.

To wire this up in Sitecore Services Client, all you need to do is to add an entry into the section of the Sitecore.Services.Client.config file:

<filter>SSCActionFilter.LoopbackAuthorisationFilter, SSCActionFilter</filter>

It’s as simple as that 🙂

I have an example project on GitHub for you to try if you wish which will compile a DLL for you to use with your Sitecore Serice Client implementation:

Whilst this filter is simplistic, it is very easy to extend it to cater for any scenario you require, or even create your own Authorisation Filter.

Hope you have fun with this!

To find out more about the Sitecore Services Client, have a look at the Developers Guide to Sitecore.Services.Client here:

The Importance of Datasources

Over the years I have been involved in my fair share of “rescue” projects with Sitecore with the most common of issues being projects that do not adhere to the standards and best practices of Sitecore.

One of the biggest complaints I hear is the lack of complete Page Editor functionality and components not being testable. Sitecore themselves make it their business to push personalisation and this is one of the key selling points of the Sitecore platform and goes some way to justify the license costs. That said, the lack of adhering to best practices may work for some (ensuring the quickest turnaround time) however later on down the line this will unravel when clients wish to utilise “out of the box functionality” that Sitecore provides.

Also, I’ve heard worrying phrases such as:

They haven’t been shown that or told to use that feature of the Page Editor


They don’t or shouldnt use it like that

or even worse

I can’t see this ever needing to be tested or personalised

Two things I normally advise with in these circumstances:

  1. Never make assumptions on how a client with use the Page Editor. Whilst they may not wish to use its functionality now, they may wish to utilise it in the future – so why make these assumptions in the first place?
  2. There may be a future possibility that the client will employ someone who is well versed in Sitecore who wants to begin to utilise the out of the box features of the Page Editor. Wouldn’t it be embarrassing if they clicked the “Set Associated Content” button in the Page Editor on a component and were unable to create a new Datasource to see what it would look like with different labels? (this is built-in, every component should support this)

Fortunately the above can easily be addressed by ensuring that Sitecore’s best practices of using Datasources for almost everything (unless its Presentation Configuration, in which you may wish to consider Parameter Templates). In fact, I rigidly adhere to Datasources unless there is a good and valid case not to.

Common Problems with components:

  • Not abiding to a Datasource at all – Components who get all of their data from the Context Item (which will be the Page). Bear in mind that the Context Item will be the Page – which normally means that there is a lack of separation of Site Information and Page Content.
  • Hard wired Datasources – the data for a component is pulled in via a link directly to a Content Item. The issue with this is obvious, if the Datasource is recreated it will be assigned a new ID, hence the code that utilises it will need to be updated.
  • Not restricting Datasources – Allowing “any” item to be bound as a Datasource that does not contain the correct fields that are expected by the component. Whilst the component might work, the Content Editor could break a component by assigning an inappropriate Datasource.
  • Inappropriate usage of Datasources – Using Dataosources that contain “too much information” i.e. a Global Item that is bound to the majority of components, or a component that takes data from multiple content items – making if difficult to personalise the component as DMS is only capable of taking control over the Datasource (remember, we should be in the habit of allowing ALL components to be personalised – it’s no extra work!)

To address the above, I normally create a base class that contains a DataSourceItem property. This is then bound to the Item property of all the Sitecore controls on the page. This means that the component doesn’t care where there Datasource is being set as that’s not the concern of the Component. All the component should care about is that it is “given” data by Sitecore.

I have an example of a base class that can be used on GitHub in my Sitecore Toolbox Project:

When creating the Sublayout in Sitecore I always ensure that each component is coupled with its related Datasource Template (it’s a good idea to create the Datasource Template first to prevent bouncing from Sublayouts to Templates to create the Datasource Template and back to Sublayouts to assign it to the Component). This ensures that the data that is passed to a component is known by the component (and developer) and prevents the scenario where the component has to make a call to a different Content Item in Sitecore for its information (i.e. the component needing to be knowledgable about your IA).

Coupled with this, it is important to specify Datasource Location fields when creating the Sublayout in Sitecore. This will ensure that all Datasources that are suitable for this Component are located in one location improving the experience for the Content Editor.When these fields are provided, Sitecore will not allow an inappropriate Datasource to be bound to a component and the Datasource Location ensures that all Datasource Items are stored in a logical place in Sitecore.

If there is a situation where data is required from different nodes of the content tree, these can be provided via Droplinks in the Datasource Template o those locations – again, this ensures there is clarity and understanding of the data that the component requires to function. This also improves component testability as if the client wishes to perform any AB/MV testing, this will be possible by creating alternative Datasources.

Even if the Content Editor does not want to utilise MV testing, there are other ways to test a component. I’ve had a client want to create two pages with the same component on both, but each component pointing to two different Datasources. This method was required to show an example of a page that contains different content to the CEO to get approval on which content to use. This did require a small amount of rework (as the component pointed to the Context Item for its data) but after a little rework my client was very pleased with the capability and really started to “get” the power of Sitecore.

If the above is adhered to, this will go a long way to ensure that your components

So, just to recap

  • Always use Dataources, they are very easy to use, and will save you rework in the future when you client wants to begin to utiilise other functionality of Sitecore (Testability/DMS etc.)
  • Adopt “Assumption-less Design” i.e. Never assume anything in the Component. Always get you data from the Datasource (unless there is a very good reason not to – fortunately there are not many of these!)
  • If you are finding that the Datasource is too large, it may be an indication that your component needs to be broken down into sub components.

Remember, as Developers it is our responsibility to design components that can be reused whenever required and to have the power to be testable and “personalisable” (is that a word?).

By taking this approach, you are not only ensuring that your clients gets Value for Money and can justify purchasing a Sitecore license, but also helps ensure the longevity of the components that you create 🙂

Feel free to leave any comments/questions 🙂

Dynamic Menu’s in Sitecore Part 2

Welcome to Part 2 of setting up Dynamic Menu’s in Sitecore. In this post, I will quickly demonstrate how easy it is to utilise the power. Of DMS to alter what is displayed in site navigation and empower users to make choices on which content is displayed.

If you want to have a look at how a dynamic menu can be structured, please read Part 1. This post will follow on from there.

So, just to recap, we now have a navigation Item, which is simply an instance of a Navigation link on your site and a Navigation Collection, which consists of a collection of Navigation Items. The Navigation Collection can then be used as a Datasource Navigation Component.

Let’s choose the simple scenario that you want to have a different navigation displayed for a user that has successfully logged into out site.

First let’s assume that we have the following Navigation Items defined:

Navigation Items

Now lets two navigation collections, one for not logged in and one for logged in:

Navigation Collections

The “Not Logged In” collection will contain links to the “Log in” and “Sign Up” Navigation Items:

Not Logged In Collection

The “Logged In” collection will contain links to the “My profile” and “Log out” Navigation Items”

Logged In Collection

As these two collections are designed to be used as Datasources, we need to establish which Datasource to pass to the Navigation component and what drives this decision. This can be achieved by setting up a Rule Condition

Then, set up a Rule Condition which will detect whether the user has logged in:

public class AuthenticatedRuleCondition&lt;T&gt; : TrueCondition&lt;T&gt; where T : RuleContext
protected override bool Execute(T ruleContext)
Assert.ArgumentNotNull(ruleContext, &amp;amp;amp;amp;quot;ruleContext&amp;amp;amp;amp;quot;);

if (Sitecore.Context.IsLoggedIn)
return true;

return false;

We also need to register this new Rule Condition in Sitecore. This can be done by inserting a new Conditional Rendering into the following location (replacing <rule-condition-class> the fully qualified namespace/class name and <dll> with the DLL in which the rule resides):


We can now use this Rule Condition to help decide which navigation to display. To do this, “Personalise” the component in the Presentation Layer and make use of this Rule Condition. Essentially what I am saying below is if my Rule Condition is true (i.e. the user is logged in), use a different Datasource to what is the default (the default is Not Logged In Datasource)


… and that’s it! It really is that simple. Sitecore already has a rule for authentication “when the current user is anonymous” (or the reverse of that rule) however the above can be easily modified to check for presence of a Role:

if (Sitecore.Context.User.IsInRole(&quot;extranet\\membership&quot;);)


// Perform some additional checks if necessary

return true; }

… or any other condition necessary.

When all is published, you will notice that Sitecore provides a different Datasource to the Navigation component when the user is logged in (or when the condition is met).

Hope this helps 🙂

Dependency injection and Inversion of Control (IOC)

I was involved in an interesting debate a few days ago regarding the importance of IOC containers and whether they are necessary, whilst this post will not teach you what IOC is (there are many excellent posts that do this) I just wanted to share my experience with IOC and one of the most compelling reasons for using them.

Sure, you can get by without using them, they are not mandatory for Dependency Injecion, however if you follow the Single Responsibility Principle (SRP), you will find they are a huge as advantage and also clean up your code no end.

For me, the “Eureka!” Moment came whilst doing TDD for the first time whilst exercising Separation Of Concerns and the Single Responsibility principle, I noticed that my class construction was becoming too involved and almost unreadable.

To quickly demonstrate this, I’ve put together a very crude implementation to demonstrate how IOC can assist.

For example, if I had a UserRegistration component that is dependent on a number of other classes, this is how it might look:

IUserRegistration registration = new UserRegistration(new CRMUserRegistration(),
new UserEmailSender(new SMTPService()),
new MembershipEmailSender(new SMTPService()));

As you can see, there are several dependencies being injected here. With a tool like StructureMap, all you need is a single declaration

IUserRegistration userRegistration = ObjectFactory.GetInstance<IUserRegistration>();


This does require a little setup:

var container = new Container();
container.Configure(x =>

This only needs to be done once in your code (normally on application start up)

As a user of the component you no longer need to know (or even care) what all the dependencies are which is great 🙂 You can still use the older method of declaring dependencies however there really is no need. StructureMap will automatically new up and instances that are required and even walk through the dependency tree creating any new instances that are necessary in any sub components that are required.

Also, as you are using an IOC (in the case StructureMap), you can quickly make an instance a Singleton instance without modifying your class:


I’ve quickly put together a project that demonstrates this principle .. not that none of the code does anything, this is purely for demonstration purposes 🙂

Within the project there is a RegistrationController.cs class which demonstrates the above – bear in mind the project doesn’t do anything, it’s purely for educational purposes. If I get a bit of time I might turn it in to something more useful 🙂

So, to conclude, there is no longer any need to create your own class factories to do this. IOC Containers are the way to go (well, in my opinion anyway).

Many many awesome posts have been written on this subject, take a look below for some further reading:

Indexing Multilist/Treelist fields and reading them back

Whilst in the process of ensuring Multilist/Treelist fields are being indexed and pulled back correctly, I came across a very useful blog post to assist in converting a list of GUID’s in the index back to an ID array

This works like a dream 🙂 Don’t forget to update your index config to reflect that you want to ensure that your field is being indexed (below is an example). The important part of this is ensuring “type” is set to “System.GUID”

<field fieldName="updated_specifications" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.GUID" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
<analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />

Also, you need to alter the definition of Droptree (or TreeListEx, or whatever field you are indexing) in <fieldTypes> section. By default the storageType is set to “NO”, change this to “YES”

Reindex your site with the TypeConverter and alterations to your index config and you should be good to go 🙂