Home » Commands (Page 3)

Category Archives: Commands

Copy Sitecore Item Field Values To Your Clipboard as JSON

With all the exciting things happening around json recently — the Sitecore Item Web API (check out this awesome presentation on the Sitecore Item Web API) and pasting JSON As classes in ASP.NET and Web Tools 2012.2 RC — I’ve been plagued by json on the brain.

For the past few weeks, I’ve been thinking about building a Sitecore client command that copies fields values from a Sitecore item into a string of json via the clipboard, though have been struggling with whether such a command has any utility.

Tonight, I decided to build such a command. Here is what I came up with.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Configuration;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Data.Templates;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.Sheer;

using Sitecore.Sandbox.Utilities.Serialization.Base;
using Sitecore.Sandbox.Utilities.Serialization;

namespace Sitecore.Sandbox.Commands
{
    public class CopyItemAsJsonToClipboard : ClipboardCommand
    {
        private const bool AlertIfClipboardCopyNotSupported = true;
        private static readonly CopyToClipboard CopyToClipboard = new CopyToClipboard();

        private Template _StandardTemplate;
        private Template StandardTemplate 
        {
            get
            {
                if(_StandardTemplate == null)
                {
                    _StandardTemplate = GetStandardTemplate();
                }

                return _StandardTemplate;
            }
        }

        private static Template GetStandardTemplate()
        {
            return TemplateManager.GetTemplate(Settings.DefaultBaseTemplate, Context.ContentDatabase);
        }
        
        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");

            if (IsSupported(AlertIfClipboardCopyNotSupported))
            {
                IEnumerable<Field> fields = GetNonStandardTemplateFields(commandContext);
                CopyToClipBoard(GetFieldsAsJson(fields));
            }
        }

        private static string GetFieldsAsJson(IEnumerable<Field> fields)
        {
            Assert.ArgumentNotNull(fields, "fields");
            IList<string> list = new List<string>();
            foreach(Field field in fields)
            {
                list.Add(string.Format("\"{0}\":\"{1}\"", field.Name, EscapeNewlines(field.Value)));
            }

            return string.Concat("{", string.Join(",", list), "}");
        }

        private static string EscapeNewlines(string value)
        {
            Assert.ArgumentNotNull(value, "value");
            return ReplaceSubstrings
            (
                value,
                new KeyValuePair<string, string>[] 
                { 
                    new KeyValuePair<string, string>("\n", "\\n"),
                    new KeyValuePair<string, string>("\r", "\\r")
                }
            );
        }

        private static string ReplaceSubstrings(string source, IEnumerable<KeyValuePair<string, string>> oldNewValues)
        {
            Assert.ArgumentNotNull(source, "source");
            Assert.ArgumentNotNull(oldNewValues, "oldNewValues");
            foreach (KeyValuePair<string, string> oldNewValue in oldNewValues)
            {
                source = source.Replace(oldNewValue.Key, oldNewValue.Value);
            }

            return source;
        }

        private IEnumerable<Field> GetNonStandardTemplateFields(CommandContext commandContext)
        {
            return GetNonStandardTemplateFields(GetItemWithAllFields(commandContext));
        }

        private IEnumerable<Field> GetNonStandardTemplateFields(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            return GetNonStandardTemplateFields(item.Fields);
        }

        private IEnumerable<Field> GetNonStandardTemplateFields(IEnumerable<Field> fields)
        {
            Assert.ArgumentNotNull(fields, "fields");
            return fields.Where(field => !IsStandardTemplateField(field));
        }

        private static void CopyToClipBoard(string json)
        {
            if(!string.IsNullOrEmpty(json))
            {
                SheerResponse.Eval(GetCopyToClipBoardJavascript(json));
            }
        }

        private static string GetCopyToClipBoardJavascript(string json)
        {
            Assert.ArgumentNotNullOrEmpty(json, "json");
            return string.Format("window.clipboardData.setData('Text', '{0}')", json);
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Item item = GetItemWithAllFields(commandContext);
            bool makeEnabled = CopyToClipboard.QueryState(commandContext) == CommandState.Enabled && HasFields(item);

            if (makeEnabled)
            {
                return CommandState.Enabled;
            }

            return CommandState.Disabled;
        }

        private static bool HasFields(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            return item.Fields.Any();
        }

        private static Item GetItemWithAllFields(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Item item = GetItem(commandContext);

            if (item != null)
            {
                item.Fields.ReadAll();
            }
            
            return item;
        }

        public bool IsStandardTemplateField(Field field)
        {
            Assert.ArgumentNotNull(StandardTemplate, "StandardTemplate");
            return StandardTemplate.ContainsField(field.ID);
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            Assert.ArgumentCondition(commandContext.Items.Any(), "commandContext.Items", "There must be at least one item in the array!");
            return commandContext.Items.FirstOrDefault();
        }
    }
}

The command above iterates over all fields on the selected item — not including those that are defined in the Standard Template — and builds a string of json containing field names accompanied by their values.

I found this article by John West to be extremely helpful in writing the code above to determine if a field belongs to the Standard Template — this is used when leaving out these fields in our resulting json string.

Further, the command is only enabled when the selected item has fields coupled with the CommandState returned by a call to the QueryState() method on an instance of Sitecore.Shell.Framework.Commands.CopyToClipboard — this object’s QueryState() method checks things we care about, and I wanted to leverage its logic.

I then mapped the command above in a patch include file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <sitecore>
    <commands>
      <command name="item:copyitemasjsontoclipboard" type="Sitecore.Sandbox.Commands.CopyItemAsJsonToClipboard,Sitecore.Sandbox"/>
    </commands>
  </sitecore>
</configuration>

Now that we have our command, let’s create an item context menu option for it:

copy-as-json-context-menu

Let’s see this thing in action.

I created an item for testing:

jsonify-me-item

I right-clicked on our new item to launch its context menu, and then clicked on the ‘Copy As Json’ menu option:

copy-as-json-context-menu-jsonify

I pasted the following from my clipboard into Notepad++:

json-string

If you can think how this, or something similar could be useful, please drop a comment.

Make a Difference by Comparing Sitecore Items Across Different Databases

The other day I pondered whether anyone had ever built a tool in the Sitecore client to compare field values for the same item across different databases.

Instead of researching whether someone had built such a tool — bad, bad, bad Mike — I decided to build something to do just that — well, really leverage existing code used by Sitecore “out of the box”.

I thought it would be great if I could harness code used by the versions Diff tool — a tool that allows users to visually ascertain differences in fields of an item across different versions in the same database:

compare-version

After digging around in Sitecore.Kernel.dll, I discovered I could reuse some logic from the versions Diff tool to accomplish this, and what follows showcases the fruit yielded from that research.

The first thing I built was a class — along with its interface — to return a collection of databases where an item resides:

using System.Collections.Generic;

namespace Sitecore.Sandbox.Utilities.Gatherers.Base
{
    public interface IDatabasesGatherer
    {
        IEnumerable<Sitecore.Data.Database> Gather();
    }
}
using System.Collections.Generic;
using System.Linq;

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Sandbox.Utilities.Gatherers.Base;
using Sitecore.Configuration;

namespace Sitecore.Sandbox.Utilities.Gatherers
{
    public class ItemInDatabasesGatherer : IDatabasesGatherer
    {
        private ID ID { get; set; }

        private ItemInDatabasesGatherer(string id)
            : this(MainUtil.GetID(id))
        {
        }

        private ItemInDatabasesGatherer(ID id)
        {
            SetID(id);
        }

        private void SetID(ID id)
        {
            AssertID(id);
            ID = id;
        }

        public IEnumerable<Sitecore.Data.Database> Gather()
        {
            return GetAllDatabases().Where(database => DoesDatabaseContainItemByID(database, ID));
        }

        private static IEnumerable<Sitecore.Data.Database> GetAllDatabases()
        {
            return Factory.GetDatabases();
        }

        private bool DoesDatabaseContainItemByID(Sitecore.Data.Database database, ID id)
        {
            return GetItem(database, id) != null;
        }

        private static Item GetItem(Sitecore.Data.Database database, ID id)
        {
            Assert.ArgumentNotNull(database, "database");
            AssertID(id);
            return database.GetItem(id);
        }

        private static void AssertID(ID id)
        {
            Assert.ArgumentCondition(!ID.IsNullOrEmpty(id), "id", "ID must be set!");
        }

        public static IDatabasesGatherer CreateNewItemInDatabasesGatherer(string id)
        {
            return new ItemInDatabasesGatherer(id);
        }
        
        public static IDatabasesGatherer CreateNewItemInDatabasesGatherer(ID id)
        {
            return new ItemInDatabasesGatherer(id);
        }
    }
}

I then copied the xml from the versions Diff dialog — this lives in /sitecore/shell/Applications/Dialogs/Diff/Diff.xml — and replaced the versions Combobox dropdowns with my own for showing Sitecore database names:

<?xml version="1.0" encoding="utf-8" ?> 
<control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense">
  <ItemDiff>
    <FormDialog Icon="Applications/16x16/window_view.png" Header="Database Compare" Text="Compare the same item in different databases. The differences are highlighted." CancelButton="false">
      <CodeBeside Type="Sitecore.Sandbox.Shell.Applications.Dialogs.Diff.ItemDiff,Sitecore.Sandbox"/>
      <link href="/sitecore/shell/Applications/Dialogs/Diff/Diff.css" rel="stylesheet"/>
      <Stylesheet>
        .ie #GridContainer {
          padding: 4px;
        }
        
        .ff #GridContainer &gt; * {
          padding: 4px;
        }
        
        .ff .scToolbutton, .ff .scToolbutton_Down, .ff .scToolbutton_Hover, .ff .scToolbutton_Down_Hover {
          height: 20px;
          float: left;
        }
      </Stylesheet>
      <AutoToolbar DataSource="/sitecore/content/Applications/Dialogs/Diff/Toolbar" def:placeholder="Toolbar"/>
      <GridPanel Columns="2" Width="100%" Height="100%" GridPanel.Height="100%">
		<Combobox ID="DatabaseOneDropdown" Width="100%" GridPanel.Width="50%" GridPanel.Style="padding:0px 4px 4px 0px" Change="#"/>
        <Combobox ID="DatabaseTwoDropdown" Width="100%" GridPanel.Width="50%" GridPanel.Style="padding:0px 0px 4px 0px" Change="#"/>
        <Scrollbox ID="GridContainer" Padding="" Background="white" GridPanel.ColSpan="2" GridPanel.Height="100%">
          <GridPanel ID="Grid" Width="100%" CellPadding="0" Fixed="true"></GridPanel>  
        </Scrollbox>
      </GridPanel>
    </FormDialog>
  </ItemDiff>
