Category Archives: Sitecore

Add Page Views column to the table on Sitecore Analytics Reports

On many pages of the Sitecore Analytics dashboard, there is a table of visit data.

This by default is sorted by page views descending, but there is no page views column! The Visits column is actually the number of visits where at least one page view hit the page in question.

We were asked to add Page Views to this table, and it turned out to be incredibly easy.

In the Core database, go to /Sitecore/client/Applications/ExperienceAnalytics/Common/System/ListControl and you’ll see all the headings from the above table are items under this one:

 

Simply duplicate the Visits item and change the header to “Page views” and data field to “pageViews” as per the above screenshot.

Hey presto:

Also worth pointing out you can set the default sort option here under the relevant ExperienceAnalyticsListControl Parameters item (see my previous post for more detail on customising the Analytics pages):

 

 

Deploying Sitecore Unicorn Items to Azure Web App using VSTS Build and Release

For years we have been using Unicorn to manage and deploy our developer-owned Sitecore items using TeamCity. Nowadays, we have moved to using VSTS for source code, build and release management, and Microsoft Azure for web app hosting. We struggled to set up a process akin to our TeamCity deployment process and Darren Guy’s epic blog series only covers Octopus Deploy.

I won’t go into setting up Unicorn as this is covered in the documentation. I will assume you have got it saving serialized files into source control and just outline the solution we have used to deploy the items.

We decided to put the Unicorn files into /App_Data/Unicorn so it is beneath the Webroot so can be deployed to, but protected from the public.

1. Configure the build to include Unicorn files

We used a Copy Files step to copy the Unicorn folder from source control into the artefact staging directory. This means the files are available at Release time. We’re copying it into a new folder “UnicornWWW” in the location under the website path that we want to deploy the items to (App_Data/Unicorn).

We also zip this folder up into a Unicorn.zip which contains the path within the website inside the zip, and delete the temporary folder as we don’t need it anymore.

Now the UnicornWWW.zip is a build artefact available at release time. You can check by going to the completed build summary page and checking the Artefacts tab, where the file should be listed.

2. Deploy the Unicorn files

This was tricky as we want to not only deploy the new files but also delete any old ones that have been removed from source control. We already had an Azure App Service Deploy step to deploy our web deploy package to the web app. What we did was add a post deployment script to this step which removes the Unicorn folder:


Then we have a follow up deployment which deploys the UnicornWWW.zip directly to the web app. As it has the App_Data/Unicorn folder inside it, the Unicorn files are deployed to the right place and the previous version have been deleted beforehand.

I believe it should be possible to do a manual msdeploy call inside a Powershell script where you could target a subfolder and do ‘sync’ to delete existing files, much like we do with TeamCity, but we haven’t got that working quite yet as not sure how the publish credentials would be taken out of the service principal setup that connects VSTS and Azure – it “just works” when you use the Azure App Service Deploy task so for now this is what we are sticking with.

3. Sync the Unicorn files

First we need a copy of the Unicorn Powershell API scripts available to the release agent. To do this we go back to the build and add a step to copy the Unicorn Tools PSAPI folder from the nuget package location into the build artefact folder:


We then use a Powershell step which runs on the Release agent, which triggers Unicorn sync using the Unicorn Powershell API. This is based on the sample.ps1 from the PSAPI folder. Here we specify the environment URL + /unicorn.aspx and the shared secret that is configured as per Unicorn.UI.config.


The URL and secret can be made environment variables and then you have a fully automated deployment of Unicorn items to your Azure web app environment!

Customising Sitecore Experience Analytics Dashboard

We had a request to customise the default Experience Analytics dashboard on a Sitecore 8.1 site. With a little guidance from Sitecore we have been able to do this easily without development, but it is a bit of a convoluted process so I thought I would outline it here.

If possible, get your site live with Analytics configured correctly and capturing data well before you start looking at customising it, as you can then browse around the default analytics pages and see the real data that is captured. You can then give an analyst access and ask them what changes would be useful.

