Invert list selection with Sitecore Powershell

I recently needed to run a script on a block of Sitecore content in invert the selection of a checklist and multilist. As I couldn’t find any example of how to do this at the time, I thought I’d share what I wrote.

#script to update tier
Get-ChildItem -r -Path "master:\content\Home" -Language * | ForEach-Object {
    if ($_.PSobject.Properties.name -match "Tier") {
        [String[]]$tiers = $_.Tier -split "\|"

        $_.Editing.BeginEdit()
        $newtiers = Get-ChildItem 'master:\content\Lookups\Tiers\' | Where-Object { $tiers -notcontains $_.Id }    
        $_.Tier = $newtiers.Id -join "|"
        $_.Editing.EndEdit()
    }
}

Get-ChildItem -r -Path “master:\content\Home” -Language * | ForEach-Object {

This line is getting the child items from the home node in the master db. The -r specified that it should be recursive and the -Language * specifies to include all languages. The results are then piped to a for each loop.

if ($_.PSobject.Properties.name -match “Tier”) {

The field I needed to update was called Tier, as this was included in multiple templates I checked that the object included a field called Tier, rather than checking the template types.

[String[]]$tiers = $_.Tier -split “\|”

List fields in Sitecore get stored as a pipe separated list of the item Id’s for the selected items. In order to do a comparison in Powershell I needed to turn the string back into an array using the split command. Notice the backslash that is needed before the pipe.

$_.Editing.BeginEdit()

To edit an item you need to begin an edit

$newtiers = Get-ChildItem ‘master:\content\Components\Lookups\Tiers\’ | Where-Object { $tiers -notcontains $_.Id }

This is where we get the new list of tiers to set as the selected ones for the item. The Get-ChildItem command is retrieving the original options that could be selected and the where-object statement is then excluding the ones that are in the $tiers array we just made.

$_.Tier = $newtiers.Id -join “|”

To save the new list we need to convert the results of the query into a pipe separated list using a join.

$_.Editing.EndEdit() } }

End the editing to save and close the the if and loop statements.

 

Advertisements

Tracking downloads in Sitecore Experience Analytics

This blog is generally aimed at developers whereas the contents of this post could be categorized as a topic for marketers, but I’ve decided to include it as its likely something a Sitecore dev could get asked about and its also quite useful to know about.

Out the box Sitecore’s Experience Analytics comes with a set of pre-configured reports to give insights into the sites visitors. Previously I blogged about Populating the internal search report in Sitecore which unless done will probably lead to someone asking why it’s blank. Another report which initially won’t show any data is downloads.

AnalyticsBehaviourTab

Located under behavior there is actually now two reports relating to downloads. The Assets report and the Downloads report.

Assets, in Sitecores words – “Describes your marketing assets or content used to attract contacts to your website and increase their engagement with your organization.”

Downloads – “Describes your specific assets, their download activity, and their value.”

These reports are populated by assigning a download event to a piece of media and organizing it as a marketing asset.

Adding a download event to an item

Sitecore doesn’t know which items you think are important to track as downloads so content editors need to mark them manually.

  1. Go to the Media Library

    Media Library

  2. Select the item you want to track as a download

    Select Item

  3. From the ribbon select the Analyze tab and click Attributes

    Click Attributes

  4. Select download form the list of events

    Select Download Attribute

  5. Remember to publish your changes.

Categorizing an Asset

By assigning a marketing asset type to your items they can be grouped for analysis. Such as grouping downloads into categories like white paper and product brochure.

  1. Before you assign a marketing asset to an item you will first need to create your assets. On the Sitecore Launchpad, open the Marketing Control Panel.

    Marketing Control Panel

  2. Go to Assets which is located under Taxonomies.

    Asset

  3. Create your set of Asset Groups and Assets within each. In this example I’ve created a group called Content and Assets called Instruction Manual and Product Brochure.

    Assets

  4. Navigate to the item you want to assign the asset to and select the relevant asset in the marketing asset field.

    Marketing Asset on Item

  5. Publish all your changes.

The result

Now you’ve set a download event and a marketing asset, the assets and downloads reports will start populating.

Going Further

The concept of having to tag every download as a download may seem a little tedious and also prone to being missed in the future. If all your downloads are PDF’s and you want to track all PDF’s as a download, one way to make life easier is to update the standard values on the PDF template item (/sitecore/templates/System/Media/Unversioned/Pdf) so that it always has the attribute of download. The content authors will still need to do the marketing asset categorization, but at least this gives them 1 less thing to do.