</control>

I saved the above xml in /sitecore/shell/Applications/Dialogs/ItemDiff/ItemDiff.xml.

With the help of the code-beside of the versions Diff tool — this lives in Sitecore.Shell.Applications.Dialogs.Diff.DiffForm — I built the code-beside for the xml control above:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.shell.Applications.Dialogs.Diff;
using Sitecore.Text.Diff.View;
using Sitecore.Web;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.WebControls;

using Sitecore.Sandbox.Utilities.Gatherers.Base;
using Sitecore.Sandbox.Utilities.Gatherers;

namespace Sitecore.Sandbox.Shell.Applications.Dialogs.Diff
{
    public class ItemDiff : BaseForm
    {
        private const string IDKey = "id";
        private const string OneColumnViewRegistry = "OneColumn";
        private const string TwoColumnViewRegistry = "TwoColumn";
        private const string ViewRegistryKey = "/Current_User/ItemDatabaseDiff/View";

        protected Button Cancel;
        protected GridPanel Grid;
        protected Button OK;
        protected Combobox DatabaseOneDropdown;
        protected Combobox DatabaseTwoDropdown;

        private ID _ID;
        private ID ID
        {
            get
            {
                if (ID.IsNullOrEmpty(_ID))
                {
                    _ID = GetID();
                }

                return _ID;
            }
        }

        private Database _DatabaseOne;
        private Database DatabaseOne
        {
            get
            {
                if (_DatabaseOne == null)
                {
                    _DatabaseOne = GetDatabaseOne();
                }

                return _DatabaseOne;
            }
        }

        private Database _DatabaseTwo;
        private Database DatabaseTwo
        {
            get
            {
                if (_DatabaseTwo == null)
                {
                    _DatabaseTwo = GetDatabaseTwo();
                }

                return _DatabaseTwo;
            }
        }

        private ID GetID()
        {
            return MainUtil.GetID(GetServerPropertySetIfApplicable(IDKey, IDKey), ID.Null);
        }

        private Database GetDatabaseOne()
        {
            return GetDatabase(DatabaseOneDropdown.SelectedItem.Value);
        }

        private Database GetDatabaseTwo()
        {
            return GetDatabase(DatabaseTwoDropdown.SelectedItem.Value);
        }

        private static Database GetDatabase(string databaseName)
        {
            if(!string.IsNullOrEmpty(databaseName))
            {
                return Factory.GetDatabase(databaseName);
            }

            return null;
        }

        private static string GetServerPropertySetIfApplicable(string serverPropertyKey, string queryStringName, string defaultValue = null)
        {
            Assert.ArgumentNotNullOrEmpty(serverPropertyKey, "serverPropertyKey");
            string value = GetServerProperty(serverPropertyKey);

            if(!string.IsNullOrEmpty(value))
            {
                return value;
            }

            SetServerProperty(serverPropertyKey, GetQueryString(queryStringName, defaultValue));
            return GetServerProperty(serverPropertyKey);
        }

        private static string GetServerProperty(string key)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            return GetServerProperty<string>(key);
        }
        
        private static T GetServerProperty<T>(string key) where T : class
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            return Context.ClientPage.ServerProperties[key] as T;
        }

        private static void SetServerProperty(string key, object value)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            Context.ClientPage.ServerProperties[key] = value;
        }

        private static string GetQueryString(string name, string defaultValue = null)
        {
            Assert.ArgumentNotNullOrEmpty(name, "name");
            if(!string.IsNullOrEmpty(defaultValue))
            {
                return WebUtil.GetQueryString(name, defaultValue);
            }

            return WebUtil.GetQueryString(name);
        }

        private void Compare()
        {
            Compare(GetDiffView(), Grid, GetItemOne(), GetItemTwo());
        }

        private static void Compare(DiffView diffView, GridPanel gridPanel, Item itemOne, Item itemTwo)
        {
            Assert.ArgumentNotNull(diffView, "diffView");
            Assert.ArgumentNotNull(gridPanel, "gridPanel");
            Assert.ArgumentNotNull(itemOne, "itemOne");
            Assert.ArgumentNotNull(itemTwo, "itemTwo");
            diffView.Compare(gridPanel, itemOne, itemTwo, string.Empty);
        }

        private static DiffView GetDiffView()
        {
            if (IsOneColumnSelected())
            {
                return new OneColumnDiffView();
            }

            return new TwoCoumnsDiffView();
        }

        private Item GetItemOne()
        {
            Assert.IsNotNull(DatabaseOne, "DatabaseOne must be set!");
            return DatabaseOne.Items[ID];
        }

        private Item GetItemTwo()
        {
            Assert.IsNotNull(DatabaseOne, "DatabaseTwo must be set!");
            return DatabaseTwo.Items[ID];
        }

        private static void OnCancel(object sender, EventArgs e)
        {
            Assert.ArgumentNotNull(sender, "sender");
            Assert.ArgumentNotNull(e, "e");
            Context.ClientPage.ClientResponse.CloseWindow();
        }

        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");
            base.OnLoad(e);

            OK.OnClick += new EventHandler(OnOK);
            Cancel.OnClick += new EventHandler(OnCancel);

            DatabaseOneDropdown.OnChange += new EventHandler(OnUpdate);
            DatabaseTwoDropdown.OnChange += new EventHandler(OnUpdate);
        }

        private static void OnOK(object sender, EventArgs e)
        {
            Assert.ArgumentNotNull(sender, "sender");
            Assert.ArgumentNotNull(e, "e");
            Context.ClientPage.ClientResponse.CloseWindow();
        }

        protected override void OnPreRender(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");
            base.OnPreRender(e);

            if (!Context.ClientPage.IsEvent)
            {
                PopuplateDatabaseDropdowns();
                Compare();
                UpdateButtons();
            }
        }

        private void PopuplateDatabaseDropdowns()
        {
            IDatabasesGatherer IDatabasesGatherer = ItemInDatabasesGatherer.CreateNewItemInDatabasesGatherer(ID);
            PopuplateDatabaseDropdowns(IDatabasesGatherer.Gather());
        }

        private void PopuplateDatabaseDropdowns(IEnumerable<Database> databases)
        {
            PopuplateDatabaseDropdown(DatabaseOneDropdown, databases, Context.ContentDatabase);
            PopuplateDatabaseDropdown(DatabaseTwoDropdown, databases, Context.ContentDatabase);
        }

        private static void PopuplateDatabaseDropdown(Combobox databaseDropdown, IEnumerable<Database> databases, Database selectedDatabase)
        {
            Assert.ArgumentNotNull(databaseDropdown, "databaseDropdown");
            Assert.ArgumentNotNull(databases, "databases");

            foreach (Database database in databases)
            {
                databaseDropdown.Controls.Add
                (
                    new ListItem 
                    { 
                        ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("ListItem"), 
                        Header = database.Name,
                        Value = database.Name,
                        Selected = string.Equals(database.Name, selectedDatabase.Name)
                    }
                );
            }
        }

        private void OnUpdate(object sender, EventArgs e)
        {
            Assert.ArgumentNotNull(sender, "sender");
            Assert.ArgumentNotNull(e, "e");
            Refresh();
        }

        private void Refresh()
        {
            Grid.Controls.Clear();
            Compare();
            Context.ClientPage.ClientResponse.SetOuterHtml("Grid", Grid);
        }

        protected void ShowOneColumn()
        {
            SetRegistryString(ViewRegistryKey, OneColumnViewRegistry);
            UpdateButtons();
            Refresh();
        }

        protected void ShowTwoColumns()
        {
            SetRegistryString(ViewRegistryKey, TwoColumnViewRegistry);
            UpdateButtons();
            Refresh();
        }

        private static void UpdateButtons()
        {
            bool isOneColumnSelected = IsOneColumnSelected();
            SetToolButtonDown("OneColumn", isOneColumnSelected);
            SetToolButtonDown("TwoColumn", !isOneColumnSelected);
        }

        private static bool IsOneColumnSelected()
        {
            return string.Equals(GetRegistryString(ViewRegistryKey, OneColumnViewRegistry), OneColumnViewRegistry);
        }

        private static void SetToolButtonDown(string controlID, bool isDown)
        {
            Assert.ArgumentNotNullOrEmpty(controlID, "controlID");
            Toolbutton toolbutton = FindClientPageControl<Toolbutton>(controlID);
            toolbutton.Down = isDown;
        }

        private static T FindClientPageControl<T>(string controlID) where T : System.Web.UI.Control
        {
            Assert.ArgumentNotNullOrEmpty(controlID, "controlID");
            T control = Context.ClientPage.FindControl(controlID) as T;
            Assert.IsNotNull(control, typeof(T));
            return control;
        }

        private static string GetRegistryString(string key, string defaultValue = null)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");

            if(!string.IsNullOrEmpty(defaultValue))
            {
                return Sitecore.Web.UI.HtmlControls.Registry.GetString(key, defaultValue);
            }

            return Sitecore.Web.UI.HtmlControls.Registry.GetString(key);
        }

        private static void SetRegistryString(string key, string value)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            Sitecore.Web.UI.HtmlControls.Registry.SetString(key, value);
        }
    }
}

The code-beside file above populates the two database dropdowns with the names of the databases where the Item is found, and selects the current content database on both dropdowns when the dialog is first launched.

Users have the ability to toggle between one and two column layouts — just as is offered by the versions Diff tool — and can compare field values on the item across any database where the item is found — the true magic occurs in the instance of the Sitecore.Text.Diff.View.DiffView class.

Now that we have a dialog form, we need a way to launch it:

using System;
using System.Collections.Generic;
using System.Linq;

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Text;
using Sitecore.Web.UI.Sheer;

using Sitecore.Sandbox.Utilities.Gatherers.Base;
using Sitecore.Sandbox.Utilities.Gatherers;

namespace Sitecore.Sandbox.Commands
{
    public class LaunchDatabaseCompare : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            SheerResponse.CheckModified(false);
            SheerResponse.ShowModalDialog(GetDialogUrl(commandContext));
        }

        private static string GetDialogUrl(CommandContext commandContext)
        {
            return GetDialogUrl(GetItem(commandContext).ID);
        }

        private static string GetDialogUrl(ID id)
        {
            Assert.ArgumentCondition(!ID.IsNullOrEmpty(id), "id", "ID must be set!");
            UrlString urlString = new UrlString(UIUtil.GetUri("control:ItemDiff"));
            urlString.Append("id", id.ToString());
            return urlString.ToString();
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            IDatabasesGatherer databasesGatherer = ItemInDatabasesGatherer.CreateNewItemInDatabasesGatherer(GetItem(commandContext).ID);

            if (databasesGatherer.Gather().Count() > 1)
            {
                return CommandState.Enabled;
            }

            return CommandState.Disabled;
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            return commandContext.Items.FirstOrDefault();
        }
    }
}