The default dashboard looks a little like this, on a site that hasn’t had any Analytics customisation done:

All the blocks apart from are ‘by value’ which means there is no data because no profiles / personas / experience scoring has been configured. Therefore, our analyst asked if the dashboard could be changed to include more common analytics like you might find on a Google Analytics dashboard.

  • Total Visits (line chart)
  • Top Referring Site (bar graph)
  • Top Entry Pages (bar graph)
  • Pageviews + Pageview/Visit (line chart)
  • Top pages (bar chart)
  • Top pages over time (line chart)
  • Top 10 pages (table)

These are all graphs that she found in other Analytics report pages, so all we had to do is figure out how to remove the existing charts from the dashboard and copy these from the other pages, creating a new dashboard layout.

The most relevant Sitecore documentation discusses how to create a new report page with a single chart. Using this and a bit of Sitecore knowledge you can figure out how to edit an existing complex dashboard.

The analytics reports structure is stored as Sitecore items in the core database. You can view it by using Sitecore Desktop (link from the Sitecore launchpad) and switch to Core DB using the link at the bottom right:

Then open Content Editor and browse to /sitecore/client/Applications/ExperienceAnalytics/Dashboard

You can see that beneath Dashboard are all the report folders (Audience, Behaviour, etc – which are just common Folders) and report pages (Overview, Devices, etc – using template /sitecore/client/Speak/Templates/Pages/Speak-DashboardPage)

Each report page has a PageSettings folder (template = /sitecore/client/Speak/Templates/Pages/PageSettings) that contains an item underneath it for every chart on the page. These items allow you to set the chart title and any other settings such as which metrics / dimensions to use on the chart.

Review the Layout Details for any page with multiple charts and you can see it is made up of a series of Rows and Columns which define the page layout, and renderings for each chart.

Click Edit and you can see the placeholder IDs used – now you can see how the page is put together. RowPanels are rendered one above the other (in Main.Content placeholder) and each RowPanel automatically defines a placeholder “RowPanel X.Content” where X is the row number. Then ColumnPanels are inserted into the RowPanel placeholders to set up however many columns you want to break that row into. In this example, one full width row, then two 50/50 rows.

The chart renderings themselves are inserted into the ColumnPanels using autogenerated placeholders based on the row and column number e.g. “ColumnPanel 3.2.Content” means this rendering will be shown in row 3 column 2.

To edit this becomes more interesting because you can’t simply edit this in Sitecore – Edit gives you a server error, and Change gives you an empty list of renderings:

So based on the Sitecore article we have to switch to Sitecore Rocks which is able to edit these. Install and connect to the Sitecore instance, then expand Core database to the same location. Select a report page, Right-click, Tasks, Design Layout:

Now you can edit the configuration of rows/columns by moving/adding/removing RowPanel and ColumnPanels, editing the Placeholder of each. Note that each ColumnPanel has a ‘GridColumns’ field set to 12 for full width, 6 for half width, 4 for 1/3 width, etc. Each RowPanel seems to be used for a single Row, not floating multiple charts into it.

The charts themselves use one of a number of Renderings all starting with ‘ExperienceAnalytics’ – you can copy/paste these using right click options from one page’s layout to another, or Add Rendering to pick one to add from scratch:

Each chart needs to have its Datasource set to a PageSettings child item using the matching parameters template:

Easiest is to find and copy the existing settings item from another report page, under the dashboard page, and then edit the datasource of the chart rendering item to use the new settings item.

Save regularly and reload the dashboard page, to see your changes. Here is my modified dashboard page where I have different charts:

How to shrink a Sitecore database

We had some databases that were 25 gb each due to some large media items.

To shrink the database, it is not as simple as deleting the large items.

After you have identified and deleted any unnecessary items from Sitecore, do this on each database (or publish the parent section) and then Empty the Sitecore recycle bin (in each database, via the Sitecore Desktop menu).

Then you have to run the Sitecore Clean Up Database wizard. This will remove the orphaned items from the DB. Finally you can shrink the databases and the space will actually be reclaimed.