Populating the internal search report in Sitecore

Out the box Sitecore ships with a number of reports pre-configured. Some of these will show data without you doing anything. e.g. The pages report will automatically start showing the top entry and exit pages as a page view is something Sitecore can track.

Other’s like the internal search report will just show a message of no data to display, which can be confusing/frustrating for your users. Particularly when they’ve just spent money on a license fee to get great analytics data only to see a blank report.

Internal Search Report

The reason it doesn’t show any information is relatively straight forward. Sitecore doesn’t know how your site search is going to work and therefore it can’t do the data capture part of the process. That part of the process however is actually quite simple to do.

Sitecore has a set of page events that can be registered in the analytics tracker. Some of these like Page Visited will be handled by Sitecore. In this instance the one we are interested in is Search and will we have to register it manually.

Search Event

To register the search event use some code like this (note, there is a constant that references the item id of the search event). The query parameter should be populated with the search term the user entered.

using Sitecore.Analytics;
using Sitecore.Analytics.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using SitecoreItemIds;

namespace SitecoreServices
{
    public class SiteSearch
    {
        public static void TrackSiteSearch(Item pageEventItem, string query)
        {
            Assert.ArgumentNotNull(pageEventItem, nameof(pageEventItem));
            Assert.IsNotNull(pageEventItem, $"Cannot find page event: {pageEventItem}");

            if (Tracker.IsActive)
            {
                var pageEventData = new PageEventData("Search", ContentItemIds.Search)
                {
                    ItemId = pageEventItem.ID.ToGuid(),
                    Data = query,
                    DataKey = query,
                    Text = query
                };
                var interaction = Tracker.Current.Session.Interaction;
                if (interaction != null)
                {
                    interaction.CurrentPage.Register(pageEventData);
                }
            }
        }
    }
}

Now after triggering the code to be called a few times, your internal search report should start to be populated like this.

Internal Search Report Populated

Optimize the Rich Text Editor in Sitecore

When it comes to building a Sitecore site your first thought probably isn’t that you are going to need to make any setting updates or customization’s to the rich text editor. After all when you learn about building a site its mostly focused around creating components to add and remove from pages, but there are a couple of things that will greatly enhance your content editors experience.

Configure the toolbars

Out the box Sitecore ships with 4 toolbar configurations. These are defined in the core db here:

  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Default
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Full
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text IDE
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Medium

The “Rich Text Default” toolbar

Default Toolbar

The “Rich Text Full” toolbar

Full Toolbar

The “Rich Text IDE” toolbar

IDE Toolbar

The “Rich Text Medium” toolbar

Medium Toolbar

As the name suggests, by default your content editors will see the default toolbar that contains a very limited number of options. This may in-fact be to limited and you need to offer the content editors one of the toolbar’s with more options. Equally, the full toolbar may give to many options such as font’s and you would want to offer a more restricted set of options.

Setting a toolbar on a field

You can set a toolbar on each individual field by specifying the path in the template fields source field. This is particularly useful when a field needs specific options, such as a text area that should allow a user to configure bold, italics and links but shouldn’t ever contain an image.

Setting toolbar in on an individual field

Updating the default toolbar for a rich text field

When you want to change the toolbar for all rich text fields, a better option is to update which toolbar is used by default. You can do this with a patch config file.


<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="HtmlEditor.DefaultProfile" value="/sitecore/system/Settings/Html Editor Profiles/Rich Text Full" />
    </settings>
  </sitecore>
</configuration>

Updating the rich text editor css

A second way of customizing the rich text editor that you should consider is to make changes to the css file that the editor uses. By default this will use a css file called default.css that you will find in the root of the site. You can see this being referenced form a config setting if you look at the showconfig.aspx page.

<!--  WEB SITE STYLESHEET
    CSS file for HTML content of Sitecore database.
    The file pointed to by WebStylesheet setting is automatically included in Html and Rich Text fields.
    By using it, you can make the content of HTML fields look the same as the actual Web Site
-->
<setting name="WebStylesheet" value="/default.css" />

You can change this to use a different css file using a patch config file as follows:


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="WebStylesheet">
        <patch:attribute name="value">/rich-text-editor.css</patch:attribute>
      </setting>
    </settings>
  </sitecore>
</configuration>