The above command launches our ItemDiff dialog, and passes the ID of the selected item to it.

If the item is only found in one database — this will be the current content database — the command is disabled. What would be the point of comparing the item in the same database?

I then registered this command in a patch include configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <sitecore>
    <commands>
      <command name="item:launchdatabasecompare" type="Sitecore.Sandbox.Commands.LaunchDatabaseCompare,Sitecore.Sandbox"/>
    </commands>
  </sitecore>
</configuration>

Now that we have our command ready to go, we need to lock and load this command in the Sitecore client. I added a button for our new command in the Operations chunk under the Home ribbon:

database-compare-chunk-button-new

Time for some fun.

I created a new item for testing:

database-compare-new-item

I published this item, and made some changes to it:

database-compare-changed-item-in-master

I clicked the Database Compare button to launch our dialog form:

database-compare-launched-dialog

As expected, we see differences in this item across the master and web databases:

database-compare-one-column-comparison

Here are those differences in the two column layout:

database-compare-two-column-comparison

One thing I might consider adding in the future is supporting comparisons of different versions of items across databases. The above solution is limited in only allowing users to compare the latest version of the Item in each database.

If you can think of anything else that could be added to this to make it better, please drop a comment.

Where Is This Field Defined? Add ‘Goto Template’ Links for Fields in the Sitecore Content Editor

About a month ago, I read this answer on Stack Overflow by Sitecore MVP Dan Solovay, and thought to myself “what could I do with a custom EditorFormatter that might be useful?”

Today, I came up with an idea that might be useful, especially when working with many levels of nested base templates: having a ‘Goto Template’ link — or button depending on your naming preference, although I will refer to these as links throughout this post since they are hyperlinks — for each field that, when clicked, will bring you to the Sitecore template where the field is defined.

I first defined a class to manage the display state of our ‘Goto Template’ links in the Content Editor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Web.UI.HtmlControls;

namespace Sitecore.Sandbox.Utilities.ClientSettings
{
    public class GotoTemplateLinksSettings
    {
        private const string RegistrySettingKey = "/Current_User/Content Editor/Goto Template Links";
        private const string RegistrySettingOnValue = "on";

        private static volatile GotoTemplateLinksSettings current;
        private static object lockObject = new Object();

        public static GotoTemplateLinksSettings Current
        {
            get
            {
                if (current == null)
                {
                    lock (lockObject)
                    {
                        if (current == null)
                            current = new GotoTemplateLinksSettings();
                    }
                }

                return current;
            }
        }

        private GotoTemplateLinksSettings()
        {
        }

        public bool IsOn()
        {
            return Registry.GetString(RegistrySettingKey) == RegistrySettingOnValue;
        }

        public void TurnOn()
        {
            Registry.SetString(RegistrySettingKey, RegistrySettingOnValue);
        }

        public void TurnOff()
        {
            Registry.SetString(RegistrySettingKey, string.Empty);
        }
    }
}

I decided to make the above class be a Singleton — there should only be one central place where the display state of our links is toggled.

I created a subclass of Sitecore.Shell.Applications.ContentEditor.EditorFormatter, and overrode the RenderField(Control, Editor.Field, bool) method to embed additional logic to render a ‘Goto Template’ link for each field in the Content Editor:

using System.Web.UI;

using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;

using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Shell.Applications.ContentManager;

using Sitecore.Sandbox.Utilities.ClientSettings;

namespace Sitecore.Sandbox.Shell.Applications.ContentEditor
{
    public class GotoTemplateEditorFormatter : EditorFormatter
    {
        public override void RenderField(Control parent, Editor.Field field, bool readOnly)
        {
            Assert.ArgumentNotNull(parent, "parent");
            Assert.ArgumentNotNull(field, "field");
            Field itemField = field.ItemField;
            Item fieldType = GetFieldType(itemField);

            if (fieldType != null)
            {
                if (!itemField.CanWrite)
                {
                    readOnly = true;
                }

                RenderMarkerBegin(parent, field.ControlID);
                RenderMenuButtons(parent, field, fieldType, readOnly);
                RenderLabel(parent, field, fieldType, readOnly);
                AddGotoTemplateLinkIfCanView(parent, field);
                RenderField(parent, field, fieldType, readOnly);
                RenderMarkerEnd(parent);
            }
        }

        public void AddGotoTemplateLinkIfCanView(Control parent, Editor.Field field)
        {
            if (CanViewGotoTemplateLink())
            {
                AddGotoTemplateLink(parent, field);
            }
        }

        private static bool CanViewGotoTemplateLink()
        {
            return IsGotoTemplateLinksOn();
        }

        private static bool IsGotoTemplateLinksOn()
        {
            return GotoTemplateLinksSettings.Current.IsOn();
        }

        public void AddGotoTemplateLink(Control parent, Editor.Field field)
        {
            Assert.ArgumentNotNull(parent, "parent");
            Assert.ArgumentNotNull(field, "field");
            AddLiteralControl(parent, CreateGotoTemplateLink(field));
        }

        private static string CreateGotoTemplateLink(Editor.Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            return string.Format("<a title=\"Navigate to the template where this field is defined.\" style=\"float: right;position:absolute;margin-top:-20px;right:15px;\" href=\"#\" onclick=\"{0}\">{1}</a>", CreateGotoTemplateJavascript(field), CreateGotoTemplateLinkText());
        }

        private static string CreateGotoTemplateJavascript(Editor.Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            return string.Format("javascript:scForm.postRequest('', '', '','item:load(id={0})');return false;", field.TemplateField.Template.ID);
        }

        private static string CreateGotoTemplateLinkText()
        {
            return "<img style=\"border: 0;\" src=\"/~/icon/Applications/16x16/information2.png\" width=\"16\" height=\"16\" />";
        }
    }
}

‘Goto Template’ links are only rendered to the Sitecore Client when the display state for showing them is turned on.

Plus, each ‘Goto Template’ link is locked and loaded to invoke the item load command to navigate to the template item where the field is defined.

As highlighted by Dan in his Stack Overflow answer above, I created a new Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor pipeline processor, and hooked in an instance of the GotoTemplateEditorFormatter class defined above:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Diagnostics;

using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor;

namespace Sitecore.Sandbox.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor
{
    public class RenderStandardContentEditor
    {
        public void Process(RenderContentEditorArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            args.EditorFormatter = CreateNewGotoTemplateEditorFormatter(args);
            args.EditorFormatter.RenderSections(args.Parent, args.Sections, args.ReadOnly);
        }

        private static EditorFormatter CreateNewGotoTemplateEditorFormatter(RenderContentEditorArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.EditorFormatter, "args.EditorFormatter");
            return new GotoTemplateEditorFormatter 
            { 
                Arguments = args.EditorFormatter.Arguments, 
                IsFieldEditor = args.EditorFormatter.IsFieldEditor 
            };
        }
    }
}

Now we need a way to toggle the display state of our ‘Goto Template’ links. I decided to create a command to turn this state on and off:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.HtmlControls;

using Sitecore.Sandbox.Utilities.ClientSettings;

namespace Sitecore.Sandbox.Commands
{
    public class ToggleGotoTemplateLinks : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            ToggleGotoTemplateLinksOn();
            Refresh(commandContext);
        }

        private static void ToggleGotoTemplateLinksOn()
        {
            GotoTemplateLinksSettings gotoTemplateLinksSettings = GotoTemplateLinksSettings.Current;

            if (!gotoTemplateLinksSettings.IsOn())
            {
                gotoTemplateLinksSettings.TurnOn();
            }
            else
            {
                gotoTemplateLinksSettings.TurnOff();
            }
        }

        private static void Refresh(CommandContext commandContext)
        {
            Refresh(GetItem(commandContext));
        }

        private static void Refresh(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            Context.ClientPage.ClientResponse.Timer(string.Format("item:load(id={0})", item.ID), 1);
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            return commandContext.Items.FirstOrDefault();
        }

        public override CommandState QueryState(CommandContext context)
        {
            if (!GotoTemplateLinksSettings.Current.IsOn())
            {
                return CommandState.Enabled;
            }

            return CommandState.Down;
        }
    }
}

I registered the pipeline processor defined above coupled with the toggle command in a patch include configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <commands>
      <command name="contenteditor:togglegototemplatelinks" type="Sitecore.Sandbox.Commands.ToggleGotoTemplateLinks, Sitecore.Sandbox"/>
    </commands>
    <pipelines>
      <renderContentEditor>
        <processor 
            patch:instead="*[@type='Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderStandardContentEditor, Sitecore.Client']" 
            type="Sitecore.Sandbox.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderStandardContentEditor, Sitecore.Sandbox"/>
      </renderContentEditor>
      
    </pipelines>
  </sitecore>
</configuration>

I then added a toggle checkbox to the View ribbon, and wired up the ToggleGotoTemplateLinks command to it:

goto-template-links-view-checkbox

When the ‘Goto Template Links’ checkbox is checked, ‘Goto Template’ links are displayed for each field in the Content Editor:

goto-template-links-turned-on

When unchecked, the ‘Goto Template’ links are not rendered:

goto-template-links-turned-off

Let’s try it out.

Let’s click one of these ‘Goto Template’ links and see what it does, or where it takes us:

Home-Data-Title-Goto-Template-Link

It brought us to the template where the Title field is defined:

Goto-Template-Title-Template

Let’s try another. How about the ‘Created By’ field?

home-created-by-goto-template-link

Its link brought us to its template:

Goto-Template-CreatedBy-Template

Without a doubt, the functionality above would be useful to developers and advanced users.

I’ve been trying to figure out other potential uses for other subclasses of EditorFormatter. Can you think of other ways we could leverage a custom EditorFormatter, especially one for non-technical Sitecore users? If you have any ideas, please drop a comment. 🙂

Take the Field By Replicating Sitecore Field Values

I pondered the other day whether anyone had ever erroneously put content into fields on the wrong Sitecore item, only to discover they had erred after laboring away for an extended period of time — imagine the ensuing frustration after realizing such a blunder.

You might think that this isn’t a big deal — why not just rename the item to be the name of the item you were supposed to be putting content into in the first place?

Well, things might not be that simple.

What if the item already had content in it before? What do you do?

