Thursday, September 05, 2013

Working with Component / Data Templates

Avoiding the Page Template Mistake

This blog post is part 3 in a series on “Creating good Sitecore solutions”. Rather than constantly going back and adding edits to the previous posts, just follow this link to get an overview of the series.

A few thoughts

As promised in my last post; The Page Template Mistake; I will now attempt to put my money where my mouth is (so to speak) and provide something more concrete as to how the Page Template Mistake can be avoided, and how your implementation might carry forward without encountering it.

Before I do however, I will just clarify a few things that perhaps got lost in the previous posts.

I do believe that there is a time and a place for Page Templates. It just follows much later in the process and is a much more dynamic entity than what was certainly the case for my own solutions. I would not recommend content editors being forced to add any and all components to a blank “page canvas” for every page they create – we have Page Templates, Layout Presets and other technologies to help them out here.

What I advocate is, that you move the entire consideration of Page Templates much much further back in the process. Move it to the very end. Both to help you verify and assess components as the project comes about (if you’re tasked with that role), but also to help developers break free of the Page Template mindset entirely.

Your project will be better off for it.

My next post will be coming full circle, and demonstrate how Page Templates can be set up once you have all your Component Templates in place and – and I feel this point is important, because this used to be such a hassle for me in the past – how you can easily and quickly mock up new Page Templates as the situation requires, without breaking a sweat of what might break. Think yellow screens, think “Object Reference Not Set…” – all the common mishaps that you’ve experienced when tossing components onto a newly set up Page Template in the past.

Lastly; You’re not doing this specifically when “designing for the Sitecore Page Editor” as a few have suggested. That is a misunderstanding. What I am suggesting here is an approach that you would be taking if you’ve decided to make a good Sitecore solution. That it also happens to be a prerequisite for most meaningful work in the Sitecore Page Editor is consequential and accidental, you should not set out to “design for the Page Editor” at all.

After all – in doing so – you are inferring that this is a specific task, possibly an extra task. It is not. What I am suggesting is cost free, adds no overhead to your project. If done up front, that is. If you start by deciding to build a good Sitecore solution.

And on that note, let’s get to it.

Implementing a Component Template

To serve as an example, I’ll pick a component from the – in theory – up and coming CorePoint IT website (my own one-man consulting company). I say in theory because just as the mechanics own car, somehow working on this website always seems to end up fairly low on my priority list ;-)

I’ll pick something simple to start off with. In the HTML I’ve had done for the site, it looks like this:

04-09-2013 19-13-20

Looking at the HTML snippet for this component, it looks like this.

<div id="topBanner">
    <img src="images/banners/glass.gif" alt="" />
    <div id="topBannerContent">
        <h4>The company that does anything...</h4>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    </div>
    <a href="#">Read more >></a>
</div>

No big surprises there. Not too happy about the “id” attributes in there but let’s set aside that discussion for the time being.

I identify 5 tokens (tokens is a bad term. Anyone have another suggestion?) in there that I would like to see content managed on this component.

  • Heading
  • Body Text
  • Image
  • Link Text
  • Link

Breaking up the link near the bottom into two separate entities is a habit I’ve adopted. While it is possible on a Sitecore “General Link” for content editors to specify things such as Link Text; this doesn’t hold true for “Internal Link”. Doing it like this as a convention just saves a lot of grief.

Setting up the Component Template

04-09-2013 19-34-45

While this may look apparent, there are quite many (of my own) conventions in play here. I recommend you follow them, each of them will grant you “+2 to the overall Sitecore goodness feel”.

  • Give your component a good name. As “good” is subjective, here’s a few examples of component names that are NOT good (all of them from real life):
    • phInnerHeadingBox
    • HeroBoxTopRight
    • Content Spot
  • Set an icon for your Component Template. First thing, no delay. And while you can try and be creative and find an icon that “matches what your component does”, you will likely fail – the icon set is too generic for that. Don’t worry though, as it doesn’t really matter WHAT icon you choose – just that you choose one, and choose the same one in the steps to follow.
  • Place your fields in one “Section” named in exactly the same manner as your component.
  • Assign the icon from above, to that Section as well. Here’s how:
    04-09-2013 19-43-12
  • Name your fields, prefixed with the Component Name.
    • This is controversial, I know. But given that Sitecore does not distinguish Sections when addressing fields, and you cannot make any assumptions at this stage about the Page Template that your component will be living on (since you don’t know, and never will) – doing it like this provides the Path of Least Surprise later on.
    • Also keep in mind; field names mean nothing (really) when your content editor user is in the Page Editor – and given that the same user is given the context via the Section in the Content Editor, they won’t have much trouble scanning the fields for the one they need there either.
  • Set a short help text for each of your fields. This often overlooked step will mean a world of difference for your Content Editor users, takes you about 10 seconds per field (at this stage in the process) and grants you “Sitecore goodness” karma. If you haven’t done this before – try it. Take my word for it. Here’s how:
    04-09-2013 20-04-21

And you’re done. For now.

Setting up the Component

Proceed with your method of choice to set up the Sublayout Component in Sitecore. (Covering everything involved in this step probably could use a blog post of it’s own. I deem this out of scope for this one). Name it the same as your Component Template.

04-09-2013 20-11-03

