Home » 2013 » February

Monthly Archives: February 2013

Advertisements

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! 🙂

Advertisements

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. 🙂

Prevent Sitecore Users from Using Common Dictionary Words in Passwords

Lately, enhancing security measures in Sitecore have been on my mind. One idea that came to mind today was finding a way to prevent password cracking — a scenario where a script tries to ascertain a user’s password by guessing over and over again what a user’s password might be, by supplying common words from a data store, or dictionary in the password textbox on the Sitecore login page.

As a way to prevent users from using common words in their Sitecore passwords, I decided to build a custom System.Web.Security.MembershipProvider — the interface (not a .NET interface but an abstract class) used by Sitecore out of the box for user management. Before we dive into that code, we need a dictionary of some sort.

I decided to use a list of fruits — all for the purposes of keeping this post simple — that I found on a Wikipedia page. People aren’t kidding when they say you can virtually find everything on Wikipedia, and no doubt all content on Wikipedia is authoritative — just ask any university professor. 😉

I copied some of the fruits on that Wikipedia page into a patch include config file — albeit it would make more sense to put these into a database, or perhaps into Sitecore if doing such a thing in a real-world solution. I am not doing this here for the sake of brevity.

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <dictionaryWords>
      <word>Apple</word>
      <word>Apricot</word>
      <word>Avocado</word>
      <word>Banana</word>
      <word>Breadfruit</word>
      <word>Bilberry</word>
      <word>Blackberry</word>
      <word>Blackcurrant</word>
      <word>Blueberry</word>
      <word>Currant</word>
      <word>Cherry</word>
      <word>Cherimoya</word>
      <word>Clementine</word>
      <word>Cloudberry</word>
      <word>Coconut</word>
      <word>Date</word>
      <word>Damson</word>
      <word>Dragonfruit</word>
      <word>Durian</word>
      <word>Eggplant</word>
      <word>Elderberry</word>
      <word>Feijoa</word>
      <word>Fig</word>
      <word>Gooseberry</word>
      <word>Grape</word>
      <word>Grapefruit</word>
      <word>Guava</word>
      <word>Huckleberry</word>
      <word>Honeydew</word>
      <word>Jackfruit</word>
      <word>Jettamelon</word>
      <word>Jambul</word>
      <word>Jujube</word>
      <word>Kiwi fruit</word>
      <word>Kumquat</word>
      <word>Legume</word>
      <word>Lemon</word>
      <word>Lime</word>
      <word>Loquat</word>
      <word>Lychee</word>
      <word>Mandarine</word>
      <word>Mango</word>
      <word>Melon</word>
    </dictionaryWords>
  </sitecore>
</configuration>

I decided to reuse a utility class I built for my post on expanding Standard Values tokens.

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 bool IgnoreCase { get; set; }

        private StringSubstringsChecker(IEnumerable<string> substrings)
            : this(null, substrings, false)
        {
        }

        private StringSubstringsChecker(IEnumerable<string> substrings, bool ignoreCase)
            : this(null, substrings, ignoreCase)
        {
        }

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

        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!");
        }

        private void SetIgnoreCase(bool ignoreCase)
        {
            IgnoreCase = ignoreCase;
        }

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

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

            foreach (string substring in Substrings)
            {
                if(DoesSourceContainSubstring(substring))
                {
                    return true;
                }
            }

            return false;
        }

        private bool DoesSourceContainSubstring(string substring)
        {
            if (IgnoreCase)
            {
                return !IsNotFoundIndex(Source.IndexOf(substring, StringComparison.CurrentCultureIgnoreCase));
            }

            return !IsNotFoundIndex(Source.IndexOf(substring));
        }

        private static bool IsNotFoundIndex(int index)
        {
            const int notFound = -1;
            return index == notFound;
        }

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

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

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

In the version of our “checker” class above, I added the option to have the “checker” ignore case comparisons for the source and substrings.

Next, I created a new System.Web.Security.MembershipProvider subclass where I am utilizing the decorator pattern to decorate methods around changing passwords and creating users.