This hypothetical — or fictitious — scenario got the creative juices flowing. Why not create new item context menu options — check out part 1 and part 2 of my post discussing how one would go about augmenting the item context menu, and also my last post showing how one can delete sitecore items using a deletion basket which is serves as another example of adding to the item context menu — that give copy and paste functionality for field values?

The cornerstone of my idea comes from functionality that comes with Sitecore “out of the box”. You have the option to cut, copy and paste items:

cut-copy-paste-context-menu

I find these three menu options to be indispensable. I frequently use them throughout the day when developing new features in Sitecore, and have also seen content authors use these to do their work.

The only problem with these is they don’t work at the field level, ergo the reason for this post: to showcase my efforts in building copy and paste utilities that work at the field level.

I first had to come up with a way to save field values. The following interface serves as the definition of objects that save information associated with a key:

namespace Sitecore.Sandbox.Utilities.Storage.Base
{
    public interface IRepository<TKey, TValue>
    {
        bool Contains(TKey key);

        TValue this[TKey key] { get; set; }

        void Put(TKey key, TValue value);

        void Remove(TKey key);

        void Clear();

        TValue Get(TKey key);
    }
}

For my copy and paste utilities, I decided I would store them in session. That steered me into building the following session repository class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.SessionState;

using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Utilities.Storage
{
    public class SessionRepository : IRepository<string, object>
    {
        private HttpSessionStateBase Session { get; set; }

        public object this[string key]
        {
            get
            {
                return Get(key);
            }
            set
            {
                Put(key, value);
            }
        }

        private SessionRepository(HttpSessionState session)
            : this(CreateNewHttpSessionStateWrapper(session))
        {
        }

        private SessionRepository(HttpSessionStateBase session)
        {
            SetSession(session);
        }

        private void SetSession(HttpSessionStateBase session)
        {
            Assert.ArgumentNotNull(session, "session");
            Session = session;
        }

        public bool Contains(string key)
        {
            return Session[key] != null;
        }

        public void Put(string key, object value)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            Assert.ArgumentCondition(IsSerializable(value), "value", "value must be serializable!");
            Session[key] = value;
        }

        private static bool IsSerializable(object instance)
        {
            Assert.ArgumentNotNull(instance, "instance");
            return instance.GetType().IsSerializable;
        }

        public void Remove(string key)
        {
            Session.Remove(key);
        }

        public void Clear()
        {
            Session.Clear();
        }

        public object Get(string key)
        {
            return Session[key];
        }

        private static HttpSessionStateWrapper CreateNewHttpSessionStateWrapper(HttpSessionState session)
        {
            Assert.ArgumentNotNull(session, "session");
            return new HttpSessionStateWrapper(session);
        }

        public static IRepository<string, object> CreateNewSessionRepository(HttpSessionState session)
        {
            return new SessionRepository(session);
        }

        public static IRepository<string, object> CreateNewSessionRepository(HttpSessionStateBase session)
        {
            return new SessionRepository(session);
        }
    }
}

If you’ve read some of my previous posts, you must have ascertained how I favor composition over inheritance — check out this article that discusses this subject — and created another utility object for storing string values — instances of this class delegate to other repository objects that save generic objects (an instance of the session repository class above is an example of such an object):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.SessionState;

using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Utilities.Storage
{
    public class StringRepository : IRepository<string, string>
    {
        private IRepository<string, object> InnerRepository { get; set; }

        public string this[string key]
        {
            get
            {
                return Get(key);
            }
            set
            {
                Put(key, value);
            }
        }

        private StringRepository(IRepository<string, object> innerRepository)
        {
            SetInnerRepository(innerRepository);
        }

        private void SetInnerRepository(IRepository<string, object> innerRepository)
        {
            Assert.ArgumentNotNull(innerRepository, "innerRepository");
            InnerRepository = innerRepository;
        }

        public bool Contains(string key)
        {
            return InnerRepository.Contains(key);
        }

        public void Put(string key, string value)
        {
            Assert.ArgumentNotNullOrEmpty(key, "key");
            InnerRepository.Put(key, value);
        }

        public void Remove(string key)
        {
            InnerRepository.Remove(key);
        }

        public void Clear()
        {
            InnerRepository.Clear();
        }

        public string Get(string key)
        {
            return InnerRepository.Get(key) as string;
        }

        public static IRepository<string, string> CreateNewStringRepository(IRepository<string, object> innerRepository)
        {
            return new StringRepository(innerRepository);
        }
    }
}

I then built another — yes one more — repository class that uses instances of Sitecore.Data.ID as keys:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Utilities.Storage
{
    class IDValueRepository : IRepository<ID, string>
    {
        private IRepository<string, string> InnerRepository { get; set; }
        
        public string this[ID key] 
        {
            get
            {
                return Get(key);
            }
            set
            {
                Put(key, value);
            }
        }

        private IDValueRepository(IRepository<string, string> innerRepository)
        {
            SetInnerRepository(innerRepository);
        }

        private void SetInnerRepository(IRepository<string, string> innerRepository)
        {
            Assert.ArgumentNotNull(innerRepository, "innerRepository");
            InnerRepository = innerRepository;
        }

        public bool Contains(ID key)
        {
            return InnerRepository.Contains(GetInnerRepositoryKey(key));
        }

        public void Put(ID key, string value)
        {
            InnerRepository.Put(GetInnerRepositoryKey(key), value);
        }

        public void Remove(ID key)
        {
            InnerRepository.Remove(GetInnerRepositoryKey(key));
        }

        public void Clear()
        {
            InnerRepository.Clear();
        }

        public string Get(ID key)
        {
            return InnerRepository.Get(GetInnerRepositoryKey(key));
        }

        private static string GetInnerRepositoryKey(ID key)
        {
            AssertKey(key);
            return key.ToString();
        }

        private static void AssertKey(ID key)
        {
            Assert.ArgumentNotNull(key, "key");
            Assert.ArgumentCondition(!ID.IsNullOrEmpty(key), "key", "key must be set!");
        }

        public static IRepository<ID, string> CreateNewIDValueRepository(IRepository<string, string> innerRepository)
        {
            return new IDValueRepository(innerRepository);
        }
    }
}

Instances of the above class delegate down to repository objects that save strings using strings as keys.

Now that I have an unwieldy arsenal of repository utility classes — I went a little bananas on creating the utility classes above — I figured having a factory class as a central place to instantiate these repository objects would aid in keeping things organized:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Data.Fields;
using System.Web;
using System.Web.SessionState;
using Sitecore.Data;

namespace Sitecore.Sandbox.Utilities.Storage.Base
{
    public interface IStorageFactory
    {
        IRepository<string, object> CreateNewSessionRepository(HttpSessionState session);

        IRepository<string, object> CreateNewSessionRepository(HttpSessionStateBase session);

        IRepository<string, string> CreateNewStringRepository(IRepository<string, object> innerRepository);

        IRepository<ID, string> CreateNewIDValueRepository(HttpSessionState session);

        IRepository<ID, string> CreateNewIDValueRepository(IRepository<string, string> innerRepository);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

using Sitecore.Data;
using Sitecore.Data.Fields;

using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Utilities.Storage
{
    public class StorageFactory : IStorageFactory
    {
        private StorageFactory()
        {
        }

        public IRepository<string, object> CreateNewSessionRepository(HttpSessionState session)
        {
            return SessionRepository.CreateNewSessionRepository(session);
        }

        public IRepository<string, object> CreateNewSessionRepository(HttpSessionStateBase session)
        {
            return SessionRepository.CreateNewSessionRepository(session);
        }

        public IRepository<string, string> CreateNewStringRepository(IRepository<string, object> innerRepository)
        {
            return StringRepository.CreateNewStringRepository(innerRepository);
        }

        public IRepository<ID, string> CreateNewIDValueRepository(HttpSessionState session)
        {
            return CreateNewIDValueRepository(CreateNewStringRepository(CreateNewSessionRepository(session)));
        }

        public IRepository<ID, string> CreateNewIDValueRepository(IRepository<string, string> innerRepository)
        {
            return IDValueRepository.CreateNewIDValueRepository(innerRepository);
        }

        public static IStorageFactory CreateNewStorageFactory()
        {
            return new StorageFactory();
        }
    }
}

Let’s make these utility repository classes earn their keep. It’s time to build a copy command:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Fields;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;

using Sitecore.Sandbox.Utilities.Storage;
using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Commands
{
    public class CopyFieldValues : Command
    {
        private static readonly IStorageFactory Factory = StorageFactory.CreateNewStorageFactory();
        private static readonly IRepository<ID, string> FieldValueRepository = CreateNewIDValueRepository();

        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            StoreFieldValues(GetItem(commandContext));
        }

        private static void StoreFieldValues(Item item)
        {
            if (item != null)
            {
                item.Fields.ReadAll();
                StoreFieldValues(item.Fields);
            }
        }

        private static void StoreFieldValues(IEnumerable<Field> fields)
        {
            Assert.ArgumentNotNull(fields, "fields");
            foreach (Field field in fields)
            {
                FieldValueRepository.Put(field.ID, field.Value);
            }
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            if (GetItem(commandContext).Appearance.ReadOnly)
            {
                return CommandState.Disabled;
            }

            return base.QueryState(commandContext);
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            Assert.ArgumentCondition(commandContext.Items.Count() > 0, "commandContext.Items", "There must be at least one item in the array!");
            return commandContext.Items.FirstOrDefault();
        }

        private static IRepository<ID, string> CreateNewIDValueRepository()
        {
            return Factory.CreateNewIDValueRepository(HttpContext.Current.Session);
        }
    }
}

The above command iterates over all fields on the currently select item in the content tree, and saves their values using an instance of the IDValueRepository class.

What good is a copy command without a paste? The following paste command complements the copy command defined above:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;

using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.Sheer;

using Sitecore.Sandbox.Utilities.Storage;
using Sitecore.Sandbox.Utilities.Storage.Base;

namespace Sitecore.Sandbox.Commands
{
    public class PasteFieldValues : Command
    {
        private static readonly IStorageFactory Factory = StorageFactory.CreateNewStorageFactory();
        private static readonly IRepository<ID, string> FieldValueRepository = CreateNewIDValueRepository();

        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            PasteValuesIfApplicable(commandContext);
        }

        private void PasteValuesIfApplicable(CommandContext commandContext)
        {
            Item item = GetItem(commandContext);
            if (item == null)
            {
                return;
            }

            PasteValuesIfApplicable(item);
        }