Carry out these steps:

  • Set the icon for the Component to the same icon you chose for the Component Template.
    04-09-2013 20-13-34
  • Set the Datasource Template to your Component Template.
    04-09-2013 20-14-59

    04-09-2013 20-16-04
  • Finally take a snapshot of your component, and set up the Component thumbnail.
    • If your Component is part of a multi-site solution and look completely different between the sites, leave out this step. Sitecore requires customization to be able to do site-specific thumbnails, something I might cover in a later post. Tweet if you want it. @cassidydotdk ;-)

      If there is no thumbnail defined, Sitecore will show an enlarged version of your chosen icon for the component when adding it in the Page Editor. Not ideal, but still sticks with the established convention pretty good.
    • Set it up like this.
      04-09-2013 20-28-44

And that’s pretty much it. There may be additional things to consider when setting up your Component; Rendering Parameters and so on – I’m going to skip that for this post, as it doesn’t lean towards the points I am making here. I know I say that a lot, but hey… this post is going to be more than long enough already.

Implementing the Component

Like a TV chef, I’m going to skip ahead quickly and show you the resulting Sublayout .ASCX. The layout I’ve created does nothing but set up one Placeholder; “content” and include the relevant CSS files. For those of you riding the MVC wave, I’m sure you can adapt.

The .ASCX
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Top Banner.ascx.cs" Inherits="Website.layouts.CorePoint.Top_Banner" %>
<div id="topBanner">
    <sc:Image runat="server" Field="Top Banner Image" ID="sciImage"/>
    <div id="topBannerContent">
        <asp:PlaceHolder runat="server" ID="phHeading">
            <h4><sc:Text runat="server" Field="Top Banner Heading" ID="sctHeading"/></h4>
        </asp:PlaceHolder>
        <sc:Text runat="server" Field="Top Banner Body Text" ID="sctBodyText"/>
    </div>
    <asp:PlaceHolder runat="server" ID="phLink">
        <sc:Link runat="server" Field="Top Banner Link" ID="sclLink">
            <sc:Text runat="server" Field="Top Banner Link Text" ID="sclLinkText"/>
        </sc:Link>
    </asp:PlaceHolder>
</div>

The codebehind is empty, at this point.

Creating a Data Item based on my Component Template

I then create an item, based on my newly created Component Template.

04-09-2013 21-27-47

And to further stress my point that Page Templates have no place at this point, I will just proceed to modify the presentation details of the default /content/home item that ships with Sitecore.

Setting up the Sitecore page

I change the presentation details for the item, to look like this. As mentioned; the Layout only holds the basics – and a placeholder keyed “content”.

04-09-2013 21-31-04

And finally I configure my Top Banner component to use my newly created Content Item as a datasource.

04-09-2013 21-32-58

After all this, I do a quick publish – and this is what I see. If I hadn’t read The Page Template Mistake or John Wests post on how to apply data sources to components, I might be surprised at this point.

04-09-2013 21-38-01

Nothing shows. Your first instinct might be to have a look at the page source. It looks like this.

04-09-2013 21-39-34

So essentially; the component gets rendered ok. There’s just nothing in it.

And this is the crust of the Page Template Mistake. Sitecore does nothing (for you) to respond to your configuration; setting the datasource to your content item. And I do believe this is the first reason many venture down that mistaken road and begin making the Page Template Mistake in the first place. There is no immediately obvious way to get to the datasource, and the standard Sitecore web controls don’t respond to it. So one retorts to hitting the Sitecore.Context.Item, and from here on out your fate is sealed.

Fortunately there’s a better way to approach this. Let’s introduce a bit of codebehind.

Implementing the Component code (basic)
public partial class Top_Banner : UserControl
{
    protected Item _actionItem = null;

    public Item ActionItem
    {
        get
        {
            if ( _actionItem == null )
            {
                var sl = Parent as Sublayout;
                if ( sl != null )
                {
                    if ( !string.IsNullOrEmpty( sl.DataSource ) )
                    {
                        Item datasourceItem = Sitecore.Context.Database.GetItem( sl.DataSource, Sitecore.Context.Language );
                        if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                            _actionItem = datasourceItem;
                    }
                }
            }

            if ( _actionItem == null )
                _actionItem = Sitecore.Context.Item;

            return _actionItem;
        }
    }

    protected void Page_Load( object sender, EventArgs e )
    {
        sctHeading.Item =
            sctBodyText.Item =
            sciImage.Item =
            sclLink.Item =
            sctBodyText.Item = ActionItem;
    }
}

And the result.

04-09-2013 23-42-10

This is more or less Datasource 101. Implement like this, and you are more or less imitating XSL Renderings and how $sc_item is set up to work by default.

Look here’s the thing:

If you do this, and you do it consistently, your solution is already in the top N percent of well implemented Sitecore solutions. Good solutions. DMS enabled solutions. Almost by default.

You can work your way up from here, and I will give a few examples of that. But it starts here. It starts by deciding that what you want to do, is build a good Sitecore solution. You could do nothing more than just this in your solution, and you’d have pretty much all DMS scenarios covered. I really am not kidding.

Just one gotcha; Sitecore 7 expands upon the Datasource concept. Since I am blogging in the context of personal experience and practices I myself have found to be successful – I cannot account for how the above code fits with Sitecore 7. I have no live sites under my belt at this stage that uses Sitecore 7. My initial guess would be; “it’s probably fine” however.

Implementing the code (intermediate)

The next natural step up from here would be to push the ActionItem code to a base class, and make all your Components inherit from here. Quite many of my readers of the previous posts in this series point this out – and until recently this has also been my own sole approach to this problem.

The base class could look like this.

public class BaseSublayout : UserControl
{
    #region :: Action Item ::
    protected Item _actionItem = null;