How to migrate users and passwords between Sitecore instances

If you ever package users from one Sitecore instance to another you will find that upon install the users are disabled and the passwords need to be reset.

What if you were moving them from one version to another and need to keep the same passwords?

Fear not, just run this SQL script. It will update the passwords of all matching usernames to the original passwords, and enable the accounts. The databases must be on the same instance.

/******

 SELECT Upgraded Core DB in SQL Studio.

 In script below, Replace Old_Core with name of old DB

 First run the SELECT only to see what it's going to do, then run the update script.

 ******/
SELECT TOP 1000
      m.[UserId],
      om.userid,
      m.[Password],
      om.password,
      m.[PasswordSalt],
      om.passwordsalt,
      u.username,
     ou.username,
      m.comment,
     m.islockedout,
     om.islockedout,
     m.isapproved,
     om.isapproved
  FROM [aspnet_Membership] m
  inner join [aspnet_Users] u ON m.UserID = u.UserID
  inner join Old_Core.dbo.aspnet_Users ou ON ou.username = u.username
  inner join Old_Core.dbo.aspnet_Membership om ON ou.userid = om.userid

   UPDATE [aspnet_Membership]
  SET
  --comment = ou.username,    -- TEST!
  Password = om.Password,
  PasswordSalt = om.PasswordSalt,
  IsLockedOut = om.IsLockedOut,
  IsApproved = om.IsApproved
  FROM [aspnet_Membership] m
  inner join [aspnet_Users] u ON m.UserID = u.UserID
  inner join Old_Core.dbo.aspnet_Users ou ON ou.username = u.username
  inner join Old_Core.dbo.aspnet_Membership om ON ou.userid = om.userid

Sitecore 8 Federated Experience Manager

I recently posted a short introduction to the Sitecore FXM on the e3 blog, below is a more detailed version!

One new feature in Sitecore 8 is the Federated Experience Manager (FXM). This is a brand new tool designed to allow you to apply Sitecore’s marketing features to existing non-Sitecore sites. This would be ideal for clients who are investing in the Sitecore platform but also have legacy sites which aren’t being redeveloped into Sitecore. For example, associated WordPress blogs, Drupal communities, even flat microsites could contribute to a user’s Sitecore Experience profile and affect personalisation across all these sites. I’ve had a chance to experiment with this tool and this is what I found.

This new tool is an option in the new Sitecore Launchpad. It presents you with a list of sites that you have added already, along with number of visits that have been tracked through the FXM:

After creating a federated site they show in this list. For testing purposes I have added the e3 test website as a federated site. You need to enter the site’s domain and then paste some tracking script onto every page of the target site. The details of my federated site are as follows:

Now comes the fun bit. Clicking on “Open in Experience Editor” brings up a new version of the Experience Editor, geared towards being able to edit federated sites. In my instance, here you can see the e3 homepage showing up within the experience editor of my fresh Sitecore 8 instance:

From this visual editor you are able to do various things such as:

  • Attach Sitecore functionality to links / button clicks (such as triggering a goal)
  • Assign goals/campaigns/events to trigger when certain page(s) are viewed
  • Add Sitecore placeholders at any point within the existing site, to inject new content or replace existing content

As a basic example, we could trigger a goal when a user views a case study and then display a personalised block on the homepage to highlight a particular case study, such as this one about Unicef Launchpad.

The first thing you must do is add a Page Filter. This is how Sitecore will target your personalisation to decide which page(s) it affects. Here we create a filter to match all case study pages, and assign a custom “Viewed Case Study” goal I made earlier:


Next, for the personalisation on the Homepage, I can click “Add Placeholder” and then click on a part of the page. This selects the component I have clicked and gives a choice of adding before or after that component:

In this case I have chosen “Add before” as I want to add a new component in above “Our Latest Work”. Once the placeholder is added, I can add any existing Sitecore layout in the new placeholder (for example any design component you already have built for your Sitecore site), and display the desired content. The federated site may need updated CSS to correctly display design elements from the Sitecore site, otherwise they might appear unstyled. Once I’ve finished adding the new component it looks like this:

By default this new content will display all the time. The final step is to apply some personalisation to the new block. To do this, I can select the block and choose Edit personalisation from the floating toolbar:

The following personalisation settings will show the custom content if the user has viewed a case study, otherwise hide the component. You could add multiple conditions in here to display different content depending on the user’s activity.

Once all this is done and published, I can browse to the target site and it appears as normal. If I browse to any case study and then back to the homepage, I can see the new component has been injected into the page’s content:

There are many possibilities in terms of the personalisation logic you could apply, and this new ability to apply marketing features to external sites really adds a new dimension to Sitecore’s experience platform.

Automated Site Setup Scripts (Sitecore / Umbraco)

We wanted a simple way to get a new environment set up on a developer machine, but without the hassle of Virtual Machines.

Enter, Microsoft’s appcmd.

This lets you manipulate IIS7 via command line calls. There is lots of documentation on the IIS site but it takes a while to figure out which commands you need to do everything to set up a site. So I’ve put together a selection of the useful commands below in a sample site setup script.

We save these as batch files (.bat) and put them in a shared folder.

Prerequisites:

  • You work on Windows using IIS7
  • (if Sitecore) You have all relevant Sitecore installation zips in a shared network folder
  • (if Umbraco) You use Nuget package to distribute Umbraco CMS (or you could do the zip thing)
  • You run sites locally with custom host name, using a shared DB
  • All team members setup sites in the same folder path e.g. c:\work
  • You have admin rights on the local machine

Sample setup script:

Put this in a .bat file and save in a shared folder. Keep as many steps as required, and replace the relevant placeholders. To run, right click Run as Administrator.

@ECHO OFF

ECHO *** MUST BE RUN AS ADMIN - IF NOT PLEASE CLOSE AND RUN AGAIN, OTHERWISE: ***
PAUSE

ECHO *** CHECKING OUT FROM SVN ***

IF not exist c:\PATH_TO_TRUNK svn checkout -q https://SVN_PATH_TO_TRUNK c:\PATH_TO_TRUNK

ECHO *** EXTRACTING SITECORE ***

"C:\Program Files\7-Zip\7z" x -y "PATH_TO_SITECORE_ZIPS\Sitecore 7.0 rev. 140120.zip" -oc:\PATH_TO_TRUNK "Sitecore 7.0 rev. 140120\Data" "Sitecore 7.0 rev. 140120\Website"

ECHO *** RENAMING SITECORE ***

rename "c:\PATH_TO_TRUNK\Sitecore 7.0 rev. 140120" www

ECHO *** COPY LICENSE ***

copy PATH_TO_LICENSE\license.xml c:\PATH_TO_TRUNK\www\Data

ECHO *** CREATING APP POOL ***

C:\Windows\System32\inetsrv\appcmd add apppool /name:"APP_POOL_NAME" -managedRuntimeVersion:v4.0

ECHO *** CREATING SITE ***

C:\Windows\System32\inetsrv\appcmd add site /name:"APP_POOL_NAME" /bindings:http://site.localhost:80 /physicalPath:"c:\PATH_TO_TRUNK\www\Website" -applicationDefaults.applicationPool:APP_POOL_NAME

ECHO *** CREATING VIRTUAL DIRECTORIES ***

C:\Windows\System32\inetsrv\appcmd add vdir /app.name:"APP_POOL_NAME/" /path:/siteAssets /physicalPath:c:\PATH_TO_TRUNK\siteAssets

ECHO *** ADDING TO HOSTS FILE ***

find /c "	site.localhost" c:\windows\system32\drivers\etc\hosts
if %errorlevel% equ 1 goto notfound
echo Already there
goto done
:notfound
ECHO 127.0.0.1	site.localhost >> c:\windows\system32\drivers\etc\hosts
goto done
:done
  
ECHO *** BUILDING SOLUTION ***

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe c:\PATH_TO_TRUNK\src\Site.sln /verbosity:quiet

ECHO *** OPENING SITE ***