        private void PasteValuesIfApplicable(Item item)
        {
            Assert.ArgumentNotNull(item, "item");

            if (DoesFieldsHaveValues(item))
            {
                ConfirmThenPaste(item);
            }
            else
            {
                PasteValues(item);
            }
        }

        private static bool DoesFieldsHaveValues(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNull(item.Fields, "item.Fields");

            foreach (Field field in item.Fields)
            {
                if (!string.IsNullOrEmpty(field.Value))
                {
                    return true;
                }
            }

            return false;
        }

        private void ConfirmThenPaste(Item item)
        {
            NameValueCollection parameters = new NameValueCollection();
            parameters["items"] = SerializeItems(new Item[] { item });
            Context.ClientPage.Start(this, "ConfirmAndPaste", new ClientPipelineArgs { Parameters = parameters });
        }

        private void ConfirmAndPaste(ClientPipelineArgs args)
        {
            ShowConfirmationDialogIfApplicable(args);
            PasteValuesIfConfirmed(args);
        }

        private void ShowConfirmationDialogIfApplicable(ClientPipelineArgs args)
        {
            if (!args.IsPostBack)
            {
                Context.ClientPage.ClientResponse.YesNoCancel("Some fields are not empty! Are you sure you want to paste field values into this item?", "200", "200");
                args.WaitForPostBack();
            }
        }

        private void PasteValuesIfConfirmed(ClientPipelineArgs args)
        {
            bool canPaste = args.IsPostBack && args.Result == "yes";
            if (canPaste)
            {
                Item item = DeserializeItems(args.Parameters["items"]).FirstOrDefault();
                PasteValues(item);
            }
        }

        private static void PasteValues(Item item)
        {
            if (item != null)
            {
                item.Editing.BeginEdit();
                item.Fields.ReadAll();
                PasteValues(item.Fields);
                item.Editing.EndEdit();
            }
        }

        private static void PasteValues(IEnumerable<Field> fields)
        {
            Assert.ArgumentNotNull(fields, "fields");
            foreach (Field field in fields)
            {
                string value = FieldValueRepository.Get(field.ID);
                if (!string.IsNullOrEmpty(value))
                {
                    field.Value = value;
                }

                FieldValueRepository.Remove(field.ID);
            }
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            if (GetItem(commandContext).Appearance.ReadOnly)
            {
                return CommandState.Disabled;
            }

            return base.QueryState(commandContext);
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            Assert.ArgumentCondition(commandContext.Items.Count() > 0, "commandContext.Items", "There must be at least one item in the array!");
            return commandContext.Items.FirstOrDefault();
        }

        private static IRepository<ID, string> CreateNewIDValueRepository()
        {
            return Factory.CreateNewIDValueRepository(HttpContext.Current.Session);
        }
    }
}

The paste command determines if the target item has any fields with content in them — a confirmation dialog box is displayed if any of the fields are not empty — and pastes values into fields if they are present on the item.

Plus, once a field value is retrieved from the IDValueRepository instance, the above command removes it. I couldn’t think of a good reason why these should linger in session after they are pasted. If you can of a reason why they should persist in session, please leave a comment.

I registered the copy and paste commands above into a patch include file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <sitecore>
    <commands>
      <command name="item:copyfieldvalues" type="Sitecore.Sandbox.Commands.CopyFieldValues,Sitecore.Sandbox"/>
      <command name="item:pastefieldvalues" type="Sitecore.Sandbox.Commands.PasteFieldValues,Sitecore.Sandbox"/>
    </commands>
  </sitecore>
</configuration>

I created context menu options for these in the Core database:

copy-field-values-context-menu-option

paste-field-values-context-menu-option

Let’s take all of the above for a spin.

I created an item with some content:

just-some-item-with-content

I then created another item with less content:

just-some-other-item-sparse-content

I right-clicked to launch the item context menu, and clicked the ‘Copy Field Values’ option:

clicked-copy-field-values

I then navigated to the second item I created in the content tree, right-clicked, and selected the ‘Paste Field Values’ option:

clicked-paste-field-values

By now, I had put my feet up on my desk thinking it was smooth sailing from this point on, only to be impeded by an intrusive confirmation box ;):

fields-not-empty-confirm

I clicked ‘Yes’, and saw the following thereafter:

field-values-copied

In retrospect, it probably would have made more sense to omit standard fields from being copied, albeit I will leave that for another day.

Until next time, have a Sitecoretastic day! 🙂

Delete Sitecore Items Using a Deletion Basket

For the past week, I’ve been battling a nasty strain of the rhinovirus — don’t worry, that’s just the fancy medical term for what is known as the common cold — albeit there appears to be nothing common about this cold. I think I have a frankencold (I just made up this word, and might submit it to Merriam-Webster for inclusion in the English dictionary).

In my sickened state — perhaps it could be classified as a state of frenzy — I started pondering over strange feature ideas. The ‘Dislike’ button was one idea that came to mind. It would serve as the antithesis to the ‘Like’ button found on most social networking outlets. Such a feature would definitely be a whimsical thing to build, although might foment more trouble than it’s worth.

Another idea that came to mind was a deletion basket in the Sitecore client. It would be similar in theme to a shopping cart found on most e-commerce websites. Users would queue items in their deletion basket, and delete them after they are finished adding items — a checkout step for the lack of a better term.

The latter idea seemed useful — most importantly fun — so I decided to build it.

I first created a Deletion Basket class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Data;
using Sitecore.Data.Items;

namespace Sitecore.Sandbox.Utilities.Items.Base
{
    public interface IDeletionBasket
    {
        int Count();

        bool IsEmpty();

        IEnumerable<Item> GetItemsToDelete();

        bool Contains(Item item);

        void Add(Item item);

        void Remove(Item item);

        void DeleteAll();

        void Clear();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;

using Sitecore.Sandbox.Utilities.Items.Base;

namespace Sitecore.Sandbox.Utilities.Items
{
    public class DeletionBasket : IDeletionBasket
    {
        private static volatile IDeletionBasket current;
        private static object lockObject = new Object();

        public static IDeletionBasket Current
        {
            get
            {
                if (current == null)
                {
                    lock (lockObject)
                    {
                        if (current == null)
                            current = new DeletionBasket();
                    }
                }

                return current;
            }
        }

        private IList<Item> _ItemsToDelete;
        private IList<Item> ItemsToDelete
        {
            get
            {
                if (_ItemsToDelete == null)
                {
                    _ItemsToDelete = new List<Item>();
                }

                return _ItemsToDelete;
            }
        }

        private DeletionBasket()
        {
        }

        public int Count()
        {
            return ItemsToDelete.Count();
        }

        public bool IsEmpty()
        {
            return !ItemsToDelete.Any();
        }

        public IEnumerable<Item> GetItemsToDelete()
        {
            return ItemsToDelete;
        }

        public bool Contains(Item item)
        {
            return FindItemInBasket(item) != null;
        }

        private Item FindItemInBasket(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            return FindItemInBasketByID(item.ID);
        }

        private Item FindItemInBasketByID(ID id)
        {
            AssertID(id);
            return FindItemsInBasketByID(id).FirstOrDefault();
        }

        private IEnumerable<Item> FindItemsInBasketByID(ID id)
        {
            AssertID(id);
            return ItemsToDelete.Where(i => i.ID == id);
        }

        private static void AssertID(ID id)
        {
            Assert.ArgumentCondition(!ID.IsNullOrEmpty(id), "id", "ID must be set!");
        }

        public void Add(Item item)
        {
            Item itemInBasket = FindItemInBasket(item);
            if (itemInBasket == null)
            {
                ItemsToDelete.Add(item);
                AddChildren(item);
            }
        }

        private void AddChildren(Item item)
        {
            if (!item.HasChildren)
            {
                return;
            }

            foreach (Item child in item.Children)
            {
                Add(child);
            }
        }

        public void Remove(Item item)
        {
            Item itemInBasket = FindItemInBasket(item);
            if (itemInBasket != null)
            {
                ItemsToDelete.Remove(itemInBasket);
            }
        }

        public void DeleteAll()
        {
            Sitecore.Context.ClientPage.Start(this, "ConfirmAndDeleteAll", new ClientPipelineArgs());
        }

        private void ConfirmAndDeleteAll(ClientPipelineArgs args)
        {
            ShowConfirmationDialogIfApplicable(args);
            DeleteAllIfApplicable(args);
        }

        private void ShowConfirmationDialogIfApplicable(ClientPipelineArgs args)
        {
            if (!args.IsPostBack)
            {
                Context.ClientPage.ClientResponse.YesNoCancel(string.Format("Are you sure you want to delete the {0} item(s) in your Deletion Basket?", Count()), "200", "200");
                args.WaitForPostBack();
            }
        }

        private void DeleteAllIfApplicable(ClientPipelineArgs args)
        {
            bool canDelete = args.IsPostBack && args.Result == "yes";
            if (canDelete)
            {
                foreach (Item itemToDelete in ItemsToDelete)
                {
                    DeleteItem(itemToDelete);
                }

                Clear();
            }
        }

        private static void DeleteItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            if (Settings.RecycleBinActive)
            {
                item.Recycle();
            }
            else
            {
                item.Delete();
            }
        }

        public void Clear()
        {
            ItemsToDelete.Clear();
        }
    }
}

The above class stores and deletes items from a list, and prompts users ascertaining if they truly want to delete items within the deletion basket.

Only one instance of the above class can exist — I employed the Singleton pattern for this purpose — to keep the code simple for this blog post, although it probably would make more sense to make baskets session aware — have different baskets for different sessions.

Next, I created a command to add or remove an item from the deletion basket — depending on whether the item is in the basket:

using System.Linq;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Shell.Framework.Commands;

using Sitecore.Sandbox.Utilities.Items;
using Sitecore.Sandbox.Utilities.Items.Base;

namespace Sitecore.Sandbox.Commands
{
    class ToggleItemInDeletionBasket : Command
    {
        private static readonly Delete DeleteCommand = new Delete();

        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            ToggleInDeletionBasketIfEnabled(commandContext);
        }

        private void ToggleInDeletionBasketIfEnabled(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            if (QueryState(commandContext) == CommandState.Enabled)
            {
                ToggleInDeletionBasketAndRefresh(GetItem(commandContext));
            }
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            return DeleteCommand.QueryState(commandContext);
        }

        private static void ToggleInDeletionBasketAndRefresh(Item item)
        {
            ToggleInDeletionBasket(item);
            RefreshItem(item);
        }

        private static void ToggleInDeletionBasket(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            IDeletionBasket deletionBasket = DeletionBasket.Current;

            if(deletionBasket.Contains(item))
            {
                deletionBasket.Remove(item);
            }
            else
            {
                deletionBasket.Add(item);
            }
        }