    public Item ActionItem
    {
        get
        {
            if (_actionItem == null)
            {
                var sl = Parent as Sublayout;
                if (sl != null)
                {
                    if (!string.IsNullOrEmpty(sl.DataSource))
                    {
                        Item datasourceItem = Sitecore.Context.Database.GetItem(sl.DataSource, Sitecore.Context.Language);
                        if (datasourceItem != null && datasourceItem.Versions.GetVersions().Any())
                            _actionItem = datasourceItem;
                    }
                }
            }

            if (_actionItem == null)
                _actionItem = Sitecore.Context.Item;

            return _actionItem;
        }
    }
    #endregion

    protected void ApplyActionItemRecursively()
    {
        var ai = ActionItem;
        foreach ( Control c in Controls )
            RecurseControls( c, ai );
    }

    private void RecurseControls( Control parent, Item actionItem )
    {
        if ( parent.GetType().FullName.StartsWith( "Sitecore.Web.UI.WebControls" ) )
        {
            var itemProp = parent.GetType().GetProperty( "Item" );
            if ( itemProp != null )
                itemProp.SetValue( parent, actionItem );
        }

        foreach( Control c in parent.Controls )
            RecurseControls( c, actionItem );
    }
}

And with this, every one of your components would look like this in their basic form. This is where my claim “this adds no cost to your solution”. I’ll say it again; implementing Components this way carries no significant overhead. You set up this base class once, and that’s it.

public partial class Top_Banner : BaseSublayout
{
    protected void Page_Load( object sender, EventArgs e )
    {
        ApplyActionItemRecursively();
    }
}

All I have left to do, is a slight bit of housekeeping. This is another convention I apply and if you stick to it, I am fairly confident your content editor users are going to love it.

public partial class Top_Banner : BaseSublayout
{
    protected void Page_Load( object sender, EventArgs e )
    {
        ApplyActionItemRecursively();

        if ( string.IsNullOrWhiteSpace( ActionItem[ "Top Banner Heading" ] ) )
            phHeading.Visible = false;

        if ( string.IsNullOrWhiteSpace( ActionItem["Top Banner Link Text"] ) )
            phLink.Visible = false;
    }
}

And that’s it, essentially. The Component is done. It’s well behaved, it can be used in M/V tests – call it “DMS Enabled” if you must. And if all your components are implemented in this manner, your life when creating Page Templates later on will be a heck of a lot easier. Painless is more like it. And it never cost you a dime.

For that, however, you are going to have to wait for the next post in this series.

You can stop reading now :-)

But for those persistent enough to make it this far in an already excessively long post; I’ll demonstrate where I am currently at myself in my pursuits of a mythological “best practice” in this area. I will be brief and post mostly code with minimal commentary. If you’re at this level of Sitecore implementation experience, I’m sure it will make sense.

Implementing the code (advanced)

The problem with the above approach is of course, as many commenters have pointed out. In real life, not all components fit nicely into this pattern. Sitecore themselves sort of indicate this as well; every default XSLT rendering has a $home variable defined (albeit commented out). Sometimes applying “Datasource or Context Item” just isn’t good enough.

Think Headers and Footer Components for instance. While you likely could be implementing a Datasourced Header component on one of your (deep) base templates, for many purposes this just isn’t practical.

Mark Ursino rightly mentions this problem in a comment;

“Global information (e.g. header and footer) cannot really be componentized too well unless you use standard values on a very low level "base page" template to assign the same header and footer data source items to all pages. I typically instead just define a predefined structure in a global area to support the header and footer.”.

Mark, I’m with you here, but I still believe that any component that “breaks out” of the imaginary “bounding box” that is its Component Template is creating an anti pattern in the solution – not unlike how Global Variables do it for traditional structured programming.

And there’s likely many similar scenarios.

Fortunately this can be resolved easily as well – without tweaking much in the code I just presented. AND – and this is important – without starting to make up a “meta CMS in the CMS” by adding global configuration structures and similar. I’ve taken this approach myself, and I always found them to be inhibiting me sooner or later in the lifetime of the solution.

Here’s what I suggest.

Have your components adhere to relevant strategies for resolving the ActionItem. Mostly – what I just lined out above will be fine. For some components, it would be more appropriate to EITHER respond to the Datasource (if set) or retort to $home. For others again; perhaps responding to Datassource (WHATEVER else you do; always always always respect the Datasource if one has been set. Always. Please. Having a “global header” that cannot be datasourced to make a quick micro-site is just a right pain) and retorting to crawling “up the tree” until you find an item that inherits from your Component Template.

It looks like this. I’ve abbreviated slightly. It’s going to be a long paste, so I’ll quit writing now and just let the code do the rest of the talking (mostly).

Until next time :-)

namespace Website.layouts.CorePoint
{
    public abstract class ActionItemStrategy
    {
        public abstract Item Resolve( Control c );
    }

    /// <summary>
    ///     Classic Datasource handling
    /// </summary>
    public class DatasourceOrContextItemStrategy : ActionItemStrategy
    {
        private Language _fallbackLanguage;

        public DatasourceOrContextItemStrategy( Language fallbackLanguage = null )
        {
            _fallbackLanguage = fallbackLanguage;
        }

        public override Item Resolve( Control c )
        {
            var sl = c.Parent as Sublayout;
            if ( sl != null )
            {
                if ( !string.IsNullOrEmpty( sl.DataSource ) )
                {
                    Item datasourceItem = Context.Database.GetItem( sl.DataSource, Context.Language );
                    if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                        return datasourceItem;

                    if ( _fallbackLanguage != null )
                    {
                        datasourceItem = Context.Database.GetItem( sl.DataSource, _fallbackLanguage );
                        if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                            return datasourceItem;
                    }
                }
            }

            return null;
        }
    }