Now you may be wondering why you would want to do this, after all Sitecore offers an experience editor mode that will show the entire webpage as it will appear to visitors and also offers inline editing. However some aspects of a page can be better achieved using css styles rather than new components or new fields and content editor will need both an easy was to apply these style and a visual way to see that they have been applied, irrespective of if they are using the experience editor or the content editor.

For example, in this section of a blog post from Scott Hanselman he has highlighted some text as an aside which can easily be achieved in a rich text editor by applying a css class.

Hanselman Blog Aside

The first step to enabling this in Sitecore is to make sure you’re using a toolbar that allows the user to select css classes (that’s any but the default).

Next by creating a stylesheet that just contains the relevant style to be applied, the content editor can now select this in the css drop down;

.aside {
    border-left: 2px solid #e2842c;
    background-color: #f7f7f7;
    padding: 5px;
    margin: 5px;
    display: block;
}

CSS drop down

The preview will now also give visual feedback indicating what this is going to look like. It doesn’t have to look exactly like the webpage will, just enough for the content editor to understand.

Rich Text Editor

 

Sitecore Rendering Datasource Restrictions

Datasources on Sitecore Renderings are the basis for content authors to combine a variety of components to form a page, without the need for all the fields to exist in the context item. They also form the underpinnings of switching out content based on personalization rules.

To make life easier for content authors there are two properties which should always be set; Datasource Template and Datasource Location.

Datasource Template

The datasource template field is fairly straightforward to understand. It specifies what type of template is compatible with a rendering.

If the content editor try’s to select an incorrect template they will see an error message like this and the ok button will be disabled:

Incorrect template type

The template reference can point to either the final template that an instance of which will be created, or a template that had been inherited. So if you structure your templates using base template like I describe in my article on How I structure Sitecore Templates then you can reference the base template and anything including it will become available.

However there is a fundamental flaw in linking to a base template. As well as restricting the template that can be selected, specifying the template type also enables the ability to create new content, which will create it as the form of the template specified. So only link to the templates you want your editors to create.

Datasource Location

The datasource location property (as the name suggest) enables you to restrict where in the content tree items can be selected from (or new content created).

Simply specify the folder the content should be placed in and the rest of the content tree will now be hidden from content authors.

Datasource Location Fixed Path

Multi-site solutions

If your solution contains more than one website this may cause a problem as you likely want to be able to restrict certain content to certain sites and may additionally have a global content folder.

Datasource Location Multiple Folders

The first solution to this is to add multiple path’s separated by a pipe.

Datasource Location Multiple Folders Config

This will enable multiple folders to be shown to the user, but it wont enable any sort of restriction.

The second option is to add an xpath query find the relevant folder. This can also be used in conjunction with the static path by being pipe separated as in the last example.

A query like this:

Datasource Location XPath