        private static Item GetItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            Assert.ArgumentCondition(commandContext.Items.Count() > 0, "commandContext.Items", "There must be at least one item in the array!");
            return commandContext.Items.FirstOrDefault();
        }

        public override string GetHeader(CommandContext commandContext, string header)
        {
            if (DeletionBasket.Current.Contains(GetItem(commandContext)))
            {
                return Translate.Text("Remove from Deletion Basket");
            }

            return Translate.Text("Add to Deletion Basket");
        }

        private static void RefreshItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            Context.ClientPage.ClientResponse.Timer(string.Format("item:load(id={0})", item.ID), 1);
        }
    }
}

The text of the command is different when the item is in the basket versus when it is not.

The command also reloads the item in the Sitecore client — this is done to update the state of the deletion basket buttons in the ribbon.

Now, we need a command to delete items queued in the deletion basket. The ‘Empty Deletion Basket’ command does just that:

using System.Linq;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Shell.Framework.Commands;

using Sitecore.Sandbox.Utilities.Items;
using Sitecore.Sandbox.Utilities.Items.Base;

namespace Sitecore.Sandbox.Commands
{
    public class EmptyDeletionBasket : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            EmptyDeletionBasketIfEnabled(commandContext);
        }

        private void EmptyDeletionBasketIfEnabled(CommandContext commandContext)
        {
            if (QueryState(commandContext) == CommandState.Enabled)
            {
                DeleteAllItemsInDeletionBasketAndRefresh();
            }
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");

            if (DeletionBasket.Current.IsEmpty())
            {
                return CommandState.Hidden;
            }

            return base.QueryState(commandContext);
        }

        private static void DeleteAllItemsInDeletionBasketAndRefresh()
        {
            Item firstItemParent = GetFirstItemParent();
            DeleteAllItemsInDeletionBasket();
            RefreshItem(firstItemParent);
        }

        private static void DeleteAllItemsInDeletionBasket()
        {
            DeletionBasket.Current.DeleteAll();
        }

        private static Item GetFirstItemParent()
        {
            Item itemForRefresh = DeletionBasket.Current.GetItemsToDelete().FirstOrDefault();
            if (itemForRefresh != null && itemForRefresh.Parent != null)
            {
                return itemForRefresh.Parent;
            }

            return null;
        }

        private static void RefreshItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            Context.ClientPage.ClientResponse.Timer(string.Format("item:load(id={0})", item.ID), 1);
        }

        public override string GetHeader(CommandContext commandContext, string header)
        {
            IDeletionBasket deletionBasket = DeletionBasket.Current;
            return Translate.Text(string.Format("Delete {0} Item(s)", deletionBasket.Count()));
        }
    }
}

This command also reloads the Sitecore client — using the the parent item of the first item flagged for deletion (you can’t reload an item that was already deleted). This is also done to refresh the state of the buttons in the ribbon.

Plus, the command is hidden when there are no items in the deletion basket.

We shouldn’t force users to only add and delete items in their basket. We should also allow them to clear out their baskets, in case they change their mind on what they want to delete. I created a ‘Clear Deletion Basket’ command for this very reason:

using System.Linq;

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.Sheer;

using Sitecore.Sandbox.Utilities.Items;

namespace Sitecore.Sandbox.Commands
{
    public class ClearDeletionBasket : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            ClearDeletionBasketIfEnabled(commandContext);
        }

        private void ClearDeletionBasketIfEnabled(CommandContext commandContext)
        {
            if (QueryState(commandContext) == CommandState.Enabled)
            {
                ClearAllItemsInDeletionBasketAndRfresh();
            }
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");

            if (DeletionBasket.Current.IsEmpty())
            {
                return CommandState.Disabled;
            }

            return base.QueryState(commandContext);
        }

        private static void ClearAllItemsInDeletionBasketAndRfresh()
        {
            Item lastItem = GetLastItem();
            ClearAllItemsInDeletionBasket();
            RefreshItem(lastItem);
        }

        private static void ClearAllItemsInDeletionBasket()
        {
            DeletionBasket.Current.Clear();
        }

        private static Item GetLastItem()
        {
            Item itemForRefresh = DeletionBasket.Current.GetItemsToDelete().LastOrDefault();
            if (itemForRefresh != null)
            {
                return itemForRefresh;
            }

            return null;
        }

        private static void RefreshItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            Context.ClientPage.ClientResponse.Timer(string.Format("item:load(id={0})", item.ID), 1);
        }
    }
}

In order to use our commands above, we have to define them in /App_Config/Commands.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

	<!-- There's a bunch of commands up here -->
	
	<command name="item:toggleitemindeletionbasket" type="Sitecore.Sandbox.Commands.ToggleItemInDeletionBasket,Sitecore.Sandbox"/>
	<command name="item:cleardeletionbasket" type="Sitecore.Sandbox.Commands.ClearDeletionBasket,Sitecore.Sandbox"/>
	<command name="item:emptydeletionbasket" type="Sitecore.Sandbox.Commands.EmptyDeletionBasket,Sitecore.Sandbox"/>
</configuration>

Now that our commands are defined in /App_Config/Commands.config, we can now wire them up in the Core database.

I’ve wired up the ‘Empty Deletion Basket’ button:

Empty-Deletion-Basket-Core

Followed by wiring up the ‘Clear Deletion Basket’ dropdown button:

Clear-Deletion-Basket-Core

Next, I set up the ‘Toggle Item In Deletion Basket’ item context menu button:

Toggle-Item-In-Deletion-Basket-Core

Let’s see how we did.

I’ve switched back over to the master database, picked an item at random, and right-clicked. There’s our new ‘Toggle Item In Deletion Basket’ button:

Toggle-Not-In-Deletion-Basket

The appropriate wording is displayed since the item is not in the Deletion Basket.

I’ve clicked the ‘Toggle Item In Deletion Basket’ button in the item context menu, and then right-clicked on the item again to launch it again:

Toggle-In-Deletion-Basket

We see that button’s text has changed to convey that this item is in the deletion basket, and can be removed from the deletion basket by clicking the item context menu button again.

Plus, the deletion basket buttons in the ribbon have magically appeared.

I’ve clicked the dropdown on the deletion basket button in the ribbon, and we now see the ‘Clear Deletion Basket’ button:

Clear-Deletion-Basket

I’m going to add a bunch of items to our deletion basket:

Add-A-Bunch-Of-Items-Deletion-Basket

They’ve all been added. Let’s get rid of them:

chosen-items-basket-delete

Doh — I’ve been blocked by an instrusive confirmation box:

chosen-items-basket-delete-confirmation

I’ve clicked ‘Yes’, and now the items are gone:

chosen-items-basket-deleted

That was all in good fun.

Time to investigate adding a ‘Dislike’ button to the popular social media channels. 😉

Chain Together Sitecore Client Commands using a Composite Command

Today, I procrastinated on doing chores around the house by exploring whether one could chain together Sitecore client commands in order to reduce the number of clicks and/or keypresses required when invoking these commands separately — combining the click of the ‘Save’ button followed by one of the publishing buttons would be an example of this.

Immediately, the composite design pattern came to mind for a candidate solution — you can read more about this pattern in the the Gang of Four’s book on design patterns.

This high-level plan of attack lead to the following custom composite command.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Text;

namespace Sitecore.Sandbox.Commands
{
    public class CompositeCommand : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            IEnumerable<Command> commands = GetCommands();

            foreach (Command command in commands)
            {
                command.Execute(commandContext);
            }
        }

        protected IEnumerable<Command> GetCommands()
        {
            ListString commandNames = GetCommandNames();
            IList<Command> commands = new List<Command>();

            foreach(string commandName in commandNames)
            {
                AddToListIfNotNull(commands, CommandManager.GetCommand(commandName));
            }

            return commands;
        }

        private ListString GetCommandNames()
        {
            return new ListString(GetCommandsFieldValue(), '|');
        }

        private string GetCommandsFieldValue()
        {
            XmlNode xmlNode = Factory.GetConfigNode(string.Format("commands/command[@name='{0}']", Name));
            bool canGetCommands = xmlNode != null && xmlNode.Attributes["commands"] != null;

            if (canGetCommands)
            {
                return xmlNode.Attributes["commands"].Value;
            }
            
            return string.Empty;
        }

        private static void AddToListIfNotNull<T>(IList<T> list, T objectToAdd) where T : class
        {
            Assert.ArgumentNotNull(list, "list");
            if (objectToAdd != null)
            {
                list.Add(objectToAdd);
            }
        }
    }
}

The above command — using the Sitecore.Configuration.Factory class — gets its XML configuration element; parses the list of commands it wraps from a new attribute I’ve added — I’ve named this attribute “commands”; gets instances of these commands via Sitecore.Shell.Framework.Commands.CommandManager (from Sitecore.Kernel.dll); and invokes all Command instances’ Execute() methods consecutively — ordered from left to right, separated by pipes, in the “commands” attribute on the command XML element in /App_Config/Commands.config.

To test this out, I thought I’d create a composite command combining the item save command with the publish command — the command that launches the Publish Item Wizard.

I first had to wire up my new command by adding a new command XML element to /App_Config/Commands.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<!-- bunch of commands up here --> 
	<command name="composite:savethenpublish" commands="contenteditor:save|item:publish" type="Sitecore.Sandbox.Commands.CompositeCommand,Sitecore.Sandbox"/>
</configuration>

Next, in the core db, I had to create a reference under the home strip:

save-publish-reference

Followed by a chunk containing a button that holds the name of our new command:

save-publish-chunk-button

Let’s see this new composite command in action. I did the following:

save-and-publish-item

After the Sitecore save animation completed, the Publish Item Wizard popped up:

save-publish-item-2

Now, it’s time for some fun. Let’s combine commands that make little sense in chaining together.

Let’s chain together:

  1. the command I built in my post on expanding Standard Values tokens
  2. the command to move an item before all its siblings in the content tree
  3. the command to move an item down in the content tree

Here’s what the command’s configuration looks like in /App_Config/Commands.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<!-- bunch of commands up here --> 
	<command name="composite:chainsomeunrelatedcommands" commands="item:expandtokens|item:movefirst|item:movedown" type="Sitecore.Sandbox.Commands.CompositeCommand,Sitecore.Sandbox"/>
</configuration>

I decided to add this to the item context menu — for more information on adding to the context menu for items, please check out my post that shows you how to do this — so I created new menu option in the context menu for items in the core database:

chain-command-context-menu-option