    /// <summary>
    ///     Resolves the ActionItem by datasource and falls back to Site Root.
    /// </summary>
    public class DatasourceOrHomeItemStrategy : ActionItemStrategy
    {
        public override Item Resolve( Control c )
        {
            Item datasourceItem = new DatasourceOrContextItemStrategy().Resolve( c );
            if ( datasourceItem != null )
                return datasourceItem;

            Item home = Context.Database.GetItem( Context.Site.StartPath, Context.Language );
            if ( home.Versions.GetVersions().Any() )
                return home;

            return null;
        }
    }

    public class BaseSublayout : UserControl
    {
        protected Item _actionItem = null;

        public Item ActionItem
        {
            get
            {
                if ( _actionItem == null )
                {
                    _actionItem = GetActionItemStrategy().Resolve( this );
                    if ( _actionItem == null )
                        _actionItem = Sitecore.Context.Item;
                }

                return _actionItem;
            }
        }

        protected virtual ActionItemStrategy GetActionItemStrategy()
        {
            return new DatasourceOrContextItemStrategy();
        }

        protected void ApplyActionItemRecursively()
        {
            Item ai = ActionItem;
            foreach ( Control c in Controls )
                RecurseControls( c, ai );
        }

        private void RecurseControls( Control parent, Item actionItem )
        {
            if ( parent.GetType().FullName.StartsWith( "Sitecore.Web.UI.WebControls" ) )
            {
                PropertyInfo itemProp = parent.GetType().GetProperty( "Item" );
                if ( itemProp != null )
                    itemProp.SetValue( parent, actionItem );
            }

            foreach ( Control c in parent.Controls )
                RecurseControls( c, actionItem );
        }
    }
}

And with this in place, the individual Component implementations could “do nothing” – in which case they would just apply default behaviour. But for some cases, overriding this behaviour is desirable – so we configure these with simple overrides. A few examples.

Site Header Component
protected override ActionItemStrategy GetActionItemStrategy()
{
    return new DatasourceOrHomeItemStrategy();
}
Implementing Language Fallback

Make this your default sublayout, overriding the default I listed above.

protected override ActionItemStrategy GetActionItemStrategy()
{
    return new DatasourceOrContextItemStrategy( Sitecore.Globalization.Language.Parse( "en" ) );
}

Make up your own as you go along. Not too many though – or the point of this whole exercise gets lots completely. I can attest from experience however; just the two first strategies solved the very large majority of my component worries. And I don’t implement any meta-structures any longer to support neither menus, nor headers or footers, or pretty much anything else for that matter.

And the flexibility this approach gives me in setting up any and all Page Templates that my content editors require; is near phenomenal. More on that next time.

Wednesday, August 21, 2013

The page template mistake

How to recognise it and how to avoid it

This blog post is part 2 in a series on “Creating good Sitecore solutions”. You will find part 1; “How do I create a good Sitecore solution?” here.

Getting more, for less. Or even for free.

Having decided to create a good Sitecore solution, or even just “a Sitecore solution”, there is one thing you need to get right that adds more “good Sitecore value” to your solution above all other things you could be doing.

And the best thing about it is; it will (should) not add any costs to your implementation. If the practices lined out here are followed from the start, my own personal experience has shown me that your implementation time is not increased. In fact I would argue, following these guidelines will bring your overall implementation time down more than anything. And from whichever side of the table you are on – buying or selling a Sitecore solution – time will be money.

I will explain this in more detail, as I go along.

The problem with (most) Sitecore implementations.

In my first post in this series, I hinted that a very large majority of Sitecore solutions I come across in may day to day work were, to some extent, not entirely “fit for duty”. While some of the shortcomings can be put down to just this – the solutions were never truly designed to be good Sitecore solutions to begin with; the decision to to so was just plain never made. Most of them have a very fundamental architectural shortcoming in common. And this particular shortcoming – more than anything else – will nothing short of completely rule out pretty much any DMS scenario you can think of. Right then and there – one glitch, if you will, in the way these solutions were architected – and you can forget about the (in my view) most important set of features in Sitecore or possibly any CMS platform on the market today.

Before I go on, and step up high and mighty on my soapbox – let me be the first to admit this. Up until just a few years ago, I was happily designing and implementing Sitecore solutions following these same – faulty, as this post should demonstrate – practices and guidelines.

It wasn’t until around the beginning of 2012 and having just gone through a greenfield Sitecore 6.5 implementation that it dawned on me; the way I was perceiving and approaching basic Sitecore information architecture was just – well plain wrong. I recall asking on LinkedIn “Have you built a site yet, truly "true" to the changes in the 6.5 platform?” (Sitecore MVP group, for those who have access) – asking if anyone else had revisited the way they implemented Sitecore solutions following the release of Sitecore 6.5. It created a bit of debate, but nothing too ground shaking.

I was under the mistaken impression at the time, that it was Sitecore 6.5 and DMS that brought on these changes. Having mulled over this ever since, I now know that I was wrong. I know now that the way one is supposed to be implementing and architecting Sitecore for the solutions to end up “DMS ready” and being well on the way to becoming a “good Sitecore solution” dates back at least as far as Sitecore version 5. It might even be sooner, but I have little to no experience with Sitecore versions pre-dating version 5.