By default, we are instantiating an instance of the System.Web.Security.SqlMembershipProvider — this is what my local Sitecore sandbox instance is using, in order to get at the ASP.NET Membership tables in the core database.

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

using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Security;

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

namespace Sitecore.Sandbox.Security.MembershipProviders
{
    public class PreventDictionaryWordPasswordsMembershipProvider : MembershipProvider 
    {
        private static IEnumerable<string> _DictionaryWords;
        private static IEnumerable<string> DictionaryWords
        {
            get
            {
                if (_DictionaryWords == null)
                {
                    _DictionaryWords = GetDictionaryWords();
                }

                return _DictionaryWords;
            }
        }

        public override string Name
        {
            get
            {
                return InnerMembershipProvider.Name;
            }
        }

        public override string ApplicationName
        {
            get
            {
                return InnerMembershipProvider.ApplicationName;
            }
            set
            {
                InnerMembershipProvider.ApplicationName = value;
            }
        }

        public override bool EnablePasswordReset
        {
            get
            {
                return InnerMembershipProvider.EnablePasswordReset;
            }
        }

        public override bool EnablePasswordRetrieval
        {
            get
            {
                return InnerMembershipProvider.EnablePasswordRetrieval;
            }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get
            {
                return InnerMembershipProvider.MaxInvalidPasswordAttempts;
            }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get
            {
                return InnerMembershipProvider.MinRequiredNonAlphanumericCharacters;
            }
        }

        public override int MinRequiredPasswordLength
        {
            get
            {
                return InnerMembershipProvider.MinRequiredPasswordLength;
            }
        }

        public override int PasswordAttemptWindow
        {
            get
            {
                return InnerMembershipProvider.PasswordAttemptWindow;
            }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get
            {
                return InnerMembershipProvider.PasswordFormat;
            }
        }

        public override string PasswordStrengthRegularExpression
        {
            get
            {
                return InnerMembershipProvider.PasswordStrengthRegularExpression;
            }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get
            {
                return InnerMembershipProvider.RequiresQuestionAndAnswer;
            }
        }

        public override bool RequiresUniqueEmail
        {
            get
            {
                return InnerMembershipProvider.RequiresUniqueEmail;
            }
        }

        private MembershipProvider InnerMembershipProvider { get; set; }
        private ISubstringsChecker<string> DictionaryWordsSubstringsChecker { get; set; }

        public PreventDictionaryWordPasswordsMembershipProvider()
            : this(CreateNewSqlMembershipProvider(), CreateNewDictionaryWordsSubstringsChecker())
        {
        }
        
        public PreventDictionaryWordPasswordsMembershipProvider(MembershipProvider innerMembershipProvider, ISubstringsChecker<string> dictionaryWordsSubstringsChecker)
        {
            SetInnerMembershipProvider(innerMembershipProvider);
            SetDictionaryWordsSubstringsChecker(dictionaryWordsSubstringsChecker);
        }

        private void SetInnerMembershipProvider(MembershipProvider innerMembershipProvider)
        {
            Assert.ArgumentNotNull(innerMembershipProvider, "innerMembershipProvider");
            InnerMembershipProvider = innerMembershipProvider;
        }

        private void SetDictionaryWordsSubstringsChecker(ISubstringsChecker<string> dictionaryWordsSubstringsChecker)
        {
            Assert.ArgumentNotNull(dictionaryWordsSubstringsChecker, "dictionaryWordsSubstringsChecker");
            DictionaryWordsSubstringsChecker = dictionaryWordsSubstringsChecker;
        }

        private static MembershipProvider CreateNewSqlMembershipProvider()
        {
            return new SqlMembershipProvider();
        }

        private static ISubstringsChecker<string> CreateNewDictionaryWordsSubstringsChecker()
        {
            return CreateNewStringSubstringsChecker(DictionaryWords);
        }