I switched back to the master database; added some Standard Values tokens to some fields in the Page 4 item I created for testing; right-clicked on on it; and clicked my new context menu option:

chain-context-menu-option-invoke

After a second or two, I saw that the tokens were expanded, and the item was moved:

chain-context-menu-option-finished

That’s all for now. It’s now time to go do some house chores. Otherwise, people might start thinking I’m truly addicted to building things in Sitecore. 🙂

You Can’t Move This! Experiments in Disabling Move Related Commands in the getQueryState Sitecore Pipeline

I was scavenging through my local sandbox instance’s Web.config the other day — yes I was looking for things to customize — and noticed the getQueryState pipeline — a pipeline that contains no “out of the box” pipeline processors:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<!-- Some stuff here -->
	<sitecore>
		<!-- Some more stuff here -->
		<pipelines>
			<!-- Even more stuff here -->
		<!--  Allows developers to programmatically disable or hide any button or panel in the Content Editor ribbons 
            without overriding the individual commands. 
            Processors must accept a single argument of type GetQueryStateArgs (namespace: Sitecore.Pipelines.GetQueryState)  -->
			<getQueryState>
			</getQueryState>
			<!-- Yeup, more stuff here -->
		</pipelines>
		<!-- wow, lots of stuff here too -->
	</sitecore>
	<!-- lots of stuff down here -->
</configuration>

The above abridged version of my Web.config contains an XML comment underscoring what this pipeline should be used for: disabling and/or hiding buttons in the Sitecore client.

Although I am still unclear around the practicality of using this pipeline overall — if you have an idea, please leave a comment — I thought it would be fun building one regardless, just to see how it works. Besides, I like to tinker with things — many of my previous posts corroborate this sentiment.

What I came up with is a getQueryState pipeline processor that disables buttons containing move related commands on a selected item in the content tree with a particular template. Sorting commands also fall under the umbrella of move related commands, so these are included in our set of commands to disable.

Here’s the pipeline processor I built:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.GetQueryState;
using Sitecore.Shell.Framework.Commands;

namespace Sitecore.Sandbox.Pipelines.GetQueryState
{
    public class DisableMoveCommands
    {
        private static readonly IEnumerable<string> Commands = GetCommands();
        private static readonly IEnumerable<string> UnmovableTemplateIDs = GetUnmovableTemplateIDs();

        public void Process(GetQueryStateArgs args)
        {
            if (!CanProcessGetQueryStateArgs(args))
            {
                return;
            }

            bool shouldDisableCommand = IsUnmovableItem(GetCommandContextItem(args)) && IsMovableCommand(args.CommandName);
            if (shouldDisableCommand)
            {
                args.CommandState = CommandState.Disabled;
            }
        }

        private static bool CanProcessGetQueryStateArgs(GetQueryStateArgs args)
        {
            return args != null
                    && !string.IsNullOrEmpty(args.CommandName)
                    && args.CommandContext != null
                    && args.CommandContext.Items.Any();
        }

        private static Item GetCommandContextItem(GetQueryStateArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.CommandContext, "args.CommandContext");
            Assert.ArgumentNotNull(args.CommandContext.Items, "args.CommandContext.Items");
            return args.CommandContext.Items.FirstOrDefault();
        }

        private static bool IsUnmovableItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            return IsUnmovableTemplateID(item.TemplateID);
        }

        private static bool IsUnmovableTemplateID(ID templateID)
        {
            Assert.ArgumentCondition(!ID.IsNullOrEmpty(templateID), "templateID", "templateID must be set!");
            return UnmovableTemplateIDs.Contains(templateID.ToString());
        }

        private static bool IsMovableCommand(string command)
        {
            Assert.ArgumentNotNullOrEmpty(command, "command");
            return Commands.Contains(command);
        }

        private static IEnumerable<string> GetCommands()
        {
            return GetStringCollection("moveCommandsToPrevent/command");
        }

        private static IEnumerable<string> GetUnmovableTemplateIDs()
        {
            return GetStringCollection("unmovableTemplates/id");
        }

        private static IEnumerable<string> GetStringCollection(string path)
        {
            Assert.ArgumentNotNullOrEmpty(path, "path");
            return Factory.GetStringSet(path);
        }
    }
}

The above pipeline processor checks to see if the selected item in the content tree has the unmovable template I defined, coupled with whether the current command is within the set of commands we are to disable. If both are cases are met, the pipeline processor will disable the context command.

I defined my unmovable template and commands to disable in a patch include config file, along with the getQueryState pipeline processor:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getQueryState>
        <processor type="Sitecore.Sandbox.Pipelines.GetQueryState.DisableMoveCommands, Sitecore.Sandbox" />
      </getQueryState>
    </pipelines>
    <unmovableTemplates>
      <id>{8ADD3F45-027C-49C5-A8FB-0406B8C8728D}</id>
    </unmovableTemplates>
    <moveCommandsToPrevent>
      <command>item:moveto</command>
      <command>item:cuttoclipboard</command>
      <command>item:moveup</command>
      <command>item:movedown</command>
      <command>item:movefirst</command>
      <command>item:movelast</command>
      <command>item:moveto</command>
    </moveCommandsToPrevent>
  </sitecore>
</configuration>

Looking at the context menu on my unmovable item — appropriately named “You Cant Move This” — you can see the move related buttons are disabled:

context-menu-move-commands-disabled

Plus, item level sorting commands are also disabled:

context-menu-sorting-commands-disabled

Move related buttons in the ribbon are also disabled:

move-commands-in-ribbon-disabled

There really wasn’t much to building this pipeline processor, and this pipeline is at your disposal if you ever find yourself in a situation where you might have to disable buttons in the Sitecore client for whatever reason.

However, as I mentioned above, I still don’t understand why one would want to use this pipeline. If you have an idea why, please let me know.

Empower Your Content Authors to Expand Standard Values Tokens in the Sitecore Client

Have you ever seen a Standard Values token — $name is an example of a Standard Values token — in an item’s field, and ask yourself “how the world did that get there”, or alternatively, “what can be done to replace it with what should be there?”

This can occur when tokens are added to an item’s template’s Standard Values node after the item was created — tokens are expanded once an item is created, not after the fact.

John West wrote a blog article highlighting one solution for eradicating this issue by using the Sitecore Rules Engine.

In this post, I am proposing a completely different solution — one that empowers content authors to expand unexpanded tokens by clicking a link in a custom content editor warning box.

First, I created a series of utility objects that ascertain whether “Source” objects contain substrings that we are interested in. All implement the following interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sitecore.Sandbox.Utilities.StringUtilities.Base
{
    public interface ISubstringsChecker<T>
    {
        T Source { get; set; }
        
        IEnumerable<string> Substrings { get; set; }

        bool ContainsSubstrings();
    }
}

All of our “checkers” will have a “Source” object, a collection of substrings to look for, and a method to convey to calling code whether a substring in the collection of substrings had been found in the “Source” object.

I decided to create a base abstract class with some abstract methods along with one method to serve as a hook for asserting the Source object — albeit I did not use this method anywhere in my solution (come on Mike, you’re forgetting YAGNI — let’s get with the program).

Utimately, I am employing the template method pattern — all subclasses of this abstract base class will just fill in the defined abstract stubs, and the parent class will take care of the rest:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sitecore.Sandbox.Utilities.StringUtilities.Base
{
    public abstract class SubstringsChecker<T> : ISubstringsChecker<T>
    {
        public T Source { get; set; }

        public virtual IEnumerable<string> Substrings { get; set; }

        protected SubstringsChecker(T source)
        {
            SetSource(source);
        }

        private void SetSource(T source)
        {
            AssertSource(source);
            Source = source;
        }

        protected virtual void AssertSource(T source)
        {
            // a hook for subclasses to assert Source objects
        }

        public bool ContainsSubstrings()
        {
            if (CanDoCheck())
            {
                return DoCheck();
            }

            return false;
        }

        protected abstract bool CanDoCheck();
        protected abstract bool DoCheck();
    }
}

The first “checker” I created will find substrings in a string. It made sense for me to start here, especially when we are ultimately checking strings at the most atomic level in our series of “checker” utility objects.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.StringUtilities.Base;
using Sitecore.Sandbox.Utilities.StringUtilities.DTO;

namespace Sitecore.Sandbox.Utilities.StringUtilities
{
    public class StringSubstringsChecker : SubstringsChecker<string>
    {
        private StringSubstringsChecker(IEnumerable<string> substrings)
            : this(null, substrings)
        {
        }

        private StringSubstringsChecker(string source, IEnumerable<string> substrings)
            : base(source)
        {
            SetSubstrings(substrings);
        }

        private void SetSubstrings(IEnumerable<string> substrings)
        {
            AssertSubstrings(substrings);
            Substrings = substrings;
        }

        private static void AssertSubstrings(IEnumerable<string> substrings)
        {
            Assert.ArgumentNotNull(substrings, "substrings");
            Assert.ArgumentCondition(substrings.Any(), "substrings", "substrings must contain as at least one string!");
        }

        protected override bool CanDoCheck()
        {
            return !string.IsNullOrEmpty(Source);
        }

        protected override bool DoCheck()
        {
            Assert.ArgumentNotNullOrEmpty(Source, "Source");

            foreach (string substring in Substrings)
            {
                if (Source.Contains(substring))
                {
                    return true;
                }
            }

            return false;
        }

        public static ISubstringsChecker<string> CreateNewStringSubstringsContainer(IEnumerable<string> substrings)
        {
            return new StringSubstringsChecker(substrings);
        }

        public static ISubstringsChecker<string> CreateNewStringSubstringsContainer(string source, IEnumerable<string> substrings)
        {
            return new StringSubstringsChecker(substrings);
        }
    }
}

The next level up from strings would naturally be Fields. I designed this “checker” to consume an instance of the string “checker” defined above — all for the purposes of reuse. The field “checker” delegates calls to its string “checker” instance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Data.Fields;
using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.StringUtilities.Base;

namespace Sitecore.Sandbox.Utilities.StringUtilities
{
    public class FieldSubstringsChecker : SubstringsChecker<Field>
    {
        private ISubstringsChecker<string> StringSubstringsChecker { get; set; }

        public override IEnumerable<string> Substrings 
        {
            get
            {
                return StringSubstringsChecker.Substrings;
            }
            set
            {
                StringSubstringsChecker.Substrings = value;
            }
        }

        private FieldSubstringsChecker(ISubstringsChecker<string> stringSubstringsChecker)
            : this(null, stringSubstringsChecker)
        {
        }