If you are still with me here, I think it’s about time I unveil what I believe to be at the core of the problem, in the way I was designing Sitecore solutions – and the problem in the vast majority of less than ideal Sitecore solutions I come across today.

The problem is: “Page Templates”

Yes indeed. Bear with me, and allow me to explain.

Having worked my way through I don’t know how many Sitecore releases dating as “far” back as Sitecore 5.1.1.12 (the earliest I have on record) and all the way up through to version 7 – it wasn’t until Sitecore 6.5 that Sitecore brought on a truly serious alternative offering to the ever popular “Sitecore Content Editor”. In fact the Sitecore Content Editor is so widely used that most people probably don’t even realise, this is just one content editor interface in Sitecore. To most I would bet; this editor IS “Sitecore”.

A quick re-cap. Sitecore 5 and version 6s prior to 6.5 did offer alternative interfaces. As far as I can tell however, nobody really used them. I practically never came across any implementations were these played any active role. You had to implement for these alternatives specifically (sc:Dot anyone?) and in my personal view they just plain didn’t work very well. In essence you had to do a fair amount of extra (key word here) development effort to support anything but the Sitecore Content Editor. And as I’ve already argued – time equals money – so it doesn’t get done. Only in the rarest of circumstances.

Along came 6.4 and in particular 6.5 – and changed all that. For the first time – at least for me – could one switch to this “new” Sitecore user interface (which is, in fact, not new at all) and see the site one was building become truly interactive. Without doing much if anything at all, to support it. Alright so there is a few things to consider, but I consider these insignificant in the grand scheme of things.

All of a sudden, teaching clients to do their work in the Page Editor became a viable option. And in many (most) cases a very strong alternative to the Sitecore Content Editor. I mean the Sitecore Content Editor is fine, if you’re working on Page Templates – marketing people will get that, and manage fine to go in and alter some headlines, swap out a few pictures and even add a few new pages (based on Page Templates) to the site. Not much more than that however, not in my experience.

The Page Editor, however, allows so much more than that. Following just the standard Sitecore implementation guidelines – the Page Editor allows the content editor to work with the very fabric of the page. Swapping out components, personalising components, M/V testing them with alternating content. And while all of these possibilities are also present in the Sitecore Content Editor, the Page Editor beats it by miles in terms of overall user experience for the average non-developer user.

And here’s the thing. Swapping out components, M/V testing components on a page, personalising components on a page. None of this – none of it – fits into the mindset of a “Page Template”. Your page has become a dynamic entity, something to be shaped and molded into nothing short of the “Perfect personalised user experience for your site visitors” – this is the way of the Digital Marketing Future. We’re going to the Moon and all that ;-)

The fact of the matter is; if you perceive each page on your site as something that fits the static nature of a Sitecore template – keep in mind, these can only be created by developers, and once a template has been set for an item it stays with the item forever. Or at least until you forcibly decide to change it. Also keep in mind, a template for “Page A” will also be the same template for any other pages of the same type as “Page A”. You can’t have the template holding X fields here, and Y fields there. Sitecore just isn’t designed for that (yet, I hope).

To overcome this, Sitecore uses Datasources. I think this was recently dubbed “Related Content” in a recent Sitecore release, but I’m going hardline and stick with the original term. “Feeding” your component with a Datasource is the way you instruct it to “go get your content from this place over here, don’t look at the page you happen to be sitting on”. None of this means anything to the Page Editor – it just shows (and allows edits of) the content from where ever it was sourced – whereas you need to jump around between items in the Sitecore Content Editor to achieve the same (reference: section 4.2.1 of the Content Authors Reference and Cookbook for Sitecore 6.6).

For both personalisation and M/V testing to work – your components must be able to be datasourced. No if’s, no buts'.

And this is it. This just doesn’t happen (much) in most solutions I visit. I, as most of the Sitecore developer community, implement the general term component as an ASP.NET User Control or the up-and-coming MVC alternatives. Sitecore also supports other types of components, most notably the “XSL Rendering” type of component. For a variety of reasons, this component type is being ruled out everywhere – performance reasons, lack of familiarity with the XSLT syntax among the developer base – the reasons are many. Rightfully so, I might add. It’s a relic from a time where Sitecore seemed to be designed on the idea, that the Sitecore data structure should be represented in abstract as one big XML Document – and transformed for multiple purposes by the up and coming XSLT technology. While Sitecore still supports this notion, the product is moving more and more away from this line of thinking.

So. When writing components in ones language of choice – I guess c# is the dominant choice these days, and working with a user base that exclusively accesses Sitecore through one common interface – the Sitecore Content Editor – you set yourself up for The Page Template Mistake.

The Page Template Mistake

While going through all the motions of setting up Page Insert options for your users, you would probably also be considering what fields to present to your users on each of these “pages” they can insert. If you’re doing this well, you will break down your Data Templates into smaller bits, so as to make them easily available for re-use across different Page Templates. So you’ll isolate your “Page Header” and “Sub Heading” fields into one Data Template – and then have some or most of your Page Templates inherit from this one, as well as any other Data Templates that the particular Page Type will support.

As the site evolves you shape and mold your Data Template structure, to make the best use possible of the common fields across pages.

You’ll begin to implement components – like a common “Left Menu” component for example – and have these traverse through your Page Items based on Page Templates – outputting a nice and nested logical representation of your site. The site visitor clicks elements on the menu, and navigates to a new page. The story repeats itself.

Eventually you’re done. The site launches, editors make the last minute changes to headers, round off corners of the images and changes a few icons to the Cornflower Blue. Everyone is happy.