        private static ISubstringsChecker<string> CreateNewStringSubstringsChecker(IEnumerable<string> substrings)
        {
            Assert.ArgumentNotNull(substrings, "substrings");
            const bool ignoreCase = true;
            return StringSubstringsChecker.CreateNewStringSubstringsContainer(substrings, ignoreCase);
        }

        private static IEnumerable<string> GetDictionaryWords()
        {
            return Factory.GetStringSet("dictionaryWords/word");
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (DoesPasswordContainDictionaryWord(newPassword))
            {
                return false;
            }

            return InnerMembershipProvider.ChangePassword(username, oldPassword, newPassword);
        }

        private bool DoesPasswordContainDictionaryWord(string password)
        {
            Assert.ArgumentNotNullOrEmpty(password, "password");
            DictionaryWordsSubstringsChecker.Source = password;
            return DictionaryWordsSubstringsChecker.ContainsSubstrings();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            return InnerMembershipProvider.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (DoesPasswordContainDictionaryWord(password))
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            return InnerMembershipProvider.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
        }

        public override bool DeleteUser(string userName, bool deleteAllRelatedData)
        {
            return InnerMembershipProvider.DeleteUser(userName, deleteAllRelatedData);
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            return InnerMembershipProvider.FindUsersByEmail(emailToMatch, pageIndex, pageSize, out totalRecords);
        }

        public override MembershipUserCollection FindUsersByName(string userNameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            return InnerMembershipProvider.FindUsersByName(userNameToMatch, pageIndex, pageSize, out totalRecords);
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            return InnerMembershipProvider.GetAllUsers(pageIndex, pageSize, out totalRecords);
        }

        public override int GetNumberOfUsersOnline()
        {
            return InnerMembershipProvider.GetNumberOfUsersOnline();
        }

        public override string GetPassword(string username, string answer)
        {
            return InnerMembershipProvider.GetPassword(username, answer);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return InnerMembershipProvider.GetUser(providerUserKey, userIsOnline);
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return InnerMembershipProvider.GetUser(username, userIsOnline);
        }

        public override string GetUserNameByEmail(string email)
        {
            return InnerMembershipProvider.GetUserNameByEmail(email);
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            InnerMembershipProvider.Initialize(name, config);
        }

        public override string ResetPassword(string username, string answer)
        {
            return InnerMembershipProvider.ResetPassword(username, answer);
        }

        public override bool UnlockUser(string userName)
        {
            return InnerMembershipProvider.UnlockUser(userName);
        }

        public override void UpdateUser(MembershipUser user)
        {
            InnerMembershipProvider.UpdateUser(user);
        }

        public override bool ValidateUser(string username, string password)
        {
            return InnerMembershipProvider.ValidateUser(username, password);
        }
    }
}

In our MembershipProvider above, we have decorated the ChangePassword() and CreateUser() methods by employing a helper method to delegate to our DictionaryWordsSubstringsChecker instance — an instance of the StringSubstringsChecker class above — to see if the supplied password contains any of the fruits found in our collection, and prevent the workflow from moving forward in changing a user’s password, or creating a new user if one of the fruits is found in the provided password.

If we don’t find one of the fruits in the password, we then delegate to the inner MembershipProvider instance — this instance takes care of the rest around changing passwords, or creating new users.

I then had to register my MemberProvider in my Web.config — this cannot be placed in a patch include file since it lives outside of the <sitecore></sitecore> element.

<configuration>
	<membership defaultProvider="sitecore" hashAlgorithmType="SHA1">
		<providers>
			<clear/>
			<add name="sitecore" type="Sitecore.Security.SitecoreMembershipProvider, Sitecore.Kernel" realProviderName="sql" providerWildcard="%" raiseEvents="true"/>
			
			<!-- our new provider -->
			<add name="sql" type="Sitecore.Sandbox.Security.MembershipProviders.PreventDictionaryWordPasswordsMembershipProvider, Sitecore.Sandbox" connectionStringName="core" applicationName="sitecore" minRequiredPasswordLength="6" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="256"/>
			
			<add name="switcher" type="Sitecore.Security.SwitchingMembershipProvider, Sitecore.Kernel" applicationName="sitecore" mappings="switchingProviders/membership"/>
		</providers>
    </membership>