        private FieldSubstringsChecker(Field source, ISubstringsChecker<string> stringSubstringsChecker)
            : base(source)
        {
            SetStringSubstringsChecker(stringSubstringsChecker);
        }

        private void SetStringSubstringsChecker(ISubstringsChecker<string> stringSubstringsChecker)
        {
            Assert.ArgumentNotNull(stringSubstringsChecker, "stringSubstringsChecker");
            StringSubstringsChecker = stringSubstringsChecker;
        }

        protected override bool CanDoCheck()
        {
            return Source != null;
        }

        protected override bool DoCheck()
        {
            Assert.ArgumentNotNull(Source, "Source");
            StringSubstringsChecker.Source = Source.Value;
            return StringSubstringsChecker.ContainsSubstrings();
        }

        public static ISubstringsChecker<Field> CreateNewFieldSubstringsChecker(ISubstringsChecker<string> stringSubstringsChecker)
        {
            return new FieldSubstringsChecker(stringSubstringsChecker);
        }

        public static ISubstringsChecker<Field> CreateNewFieldSubstringsChecker(Field source, ISubstringsChecker<string> stringSubstringsChecker)
        {
            return new FieldSubstringsChecker(source, stringSubstringsChecker);
        }
    }
}

If I were to ask you what the next level up in our series of “checkers” would be, I hope your answer would be Items. Below is a “checker” that uses an Item as its “Source” object, and delegates calls to an instance of a field “checker”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;

using Sitecore.Sandbox.Utilities.StringUtilities.Base;

namespace Sitecore.Sandbox.Utilities.StringUtilities
{
    public class ItemSubstringsChecker : SubstringsChecker<Item>
    {
        private ISubstringsChecker<Field> FieldSubstringsChecker { get; set; }

        public override IEnumerable<string> Substrings 
        {
            get
            {
                return FieldSubstringsChecker.Substrings;
            }
            set
            {
                FieldSubstringsChecker.Substrings = value;
            }
        }

        private ItemSubstringsChecker(ISubstringsChecker<Field> fieldSubstringsChecker)
            : this(null, fieldSubstringsChecker)
        {
        }

        private ItemSubstringsChecker(Item source, ISubstringsChecker<Field> fieldSubstringsChecker)
            : base(source)
        {
            SetFieldSubstringsChecker(fieldSubstringsChecker);
        }

        private void SetFieldSubstringsChecker(ISubstringsChecker<Field> fieldSubstringsChecker)
        {
            Assert.ArgumentNotNull(fieldSubstringsChecker, "fieldSubstringsChecker");
            FieldSubstringsChecker = fieldSubstringsChecker;
        }

        protected override bool CanDoCheck()
        {
            return Source != null && Source.Fields != null && Source.Fields.Any();
        }

        protected override bool DoCheck()
        {
            Assert.ArgumentNotNull(Source, "Source");
            bool containsSubstrings = false;

            for (int i = 0; !containsSubstrings && i < Source.Fields.Count; i++)
            {
                containsSubstrings = containsSubstrings || DoesFieldContainSubstrings(Source.Fields[i]);
            }

            return containsSubstrings;
        }

        private bool DoesFieldContainSubstrings(Field field)
        {
            FieldSubstringsChecker.Source = field;
            return FieldSubstringsChecker.ContainsSubstrings();
        }

        public static ISubstringsChecker<Item> CreateNewItemSubstringsChecker(ISubstringsChecker<Field> fieldSubstringsChecker)
        {
            return new ItemSubstringsChecker(fieldSubstringsChecker);
        }

        public static ISubstringsChecker<Item> CreateNewItemSubstringsChecker(Item source, ISubstringsChecker<Field> fieldSubstringsChecker)
        {
            return new ItemSubstringsChecker(source, fieldSubstringsChecker);
        }
    }
}

Next, I wrote code for a content editor warning box. I’m am completely indebted to .NET Reflector in helping out on this front — I looked at other content editor warning pipelines in Sitecore.Pipelines.GetContentEditorWarnings within Sitecore.Kernel to see how this is done:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Configuration;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Pipelines.GetContentEditorWarnings;

using Sitecore.Sandbox.Utilities.StringUtilities.Base;
using Sitecore.Sandbox.Utilities.StringUtilities;

namespace Sitecore.Sandbox.Pipelines.GetContentEditorWarnings
{
    public class HasUnexpandedTokens
    {
        private static readonly ISubstringsChecker<Item> SubstringsChecker = CreateNewItemSubstringsChecker();

        public void Process(GetContentEditorWarningsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (CanExpandTokens(args.Item))
            {
                AddHasUnexpandedTokensWarning(args);
            }
        }

        private static bool CanExpandTokens(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            return !IsStandardValues(item) && DoesItemContainUnexpandedTokens(item);
        }

        private static bool DoesItemContainUnexpandedTokens(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            SubstringsChecker.Source = item;
            return SubstringsChecker.ContainsSubstrings();
        }

        private static bool IsStandardValues(Item item)
        {
            return item.Template.StandardValues.ID == item.ID;
        }

        private static void AddHasUnexpandedTokensWarning(GetContentEditorWarningsArgs args)
        {
            GetContentEditorWarningsArgs.ContentEditorWarning warning = args.Add();
            warning.Title = Translate.Text("Some fields contain unexpanded tokens.");
            warning.Text = Translate.Text("To expand tokens, click Expand Tokens.");
            warning.AddOption(Translate.Text("Expand Tokens"), "item:expandtokens");
        }

        private static ISubstringsChecker<Item> CreateNewItemSubstringsChecker()
        {
            return ItemSubstringsChecker.CreateNewItemSubstringsChecker(CreateNewFieldSubstringsChecker());
        }

        private static ISubstringsChecker<Field> CreateNewFieldSubstringsChecker()
        {
            return FieldSubstringsChecker.CreateNewFieldSubstringsChecker(CreateNewStringSubstringsChecker());
        }

        private static ISubstringsChecker<string> CreateNewStringSubstringsChecker()
        {
            return StringSubstringsChecker.CreateNewStringSubstringsContainer(GetTokens());
        }

        private static IEnumerable<string> GetTokens()
        {
            return Factory.GetStringSet("tokens/token");
        }
    }
}

In my pipeline above, I am pulling a collection of token names from Sitecore configuration — these are going to be defined in a patch include file below. I had to go down this road since these tokens are not publically exposed in the Sitecore API.

Plus, we should only allow for the expansion of tokens when not on the Standard values item — it wouldn’t make much sense to expand these tokens here.

Since I’m referencing a new command in the above pipeline — a command that I’ve named “item:expandtokens” — it’s now time to create that new command:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;

using Sitecore.Sandbox.Utilities.StringUtilities;
using Sitecore.Sandbox.Utilities.StringUtilities.Base;
using Sitecore.Sandbox.Utilities.StringUtilities.DTO;

namespace Sitecore.Sandbox.Commands
{
    public class ExpandTokens : Command
    {
        public override void Execute(CommandContext commandContext)
        {
            if (!DoesCommandContextContainOneItem(commandContext))
            {
                return;
            }

            ExpandTokensInItem(GetCommandContextItem(commandContext));
        }

        private static void ExpandTokensInItem(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            item.Fields.ReadAll();
            item.Editing.BeginEdit();
            ExpandTokensViaMasterVariablesReplacer(item);
            item.Editing.EndEdit();
        }

        private static void ExpandTokensViaMasterVariablesReplacer(Item item)
        {
            MasterVariablesReplacer masterVariablesReplacer = Factory.GetMasterVariablesReplacer();
            masterVariablesReplacer.ReplaceItem(item);
        }

        public override CommandState QueryState(CommandContext commandContext)
        {
            if (ShouldHideCommand(commandContext))
            {
                return CommandState.Hidden;
            }
            
            if (ShouldDisableCommand(commandContext))
            {
                return CommandState.Disabled;
            }

            return base.QueryState(commandContext);
        }

        private bool ShouldHideCommand(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            return !DoesCommandContextContainOneItem(commandContext) 
                    || !HasField(GetCommandContextItem(commandContext), FieldIDs.ReadOnly);
        }

        private static bool ShouldDisableCommand(CommandContext commandContext)
        {
            AssertCommandContextItems(commandContext);
            Item item = GetCommandContextItem(commandContext);

            return !item.Access.CanWrite()
                    || Command.IsLockedByOther(item)
                    || !Command.CanWriteField(item, FieldIDs.ReadOnly);
        }

        private static Item GetCommandContextItem(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
            return commandContext.Items.FirstOrDefault();
        }

        private static bool DoesCommandContextContainOneItem(CommandContext commandContext)
        {
            AssertCommandContextItems(commandContext);
            return commandContext.Items.Length == 1;
        }

        private static void AssertCommandContextItems(CommandContext commandContext)
        {
            Assert.ArgumentNotNull(commandContext, "commandContext");
            Assert.ArgumentNotNull(commandContext.Items, "commandContext.Items");
        }
    }
}

This new command just uses an instance of Sitecore.Data.MasterVariablesReplacer to expand Standard Values tokens on our item.

I had to register this command in the /App_Config/Commands.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<! -- A bunch of commands defined here -->
	
	<command name="item:expandtokens" type="Sitecore.Sandbox.Commands.ExpandTokens,Sitecore.Sandbox" />
	
	<! -- A bunch more defined here too -->
</configuration>

I then put all the pieces together using a patch include config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getContentEditorWarnings>
        <processor type="Sitecore.Sandbox.Pipelines.GetContentEditorWarnings.HasUnexpandedTokens, Sitecore.Sandbox"/>
      </getContentEditorWarnings>
    </pipelines>
    <tokens>
      <token>$name</token>
      <token>$id</token>
      <token>$parentid</token>
      <token>$parentname</token>
      <token>$date</token>
      <token>$time</token>
      <token>$now</token>
    </tokens>
  </sitecore>
</configuration>

Let’s create an item for testing:

expand-tokens-new-item

As you can see, the item’s Title field was populated automatically during item creation — the $name token lives on this item’s template’s Standard Values item in Sitecore and was expanded when we created our test item.

Let’s create the problem we are trying to solve by adding new tokens to our test item’s template’s Standard Values node:

expand-tokens-new-tokens

As you can see, these new tokens appear in fields in our test item. However, don’t fret — we now have a way to fix this issue. 🙂

expand-tokens-content-editor-warning

I clicked on the ‘Expand Tokens’ link, and saw the following:

expand-tokens-expanded-no-warning

Hopefully, this post has given you another weapon to add to your arsenal for solving the unexpanded tokens issue on existing items in Sitecore.

If you find another solution, please drop me a line — I would love to hear about it.