start http://site.localhost/

PAUSE

Hope that’s helpful to someone!

How to hide the Set associated content button in Sitecore

Sitecore Page Editor provides a Set associated content button in the floating toolbar around each component:

set-associated-content

This allows you to set the Data source for the component.

The selection can be restricted by Template or Location (in the Sitecore tree) by setting the page editor options on the component:

page-editor-options

If you have some components that require a data source and others that do not, it can be confusing for editors because the Set associated content button is always visible. The only way to see if it is intended to be used in a particular instance is by clicking it and seeing whether the developer has set the restrictions – if not then it allows you to pick any item from the whole site tree and you realise you probably aren’t meant to use it.

I thought it would be nice to only show the button if the Template restriction has been set, so the editor doesn’t try to use it when it isn’t intended.

To do this, I created a custom class to replace the built-in SetDatasource command:

using Sitecore.Data.Items;
using Sitecore.Shell.Applications.WebEdit.Commands;
using Sitecore.Shell.Framework.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Training.Utilities.BaseCore.Commands
{
    public class SetDatasourceIfTemplateSet : SetDatasource
    {
        public override CommandState QueryState(CommandContext context)
        {
            Sitecore.Data.ID renderingId;
            if (Sitecore.Data.ID.TryParse(context.Parameters["renderingId"], out renderingId))
            {
                Item renderingItem = Sitecore.Context.Database.GetItem(renderingId);
                if (string.IsNullOrEmpty(renderingItem["Datasource Template"]))
                {
                    return CommandState.Hidden;
                }
            }
            return base.QueryState(context);
        }
    }
}

Then in the /App_Config/Commands.config file, replace the webedit:setdatasource command type with our custom version:

<command name="webedit:setdatasource" type="Training.Utilities.BaseCore.Commands.SetDatasourceIfTemplateSet,Training.Utilities"/>

Then the button will only show up if a Datasource Template has been assigned.

How to get a spreadsheet of Sitecore template usage

I wanted to get an overview of all the templates in a Sitecore project along with how many times each has been used.

I thought there might be some marketplace module for doing this but couldn’t find one, nor could I find a suitable report in the ASR module.

So I wrote a little aspx script to write this out, hopefully it will be useful to someone:

<%@ Page Language="C#" AutoEventWireup="true" %><%

Response.ContentType = "text/csv";
var db = Sitecore.Data.Database.GetDatabase("master");
var templates = db.GetItem("/sitecore/templates/User Defined");
foreach (var template in templates.Axes.GetDescendants())
{
	if (template.TemplateName == "Template")
	{
		var usage = Sitecore.Globals.LinkDatabase.GetReferrerCount(template);

		if (template.Children["__Standard Values"] != null)
			usage--;

		Response.Write(template.ID + "," + template.Paths.Path + "," + usage + "," + Environment.NewLine);
	}
}

%>

Style up an sc:link field for Sitecore Page Editor

If you have a normal Link field which you render using an <sc:link /> control then you can select the link in a nice friendly way when editing through the Page Editor.

However if you have a custom css class to style your link then you might expect the link field to use that style in edit mode. Here’s an example link and the HTML we want it to render:

<a class="arrow-link" href="/">Read more</a>

However, when converted into an <sc:Link CssClass=”arrow-link” /> this is what Sitecore renders during edit mode, when you haven’t yet set a link:

Note that this doesn’t include an <a> tag at all. However, it does include the CSS class, albeit encoded into the sc_parameters attribute of the <code> element.

To make it styled-up using the same CSS class I added to the CSS an additional selector for the style:

So now as well as the .arrow-link class applying to actual .arrow-links, it also applies itself to Sitecore’s scTextWrapper span (which is where the [No text in field] is rendered). Now, before you fill it in, it looks like this:

Nice. This really helps if you have lots of similar-looking fields (e.g. Text, Links, etc) all below each other, as the editor can see which is meant for which. I would like to see if anyone has a nicer way of doing this by extending Sitecore, but I thought doing it in CSS would be a simple workaround.