Everyone is happy, that is, until 3 days into the launch and your pesky content editors decides to try out some of this “fancy M/V testing that we’ve heard so much about”.

You’ve just made The Page Template Mistake. Don’t worry though matey, so have I and so have we all.

You will find, that once the content editors start moving stuff around, adding YouTube Video Player Component onto the “Contact Us” page – you’re in trouble. Sure you can go; “oh we’re sorry. We didn’t make it so that this component can work on that page” but really all you’re doing at this stage is making up excuses and adding a healthy dose of CYA. I know I did.

If all your considerations when designing your page and template structure was focused around the Sitecore Content Editor (and it is an EASY trap to fall into – you DO do all of the designing and “architecting” in this very editor) – chances are slim to none that you have all the dynamics in place to allow the kind of flexibility the Page Editor truly inspires.

M/V testing?  “Uhm sure…” (muttered on the phone while desperately scrambling to add a few template Insert Options to the solution and hoping it will work).

Ever been there?

Fortunately there’s an easy way to avoid it. Not an easy fix, mind you, refactoring your solution AFTER the fact is going to be a fairly extensive job. Avoiding this problem however, adds no cost to your solution implementation AND puts you on the road to delivering a “good Sitecore solution”.

The Data Template solution

If you look closely in the Sitecore documentation, you will find the term Data Template everywhere when speaking of content and data structures. In fact I don’t recall anywhere within official Sitecore documentation seeing the term “Page Template” mentioned. I could be wrong though, there is a vast amount of cookbooks dealing with these topics. Here’s a tip:

Don’t think Data Template, think “Component Template”.

Because that’s what you should be doing.

When going through the site designs, part of that process is identifying “Components” that has to be built for the site to be completed. You do this already – regardless of whether you’re thinking in terms of Page Templates or not. Each of these components will have a certain number of Sitecore fields supporting them. It will be the obvious ones; “Image Heading”, “Image”, “Subtitle”, “Citation” and so on – we all know how these look and work. There will (should) also be the more subtle ones like “Banner Rotation Delay”, “Allow Fullscreen” and so on. You won’t necessarily recognise all of these at the get-go, but don’t worry. These can be added as you go along with the implementation. Make sure you do, though. Things like “Banner Rotation Delay” are perfect candidates for M/V testing. Try it, you’ll probably be as surprised as I was about the difference it can make.

This is what should be defining your Component Template. A Component Template for a Component – this makes perfect sense. Name them by convention; a “YouTube Video Template” matching the “YouTube Video” component. This makes sense. To you and to your content editors alike. While configuring each component in Sitecore, make sure you configure the components Datasource Template to point to your corresponding Component Template – and you’re already more than half way on your pursuit of the “good Sitecore solution”.

Forget about Page Templates at this stage. You can do them at the end. At the very end of the project, I’m serious. Keep working your way through components and if you’re fortunate enough, get your team of developers started on implementing them right away. If not, start doing them yourself. Just make sure that the implementation of these components follow one of the most basic of rules:

Make sure the component respects it’s data source.

Mine didn’t. Not until that epiphany I had with Sitecore 6.5. As so many others, I implement my components as a Sitecore “Sublayout” (essentially an ASP.NET User Control) – and I would frequently sport code such as the following (not literally – the example code is ghastly, but am making a different point):

if ( Sitecore.Context.Item[“show in menu”] == “1” )
{
    litMenu.Text += “<li>” + Sitecore.Context.Item[“menu title”] + “</li>
}

Right up there on The Page Template Mistake, page 1, subheading “Sitecore.Context.Item”. Don’t use it. Well don’t use it in general, there are obviously cases where it is perfectly acceptable to go visit Sitecore.Context.Item.

What you need is something to the effect of (pseudocode, this post is already long enough without me diving in to a long technical explanation. I will do a follow-up post with concrete code examples to follow this one, I promise):

IF this_component HAS DEFINED Datasource
    SET $ActionItem TO Datasource
ELSE
    SET $ActionItem TO Sitecore.Context.Item

And then have all the component implementation respect draw its data exclusively from $ActionItem.

That’s all there is to it. Really. And since you’re ignoring Page Templates for now, testing and verification of the implemented components becomes very easy. Developers will be forced to add their components to “blank canvasses” as they go along and Datasource them to their items based on the respective Component Templates.

This is not new. This is not something “clever” I am making up, or a “clever idea I just had”. No my faithful reader – this principle sits at the very foundation of Sitecore presentation architecture. This behaviour has been expected from the very beginning (of Sitecore 5, maybe sooner) from every Component.

This is $sc_item versus $sc_contentitem in your (no longer used) XSLT renderings; one of the first types of components you could implement in Sitecore. Also known as a “Rendering” – a term still being broadly used today to cover most anything used to output content. I prefer the Page Editor term Component.

$sc_item would behave exactly like the pseudocode above.

A rendering can retrieve data from its data source item. The $sc_item variable represents the data source item for an XSL rendering. If the developer does not specify a data source item for a rendering, the default data source item is the context item, and $sc_item and $sc_currentitem are the same item. – Presentation Component XSL Reference section 3.2.1.

And while I have found little to no documentation in Sitecore actually specifically instructing you to be designing Component Templates in the manner I describe, I can tell you this much: If you want to support all the DMS goodness that everyone is talking about these days – this is the first step.

Forget about Page Templates; think Component Templates.

Do this from the start, and your solution will come into existence, ready and waiting to be M/V tested, personalised and whatnot. At no extra cost. Creating your information architecture in this manner from the ground up will add no extra time to your project. In fact I have found that it subtracts slightly from the implementation time.