</configuration>

So, let’s see what the code above does.

I first tried to create a new user with a password containing a fruit.

new-user-lime

I then used a fruit that was not in the collection of fruits above, and successfully created my new user.

Next, I tried to change an existing user’s password to one that contains the word “apple”.

change-password-apples

I successfully changed this same user’s password using the word orange — it does not live in our collection of fruits above.

change-password-oranges

And that’s all there is to it. If you can think of alternative ways of doing this, or additional security features to implement, please drop a comment.

Until next time, have a Sitecoretastic day!

Add Content to All Sitecore Pages Using a Custom PageExtender

Out of the box, Sitecore creates and utilizes subclass instances of Sitecore.Layouts.PageExtenders.PageExtender — this class resides in Sitecore.Kernel.dll — to hook in functionality for Preview and Debugging features of the Page Editor — check out this post by John West where John discusses these — and all PageExtender instances are called upon to insert their controls onto pages via the PageExtenders pipeline processor in the renderLayout pipeline.

Last night, I hankered to explore the possibility of using a custom PageExtender outside of Sitecore’s Page Editor as an alternative route for placing content onto rendered pages in my local Sitecore sandbox instance.

I pretended I was meeting a business requirement for a fictitious company that has a website where important information is to be displayed in a big red box at the top of every page to its website visitors when applicable.

Before building my PageExtender, I defined a template for items that will contain these important messages. I named my template Alert — I probably could have chosen a better name but decided to continue this one:

alert-template

Alert items can contain alert copy in its Alert Text Single-Line Text field.

I then created an Alert item containing some important information for website visitors:

alert-item

Now that we have content, it’s time to build our PageExtender to display this content:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using Sitecore.Configuration;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Layouts;
using Sitecore.Layouts.PageExtenders;
using Sitecore.Sites;
using Sitecore.Web.UI.WebControls;

namespace Sitecore.Sandbox.Layouts.PageExtenders
{
    public class AlertBoxPageExtender : PageExtender
    {
        private static readonly string PlaceHolderKey = Settings.GetSetting("AlertBoxPageExtender.PlaceholderKey");
        private static readonly string AlertBoxID = Settings.GetSetting("AlertBoxPageExtender.AlertBoxID");
        private static readonly string AlertTextFieldName = Settings.GetSetting("AlertBoxPageExtender.AlertTextFieldName");

        private RenderingReference _AlertBoxRenderingReference;
        private RenderingReference AlertBoxRenderingReference
        {
            get
            {
                if (_AlertBoxRenderingReference == null)
                {
                    _AlertBoxRenderingReference = CreateNewAlertBoxRenderingReference();
                }

                return _AlertBoxRenderingReference;
            }
        }

        public override void Insert()
        {
            if (CanAddAlertBox())
            {
                Sitecore.Context.Page.AddRendering(AlertBoxRenderingReference);
            }
        }

        private bool CanAddAlertBox()
        {
            SiteContext site = Context.Site;
            return site != null 
                    && site.EnablePreview 
                    && site.DisplayMode == DisplayMode.Normal
                    && AlertBoxRenderingReference != null;
        }

        private RenderingReference CreateNewAlertBoxRenderingReference()
        {
            Control alertBoxControl = CreateAlertBoxControl();
            bool canCreateRenderingReference = alertBoxControl != null 
                                                && !string.IsNullOrEmpty(PlaceHolderKey);

            if (canCreateRenderingReference)
            {
                return CreateNewRenderingReference(CreateAlertBoxControl(), PlaceHolderKey);
            }

            return null;
        }

        private Control CreateAlertBoxControl()
        {
            Control alertBoxInnerControl = CreateNewAlertBoxInnerControl();
            if (alertBoxInnerControl != null)
            {
                Panel alertBoxPanel = new Panel();
                alertBoxPanel.CssClass = "alert-box";
                alertBoxPanel.Controls.Add(alertBoxInnerControl);
                return alertBoxPanel;
            }

            return null;
        }