/sitecore/content/Shared Components/Shared Hero Banners|query:./ancestor-or-self::*[@@templatename='Site']/Components/*[@@templatename='Hero Banners']

Will produce the desired output like this:

Datasource Location XPath Result

Here you can see the shared hero banners folder is available as is the specific hero banner folder for the current site, but not the hero banner folder from the other site.

Using template source restrictions in Sitecore

The source field on a template definition is a great and easy way to enhance your content editors experience.

With fields types such as a tree list, this can be used to restrict the content tree to the section that is relevant. e.g.

Adding a source property like this:

Source Restriction

Will change how a tree list displays from this:

Unrestricted Tree List

To this:

Restricted Tree List

Multi-Site Solutions

The source field however is far more powerful than just pasting in a fixed path to an item. Rather than a static path you can use xpath to make the results based on a query, such as restricting options on a droplink by template type.

In a multi-site solution this is particularly useful, by restricting the options to the site that your content item is on.

With a fixed path the best we could do in the above example would be to set the restriction to the nearest folder that could access both, resulting in a restriction like this:

Fixed restriction showing both sites

While this makes some improvement for the user, but not hugely and they can still select content from the wrong site.

By using an xpath query that utilizes the ancestor-or-self function with a template name, the restriction will dynamically be based on navigating up the content tree from the current item until the template is found and then showing items from it or in this example going back down to the home item.


query:ancestor-or-self::*[@@templatename='Site']/Home

Resulting in an output like the original example, but dynamically changing to be the correct items for where the current content item is located:

Treelist with dynamic restriction

Creating a WFFM Save action with Field Mappings

The Sitecore Web Form for Marketers module offers content editors a flexible way to create data capture forms and then trigger certain actions to occur on submission. There’s a whole host of save action options out the box, such as sending an email, enrolling the user in an engagement plan or updating some user details.

However one save action that is often required is the ability to send the data onto a CRM system so that it can get to the people that need to act on it, rather than staying in Sitecore with the content editors. To do this your best option is to create a custom save action that can send on the information.

Creating a Save Action in Sitecore

Save actions in Sitecore are configured under /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions. Here you can see all the standard ones that come out the box and add your own.

Right click Save Actions and insert a new Save Action. You will need to fill out the Assembly and Class fields so that Sitecore knows which bit of code to execute (details on creating this bit below).

Custom Save Action Sitecore Item

Adding Field Mappings

To really make your save action usable you will want to allow the content editor to map the fields on their form with the ones in the CRM, rather than relying on them both having the same name and hard coding the expected WFFM field names in your save action logic.

On your Save Action Item in Sitecore their are 2 fields to fill out to enable the editor in WFFM (Editor and QueryString). Luckily Sitecore provide a mapping editor out the box so there’s very little effort involved here.

Within the Editor filed add the value:

control:Forms.MappingFields

And within the querystring field, add your list of fields in the format fields=FieldName|FieldDisplayText

fields=FirstName|First Name,LastName|Last Name,EmailAddress|Email Address,CompanyName|Company Name

 

Custom Save Action Field Mappings

When the content editor now adds the save action to their form they will now be able to select a form field for each of these fields.

Custom Save Action Select Fields

Creating the Save Action in code

To create the save action you will need a class that inherits from either ISaveAction or WffmSaveAction. I’ve used WffmSaveAction as it already has some of the interface implemented for you.

The field list you added to the Querystring property of the save action in Sitecore will need to be added as public properties to your class. Sitecore will then populate each of these with the ID the field gets mapped to or null if it has no mapping.

Then all that’s left is to add an Execute method to populate your CRM’s model with the data coming in through the adaptedFields parameter and send it onto your CRM.


using Sitecore.Data;
using Sitecore.WFFM.Abstractions.Actions;
using Sitecore.WFFM.Actions.Base;
using System;

namespace MyProject.Forms
{
    public class SendFormToCrmSaveAction : WffmSaveAction
    {
        public string EmailAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string CompanyName { get; set; }

        public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data)
        {
            // Map values from adapted fields into enquiry model
            IEnquiry enquiry = new Enquiry();

            enquiry.Email = GetValue(this.EmailAddress, adaptedFields);
            enquiry.FirstName = GetValue(this.FirstName, adaptedFields);
            enquiry.LastName = GetValue(this.LastName, adaptedFields);
            enquiry.CompanyName = GetValue(this.CompanyName, adaptedFields);

            // Add logic to send data for CRM here
        }

        /// <summary>
        /// Get Value from field list data for a given form field id, or return null if not found
        /// </summary>

        /// <param name="formFieldId"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        private string GetValue(string formFieldId, AdaptedResultList fields)
        {
            if (string.IsNullOrWhiteSpace(formFieldId))
            {
                return null;
            }
            if (fields == null || fields.GetEntryByID(formFieldId) == null)
            {
                return null;
            }
                return fields.GetValueByFieldID(formFieldId);
            }
        }
    }
}

How I structure Sitecore Templates

Templates are the building blocks for a Sitecore installation, they’re amazingly flexible and with capabilities such as inheritance you can produce an elegant architecture, or alternatively a complete mess. Here’s how I like to structure things:

Base Templates

BaseTemplatesFirst off I have a folder of base templates. These are the building blocks for all the fields that will end up in a component data source or an actual page via inheritance. By setting them up as a base template we can re-use the same field definition for things like headings, but more importantly it keeps them focused on a specific purpose rather including details of the entire eventual item.

One additional rule I have for base templates is that they should only contain one data section within them. This in turn helps keep them focused on a specific purpose.

Page Templates

PageTemplatesNext we have pages. You guessed it, a page template is what a content editor will create an instance of when they make a page. It’s responsibility is to bring together default presentation details, the set of fields on the page and insert options for the pages beneath it.

All fields are inherited from base templates and standard values are used to define the defaults for the page.

Additionally to make the CMS experience as easy as possible for the content editors an icon should be set so that a page type can be visually identifiable.

Component Templates

ComponentTemplatesA component template is the equivalent of a page template but for data sources.

Like page templates all the fields are inherited from base templates and standard values are used to define the defaults for the page. An icon should also be set to make content types easily identifiable by content editors.

Folder Templates

FolderTemplatesFolder templates are often overlooked but they are an essential part of creating a decent user experience.

Folder templates are created to define the insert options for components and site settings rather than having them set on the site content tree.

Where relevant a folder template should also include itself as one of the insert options so that content editors can organise their content into sub-folders.

Parameter Templates

ParameterTemplatesWhen a component needs some config to customise its look and feel that is not content, it can be better to use Rendering Parameters rather than a data source.

Site Setting Templates

SettingsTemplateA Site configuration template is useful to contain various global settings for a site. This could include things such as the Site Logo, Google Analytics account details etc. Settings should be segmented into logical sections that have been defined in Base Templates and then inherited.

It can also be useful to separate some settings into their own template item depending on the scenario of what the setting is for.

Group Into Folders

With each these template types created, you’ll end up with a tree structure that looks something like this.

AllTemplates

Data Source vs Rendering Parameters

Control Properties

On the face of it being able to specify Rendering Parameters, or a Data Source on a control achieves a very similar goal. You want to componentise your page and not fill up your page type item with fields for specific renderings. Everything should be isolated in it’s own little compartment.

Linking a rendering control to a Data Source does this by moving all your data to a completely separate item, that can be re-used over multiple pages and even swapped out to do personalization or A/B testing.

Equally, using Rendering Parameters does this just as well. Just like a Data Source, you can create a template for the fields that need to be entered, and the data is kept in the same place that a link to a Data Source would be specified.

But what should I use?

The easiest way I can describe it is by asking, are you storing content or something else?

If the answer is content then you most likely want a data source. Alternatively, if it’s something else like some config for a filter, or a background colour you will most likely want a rendering parameter (but there could be exceptions).

Data Sources

Data Sources have some distinct advantages over a Rendering Parameter including:

  • Data can be edited in the Experience Editor inline in your page
  • Language versions are very easy to understand by content editors
  • Easily used for personalization and testing
  • Can be reused on as many controls as you like

These things all make a Data Source a perfect option for anything content related. Without them you loose some big features related to content and ease of use. There are times non-content is also a good option. e.g. A hero banner on a page could be used across multiple pages and as well a reusing the text, if a background colour is also customizable you would want to be re-using that too.

Rendering Parameters

Likewise Rendering Parameters also have there benefits:

  • Doesn’t create an extra item to publish. You just have to publish the page your editing, not the related data source
  • Easy to access in the control properties of the item your looking at, without having to find the related data source

These features make Rendering Parameters ideal for the non-content config of a control and removes non-content fields from your item templates. The thing to be aware of though is you can’t easily do A/B testing or personalization with a rendering parameter, so while it’s nice for your items to only contain content, that might not be the only thing that’s being tested.

How about both?

There is also nothing to stop you using a Rendering Parameter and a Data Source at the same time.

You could have a situation when a Data Source is being used to populated the content on multiple different controls. Each control may have some additional config needed, such as text colour or text size. Keeping this data in the data source might become problematic as on one rendering your text may need to be black, whereas on another it may need to be white. By moving these fields to Rendering Parameters, you keep the benefit of a shared Data Source for content, while the Rendering Parameter takes care of the presentation config.

Sitecore html cache not clearing on publish

So you’ve got separate content management and content delivery servers, but when you publish the change is only visible on the content management box.

A likely cause is that you’ve enabled some caching but haven’t updated the config files to clear the cache on your content delivery server.

Sitecores config files contain a list of handlers for what should happen when the event publish:end and publish:end:remote are triggered. Publish end is for the content management server, whereas publish end remote is for your delivery servers. The handler we’re interested in is Sitecore.Publishing.HtmlCacheClearer which contains a list of sites to have the cache’s cleared on.

By default this will contain one entry for website, the default name given to your site in the sites config when you install sitecore. However you will have changed this if your solution supports multiple sites, or if you changed it as part of some future planning to support multiple sites. If your site is missing, just add it to the live (via a patch file of course)

<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">
    <site>SiteOne</site>
    <site>SiteTwo</site>
    <site>SiteThree</site>
  </sites>
 </handler>
</event>
<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end:remote">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">
   <site>SiteOne</site>
   <site>SiteTwo</site>
   <site>SiteThree</site>
  </sites>
 </handler>
</event>

Note: in the sample above I have removed all other handlers to simplify the example. You should not remove these from your solution.

For more info on cache clearing and optimising it, see John Wests blog series on the subject here https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/sitecore-output-cache-clearing-optimization-1-8-introduction-john-west-sitecore-blog