And on that note, I think it’s time I step down from my soapbox. I will follow-up this post with a more technically to-the-point post explaining and demonstrating how an information architecture can come into place, following these principles. Also a few pointers to how your components can easily adapt these principles and finally; “what DO we do with Page Templates then?”.

Until then.

Tuesday, July 30, 2013

How do I create a good Sitecore solution?

This blog post is part 1 in a series on “Creating good Sitecore solutions”. You will find part 2; “The page template mistakehere.

Having now worked as a Sitecore consultant for well over 8 years – sometimes in regular employment at one of the many Sitecore Partners in Denmark and the UK, but more often as a freelance consultant/contractor for the very same clients – I have been exposed to pretty much all aspects of what it means to create a Sitecore solution.

Sometimes I’m brought in to help a new and upstart Sitecore partner get some of their first Sitecore clients. They usually need help in scoping, defining and estimating the proposed project. Sometimes they keep me on to help in the actual implementation of the site as well – more often I am kept on to help train their existing developer resources in the practices and uses of Sitecore.

Other times – and these days, this is more often the case – I am hired as a Sitecore Architect for a project. In many ways the tasks I perform are the same as what I just mentioned, but the title Architect tends to imply doing all the above, alongside ensuring that whatever implementation eventually ends up getting built; will also fall in line with the almost mythological Best Practices for Sitecore implementations.

I say mythological with some irony, of course. While a lack of documentation used to be a problem, we now have nothing short of 1000s of pages of documentation and “cookbooks” available to us. These cookbooks will describe in detail, all the intricacies of implementing your Renderings, Rules, Templates. How to set up security, how to set up cloud solutions – pretty much how to do everything you’d want to with your Sitecore solution.

And this is it, really. If one was ever to define Sitecore Best Practices, this complete set of cookbooks would be it.  NOT this – The Sitecore Recommended Practices Cookbook. While I would certainly recommend that the practices described in this cookbook be followed, it in no way can be said to hold a complete set of “Best Practices” for a Sitecore solution. There’s so much more to it than that.

There simply is no single “manual” that will tell you everything you need to do. Everything you need to be aware of, everything you need to consider. There is no substitute for experience, as the proverb goes. This certainly holds true here.

And that actually brings me closer to the point I was wanting to make, and has brought me back to the keyboard after such a long absence from blogging. See the thing is – when I first started blogging, it was mostly about technical details. “The little things”. Information on Sitecore was somewhat scarce, and sharing whatever information we learned was the name of the game. With all the information now available, not to mention the probably 100s of bloggers who has taken to the blogosphere – I find myself in need of a new game. Experience. I will start using this blog to write and share some of the information you will not find in cookbooks, other peoples blogs or even John West’s book.

I’ll kick this off by beginning to answer the very question I pose in the title of this post. You will find it is going to take quite many posts to follow, to arrive at any sort of answer – but we have to start somewhere.

To create a good Sitecore solution; you must first decide to create a Sitecore solution.

“What?  That it!?”

No. That’s not all of it, but this is most definitely where you need to start.

See the thing is; as any project I’ve been part of goes through the same motions – the same pattern. Doesn’t really matter if the process in place is Agile or Waterfall. If you have a Scrum Master or a Project Manager (or both).

In the beginning (or as you go along, if you are truly Agile. I have yet to see my first truly Agile Sitecore project implementation); everyone is on about features, design and (usually most importantly) the cost. If you’re in an agency, your agency has to win the bid. If you’re building in-house, the project will still have a cost and will need an approved budget.

Then comes the construction. Developers, designers and whatnot get to work. Here the focus becomes jQuery libraries, lightboxes, valid HTML, performance and of course the actual Sitecore implementation. The perceived necessary stuff from the cookbooks mind you, whatever it takes to make it work.

And if all goes to plan, eventually the “site” (which is usually what a Sitecore project will be – the delivery of a “site” for Company A, or a re-make of a “site” for Company A – and herein lies the problem) will get handed off, go live, start receiving visitors and everyone shakes hands.

I know, I know. I am both simplifying the whole process and adding a bit of irony on top. Bear with me, this post is already turning out to be much longer than it seemed to be in my mind.

My point. The project is about a “site”. Or new features on a “site”. Very very rarely – if ever – does it get discussed, how the end user (the Sitecore end user, not the “site” visitor) will be interacting with the Sitecore solution. One simple – and when you look at it; astonishing – fact, and no-one usually thinks to ask it.

What happens is; the “site” gets built, gets handed off, gets approved – all from looking at the “public face” (if you will) of the “site”. If it ticks all the boxes, “we’re done”.

Sure enough, depending on the actual level of experience (see above) of the team that actually did the scoping and ultimately the Sitecore implementation of the “site” – parts of it will also be content manageable. Not all of it – very rarely – but parts of it.

Is this a good Sitecore solution then?  Well I would argue; “no”. It’s a “site” running on Sitecore and could therefore in the strictest sense be dubbed a “Sitecore solution” (as the customer ordered, and got). But a good one?