        private Control CreateNewAlertBoxInnerControl()
        {
            Item alertBoxItem = TryGetAlertBoxItem();
            bool canCreateInnerPanel = alertBoxItem != null 
                                        && !string.IsNullOrEmpty(AlertTextFieldName) 
                                        && !string.IsNullOrEmpty(alertBoxItem[AlertTextFieldName]);

            if (canCreateInnerPanel)
            {
                Panel alertBoxInnerPanel = new Panel();
                alertBoxInnerPanel.Controls.Add(CreateNewFieldRenderer(alertBoxItem, AlertTextFieldName));
                return alertBoxInnerPanel;
            }

            return null;
        }

        private static FieldRenderer CreateNewFieldRenderer(Item item, string fieldName)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNullOrEmpty(fieldName, "fieldName");
            return new FieldRenderer { Item = item, FieldName = fieldName };
        }

        private static RenderingReference CreateNewRenderingReference(Control control, string placeholderKey)
        {
            Assert.ArgumentNotNull(control, "control");
            Assert.ArgumentNotNullOrEmpty(placeholderKey, "placeholderKey");
            RenderingReference renderingReference = new RenderingReference(control);
            renderingReference.Placeholder = placeholderKey;
            return renderingReference;
        }

        private Item TryGetAlertBoxItem()
        {
            try
            {
                return Sitecore.Context.Database.Items[AlertBoxID];
            }
            catch (Exception ex)
            {
                Log.Error(this.ToString(), ex, this);
            }

            return null;
        }
    }
}

The above PageExtender inserts an instance of a FieldRenderer — that will render content from our Alert item’s Alert Text field above — into nested ASP.NET Panels. I give the outer Panel a CSS class to position these ASP.NET controls at the top of the page, and decorate it with a red background and large white text font — I’ve omitted this CSS from this post for the sake of brevity.

The combined ASP.NET controls are then placed into an instance of the Sitecore.Layouts.RenderingReference class — also in Sitecore.Kernel.dll. This RenderingReference is tagged for insertion into the Sitecore placeholder I have defined in a setting within my patch include configuration file below:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pageextenders>
      <pageextender type="Sitecore.Sandbox.Layouts.PageExtenders.AlertBoxPageExtender, Sitecore.Sandbox"/>
    </pageextenders>
    <settings>
      <setting name="AlertBoxPageExtender.PlaceholderKey" value="main" />
      <setting name="AlertBoxPageExtender.AlertBoxID" value="{389D13C8-9475-4F5A-819B-78BA51C62326}" />
      <setting name="AlertBoxPageExtender.AlertTextFieldName" value="Alert Text" />
    </settings>
  </sitecore>
</configuration>

Let’s take this for a spin.

I created some page items and published. I then navigation to the first page item I created:

alert-box-front-end

As you can see, our red alert box displays at the top of the page.

I then navigated to the other page I created for testing:

some-other-page-alert-box

This page also contains our red alert box.

Now, lets remove the box. I deleted the copy from the Alert Text field in our Alert item in Sitecore, and published. I refreshed our second test webpage in my browser:

no-alert-text-no-alert-box

As you can see, our red alert box is now gone.

All of this is wonderful — inserting controls globally in this manner could potentially be a project saver when needing to add content to all pages in a pinch.

However, it’s also a double-edged sword. Such a solution might force the insertion of controls onto pages without the option of removing them using Sitecore’s presentation framework of adding/removing renderings.

Plus, developers who need to update this logic will have to fish around and find where this logic lives in your solution. Having to seek through the code-base to find where this logic lives could augment the time needed to complete the task of modifying this code — I’m not saying you don’t have excellent documentation articulating where this logic lives, although some people may not look at the documentation first, and will just start surfing through code to find it. I am guilty as charged for doing this myself. 🙂

Given these two salient factors, I would strongly recommend being conservative around using custom PageExtenders for displaying content on your Sitecore webpages.

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.