At this point, if you don’t really know what a good Sitecore solution should feel like, I would recommend you contact your local Sitecore office and have one of their excellent sales people demonstrate the “Nicam” site for you. But in summary, I would say that a good Sitecore solution should at the very least tick the following boxes:

  • It doesn’t restrict the use of the built-in Sitecore tools
    • The Sitecore Page Editor
    • The Sitecore Debugger
    • The Sitecore Profiler
  • It allows you to use at least the basics of Sitecore functionality – probably the very reasons being why Sitecore was chosen over a competing system to begin with
    • All components on any page can be M/V tested
    • Sitecore Analytics Goals and Failures can be defined for relevant parts of the site
      • Alternatively that these are triggered in the code, hardcoded
    • Editor User usability has been considered
      • Placeholder settings have been set up
      • Insert Options
      • Permissions, if necessary
  • It can run on a single-server environment or scale to multi-server

I mean… The CEO (usually) who ultimately approved the considerable license fee for a Sitecore solution was told by Sitecore sales people; “Sitecore can do all this”. In most cases I have seen, the CEO doesn’t dig deeper into the subject matter – he or she will sign off, and (quite naturally) expect to be getting exactly this. As well as the “site”, mind you.

Less than 5% of all the Sitecore solutions I have seen delivered, would tick all of the above boxes.

Yes. This includes some of “my own” – albeit delivering any Sitecore solution can probably never be put down to just one persons influence.

The “reasons” are many, but the most common one that gets passed around is this. “It would require extra work for us, if we were to expand the “site” with the necessary “stuff” so you can work with it in Page Editor/Set it up for Sitecore Analytics/Configure bespoke security settings”. Extra work in this business means “more money” or at the very least “more time” – none of which any of us has enough of to pass around in this economic climate.

And so it usually ends. From time to time customers will put in tasks like; “We want a split-test set up for our Add To Basket button – how much time will that take/what will it cost?”. Small improvements like that are made over time – everyone is happy. Except – if you’ve read this far, you will once again sense a slight irony behind my words – perhaps me.

Over the posts to follow I will demonstrate how most of these boxes can be ticked, and actually not cost you any more time or the client any more money. Not to any significant degree anyway.

It comes back to experience. It comes back to what can only be read between the lines in the cookbooks and blog-posts. It comes back to first deciding:

“I want to build a Sitecore solution”

And if you get at it from the onset with that attitude, and start considering what that actually means – you are on the right track.

And if you’re in the other end; the person buying the solution. Don’t go “I need my “site” on Sitecore by the end of this year”. Go: “I need this “site” implemented as a proper Sitecore solution. I’ve seen the impressive features of Sitecore and I want to use that platform to improve my business/user experience/conversion rate”.

Decide to build or get a good Sitecore solution, and you’ve at least started with the right mindset.

Saturday, May 05, 2012

Email Confusion - Configuring SMTP options for your Sitecore (Modules)

I’ve been working a lot with the different modules in Sitecore, and it seems everytime I need to send out an email I run into difficulties. The reasons for this are quite numerous.
In web.config we have the default MailServer settings, which are used through-out the system:
      <setting name="MailServer" value="" />
      <setting name="MailServerUserName" value="" />
      <setting name="MailServerPassword" value="" />
      <setting name="MailServerPort" value="25" />
Now.. No statement without exceptions, so firstly: The Email Campaign Manager(ECM) uses its own provider settings – this makes sense, since you might not want to send out 10k+ emails through your regular SMTP provider ;-). So you either use the Sitecore Message Transfer Agent(MTA) though the Sitecore App Center with a subscription, or you setup a local MTA.
Secondly: Web Form For Marketers(WFFM) has it’s own send email action (/sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions/Send Email Message) which by default overrides your MailServer with it’s own "example.host” – not to keen on their choice of default values here, but just remove it and it will default to your web.config settings.
SNAGHTML3d66de[9]

The trouble begins

This is all well and fine, until you have a client that want to use a SMTP service with either SSL or TLS – The default Sitecore send mail method (Sitecore.MainUtil.SendEmail) do not implement SSL. This is curiously handled in both ECM and WFFM, just not in the base Sitecore system.

In ECM, when using a local MTA, you have the option to set the “SMTP.StartTLS”. And in WFFM send mail action, you have some undocumentet settings available (not really a surprise to experienced Sitecore developers ;-)) but add the “enableSSL” attribute in you “send email message” parameters section, and this will ofcourse not enable SSL – it will however enable TLS :-P.You can verify this by sending trough gmail. To make it work you need to send trough port “587”, and not “465” which is for normal SSL encryption.

SNAGHTML5b41f1
This is because Sitecore uses the System.Net.Mail.SmtpClient which states
The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.enablessl.aspx
Now we still have a problem with the rest of Sitecore – Password recorvery, Sitecore Ecormerce Services and so on.. But since Sitecore uses the System.Net.Mail.SmtpClient we then have the option to “enableSsl” trough our web.config file. Just add this entire segment to the bottom of your webconfig file (before the end </configuration> tag)
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network enableSsl="true" />
      </smtp>
    </mailSettings>
  </system.net>
This enables the rest of Sitecore to use a SSL(with TLS) SMTP provider, like gmail, for all email functions. Just set your MailServerSettings to:
      <setting name="MailServer" value="smtp.gmail.com" />
      <setting name="MailServerUserName" value="yourAccount@gmail.com"/>
      <setting name="MailServerPassword" value="yourGmailPassword" />
      <setting name="MailServerPort" value="587" />
And you are good to go. Be aware that you still need to include the <enableSSL>true</enableSSL> tag in WFFM “Send Email Message” or it will specificly set enableSSL to false.
Also Sitecore may include this in a later version, and then you should remove this and use the provided Sitecore settings. This is testet on a Sitecore CMS 6.5.0 rev 111230 with WFFM 2.3.0 rev 120216. using .Net 4 Framework