Home » 2020 » May

Monthly Archives: May 2020

Restart Your Sitecore Content Management (CM) and Content Delivery (CD) Instances using Custom Events

Last Friday, I had worked on a PowerShell script which is executed by clicking a custom button in the Sitecore Content Editor ribbon using the Content Editor Ribbon integration point offered through Sitecore PowerShell Extensions (SPE) in a UAT environment. This UAT environment has separate Content Management (CM) and Content Delivery (CD) Sitecore instances on two different servers. The script updates some records in an external datasource (data not in Sitecore) but its data is cached in the Sitecore instances outside of the stand Sitecore caching framework. In order to see these updates on the sites which live on these Sitecore instances , I needed a programmatic way to restart all Sitecore instances in the UAT environment I had built this solution for, and the following solution reflects what I had worked on to accomplish this spanning Friday until today — this post defines two custom events in Sitecore — just so I could get this out as soon as possible as it may help you understand custom events, and maybe even help you do something similar to what I am doing here.

I do want to caution you on using code as follows in a production environment — this could cause disruption to your production CDs which are live to the public; be sure to take your CD servers out of a load-balancer before restarting the Sitecore instance on them as you don’t want people showing up to your door with pitchforks and torches asking why production had been down for a bit.

I’ve also incorporated the concept of Sitecore configuration-driven feature toggles which I had discussed in a previous blog post where I had altered the appearance of the Sitecore content tree using a pipeline-backed MasterDataView, and will be repurposing code from that post here — I strongly suggest reading that post to understand the approach being used for this post as I will not discuss much how this works on this post.

Moreover, I have used numerous Configuration Objects sourced from the Sitecore IoC container in this post which I had discuss in another previous post; you might also want to have a read of that post before proceeding in order to understand why I am decorating some classes on this post with the [ServiceConfigObject] attribute.

I first defined the following Configuration Object which will live in the Sitecore IoC container:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;
using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Kernel.Models.RestartServer
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/restartServerSettings", Lifetime = Lifetime.Singleton)]
	public class RestartServerSettings : IFeatureToggleable
	{
		public bool Enabled { get; set; }
	}
}

This Configuration Object will act is the main feature toggle to turn the entire feature on/off based on the Enabled property’s value from Sitecore configuration (see the Sitecore patch configuration file towards the bottom of this post).

I then created the following interface which will ascertain when the entire feature should be turned on/off at a global level, or at an individual piece of functionality’s level:

using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Kernel.Services.RestartServer
{
	public interface IRestartServerFeatureToggleService
	{
		bool IsFeatureEnabled();

		bool IsEnabled(IFeatureToggleable toggleable);
	}
}

The following is the implementation of the interface above.

using Foundation.Kernel.Models.RestartServer;
using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Kernel.Services.RestartServer
{
	public class RestartServerFeatureToggleService : IRestartServerFeatureToggleService
	{
		private readonly RestartServerSettings _settings;
		private readonly IFeatureToggleService _featureToggleService;

		public RestartServerFeatureToggleService(RestartServerSettings settings, IFeatureToggleService featureToggleService)
		{
			_settings = settings;
			_featureToggleService = featureToggleService;
		}

		public bool IsEnabled(IFeatureToggleable toggleable) => _featureToggleService.IsEnabled(_settings, toggleable);

		public bool IsFeatureEnabled() => _featureToggleService.IsEnabled(_settings);
	}
}

I won’t explain much here as I had talked about feature toggles on a previous configuration-driven post; I suggest reading that to understand this pattern.

Now that we have our feature toggle magic defined above, let’s dive into the code which defines and handles custom events which do the actual restarting of the Sitecore instances.

I created the following Config Object to hold log messaging formatted strings which we will use when writing to the Sitecore log when restarting Sitecore instances:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.RestartServer.Events
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/restartServerEventHandlerSettings", Lifetime = Lifetime.Singleton)]
	public class RestartServerEventHandlerSettings
	{
		public string RestartServerLogMessageFormat { get; set; }

		public string RestartServerRemoteLogMessageFormat { get; set; }
	}
}

We need a way to identify the Sitecore instance we are on in order to determine if the Sitecore instance needs to be restarted, and also when logging information that a restart is happening on that instance. The following Config Object will provide the name of a Sitecore setting which holds thie identifier for the Sitecore instance we are on:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.Server
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/serverServiceSettings", Lifetime = Lifetime.Singleton)]
	public class ServerServiceSettings
	{
		public string InstanceNameSetting { get; set; }
	}
}

The following interface/implementation class will provide the name of the Sitecore instance we are on:

namespace Foundation.Kernel.Services.Server
{
	public interface IServerService
	{
		string GetCurrentServerName();
	}
}

Here’s the implementation of the interface above:

using Sitecore.Abstractions;

using Foundation.Kernel.Models.Server;

namespace Foundation.Kernel.Services.Server
{
	public class ServerService : IServerService
	{
		private readonly ServerServiceSettings _settings;
		private readonly BaseSettings _settingsProvider;

		public ServerService(ServerServiceSettings settings, BaseSettings settingsProvider)
		{
			_settings = settings;
			_settingsProvider = settingsProvider;
		}

		public string GetCurrentServerName() => GetSetting(GetInstanceNameSetting());

		protected virtual string GetInstanceNameSetting() => _settings.InstanceNameSetting;

		protected virtual string GetSetting(string settingName) => _settingsProvider.GetSetting(settingName);
	}
}

The class above consumes the ServerServiceSettings config object then uses the BaseSettings service to get the name of the Sitecore instance based on the value in the setting, and returns it to the caller. There’s really nothing more to it.

Back in 2014, I had written a post on restarting your Sitecore instance using a custom FileWatcher, and in that post I had used the RestartServer() method on the Sitecore.Install.Installer class in Sitecore.Kernel. I will be using this same class but backed by a service class. Here is the interface of that service class:

namespace Foundation.Kernel.Services.Installer
{
	public interface IInstallerService
	{
		void RestartServer();
	}
}

The following implements the interface above:

namespace Foundation.Kernel.Services.Installer
{
	public class InstallerService : IInstallerService
	{
		public void RestartServer() => Sitecore.Install.Installer.RestartServer();
	}
}

The class above just calls the RestartServer() method on the Sitecore.Install.Installer class; ultimately this just does a “touch” on your Web.config to recycle your Sitecore instance.

Like all good Sitecore custom events, we need a custom EventArgs class — well, you don’t really need one if you aren’t passing any data beyond what lives on the System.EventArgs class but I’m sure you will seldom come across such a scenario ๐Ÿ˜‰ — so I defined the following class to be just that class:

using System;
using System.Collections.Generic;

using Sitecore.Events;

namespace Foundation.Kernel.Models.RestartServer.Events
{
	[Serializable]
	public class RestartServerEventArgs : EventArgs, IPassNativeEventArgs
	{
		public List<string> ServerNames { get; protected set; }

		public RestartServerEventArgs(List<string> serverNames)
		{
			ServerNames = serverNames;
		}
	}
}

We will be passing a List of server names just in case there are multiple servers we would like to reboot simultaneously.

Now it’s time to create the event handlers. I created the following abstract class for my two event handler classes to have a centralized place for most of this logic:

using System;
using System.Linq;

using Sitecore.Abstractions;

using Foundation.Kernel.Models.RestartServer.Events;
using Foundation.Kernel.Services.Installer;
using Foundation.Kernel.Services.Server;
using Foundation.Kernel.Services.RestartServer;
using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Kernel.Events.RestartServer
{
	public abstract class BaseRestartServerEventHandler : IFeatureToggleable
	{
		private readonly RestartServerEventHandlerSettings _settings;
		private readonly IRestartServerFeatureToggleService _restartServerFeatureToggleService;
		private readonly IServerService _serverService;
		private readonly IInstallerService _installerService;
		private readonly BaseLog _log;

		public bool Enabled { get; set; }

		public BaseRestartServerEventHandler(RestartServerEventHandlerSettings settings, IRestartServerFeatureToggleService restartServerFeatureToggleService, IServerService serverService,  IInstallerService installerService, BaseLog log)
		{
			_settings = settings;
			_restartServerFeatureToggleService = restartServerFeatureToggleService;
			_serverService = serverService;
			_installerService = installerService;
			_log = log;
		}

		protected void ExecuteRestart(object sender, EventArgs args)
		{
			if(!IsEnabled())
			{
				return;
			}

			RestartServerEventArgs restartServerArgs = GetArguments<RestartServerEventArgs>(args);
			if (!ShouldRestartServer(restartServerArgs))
			{
				return;
			}

			string restartLogMessageFormat = GetRestartLogMessageFormat();
			if (!string.IsNullOrWhiteSpace(restartLogMessageFormat))
			{
				LogInfo(GetRestartServerMessage(restartLogMessageFormat, GetCurrentServerName()));
			}
			
			RestartServer();
		}

		protected virtual bool IsEnabled() => _restartServerFeatureToggleService.IsEnabled(this);

		protected abstract string GetRestartLogMessageFormat();

		protected virtual TArgs GetArguments<TArgs>(EventArgs args) where TArgs : EventArgs => args as TArgs;

		protected virtual bool ShouldRestartServer(RestartServerEventArgs restartServerArgs)
		{
			if(restartServerArgs.ServerNames == null || !restartServerArgs.ServerNames.Any())
			{
				return false;
			}

			string currentServerName = GetCurrentServerName();
			if (string.IsNullOrWhiteSpace(currentServerName))
			{
				return false;
			}

			return restartServerArgs.ServerNames.Any(serverName => string.Equals(serverName, currentServerName, StringComparison.OrdinalIgnoreCase));
		}

		protected virtual string GetCurrentServerName() => _serverService.GetCurrentServerName();

		protected virtual string GetRestartServerMessage(string messageFormat, string serverName) => string.Format(messageFormat, serverName);

		protected virtual void RestartServer() => _installerService.RestartServer();

		protected virtual void LogInfo(string message) => _log.Info(message, this);
	}
}

Subclasses of the class above will have methods to handle their events which will delegate to the ExecuteRestart() method. This method will use the feature toggle service class to determine if it should execute or not; if not, it just gracefully exits.

If it does proceed forward, the passed System.EventArgs class is casted as RestartServerEventArgs instance, and the current Sitecore instance’s name is checked against the collection server names in the RestartServerEventArgs instance. If the current server’s name is in the list, the server is restarted though proceeded by a log message indicating that the server is being restarted.

Subclasses of thie abstract class above must provide the log message formatted string so the log message can be written to the Sitecore log.

I then created the following interface for an event handler class to handle a local server restart:

using System;

namespace Foundation.Kernel.Events.RestartServer
{
	public interface IRestartLocalServerEventHandler
	{
		void OnRestartTriggered(object sender, EventArgs args);
	}
}

Here’s the implementation of the interface above:

using System;

using Sitecore.Abstractions;

using Foundation.Kernel.Models.RestartServer.Events;
using Foundation.Kernel.Services.Installer;
using Foundation.Kernel.Services.Server;
using Foundation.Kernel.Services.RestartServer;

namespace Foundation.Kernel.Events.RestartServer
{
	public class RestartLocalServerEventHandler : BaseRestartServerEventHandler, IRestartLocalServerEventHandler
	{
		private readonly RestartServerEventHandlerSettings _settings;

		public RestartLocalServerEventHandler(RestartServerEventHandlerSettings settings, IRestartServerFeatureToggleService restartServerFeatureToggleService, IServerService serverService, IInstallerService installerService, BaseLog log)
			: base(settings, restartServerFeatureToggleService, serverService, installerService, log)
		{
			_settings = settings;
		}

		public void OnRestartTriggered(object sender, EventArgs args) => ExecuteRestart(sender, args);

		protected override string GetRestartLogMessageFormat() => _settings.RestartServerLogMessageFormat;
	}
}

This subclass of the abstract class defined above just supplies its own log formatted message, and the rest of the logic is handled by its parent class.

I then created the following interface of an event handler class to remote events (those that run on CD servers):

using System;

namespace Foundation.Kernel.Events.RestartServer
{
	public interface IRestartRemoteServerEventHandler
	{
		void OnRestartTriggeredRemote(object sender, EventArgs args);
	}
}

The following class implements the interface above:

using System;

using Sitecore.Abstractions;

using Foundation.Kernel.Models.RestartServer.Events;
using Foundation.Kernel.Services.Installer;
using Foundation.Kernel.Services.Server;
using Foundation.Kernel.Services.RestartServer;

namespace Foundation.Kernel.Events.RestartServer
{
	public class RestartRemoteServerEventHandler : BaseRestartServerEventHandler, IRestartRemoteServerEventHandler
	{
		private readonly RestartServerEventHandlerSettings _settings;

		public RestartRemoteServerEventHandler(RestartServerEventHandlerSettings settings, IRestartServerFeatureToggleService restartServerFeatureToggleService, IServerService serverService,  IInstallerService installerService, BaseLog log)
			: base(settings, restartServerFeatureToggleService, serverService, installerService, log)
		{
			_settings = settings;
		}

		public void OnRestartTriggeredRemote(object sender, EventArgs args) => ExecuteRestart(sender, args);

		protected override string GetRestartLogMessageFormat() => _settings.RestartServerRemoteLogMessageFormat;
	}
}

Just as the previous event handler class had done, this class inherits from the abstract class defined above but just defines the GetRestartLogMessageFormat() method to provide its own log message formatted string; we need to identify that this was executed on a CD server in the Sitecore log.

In order to get remote events to work on your CD instances, you need to subscribe to your remote event on your CD server — this is done by listening for an instance of your custom EventArgs, we are using RestartServerEventArgs here, being sent across via the EventQueue — and then raise your custom remote event on our CD instance so your handlers are executed. The following code will be wrappers around static classes in the Sitecore API so I can use Dependency Injection in a custom <initialize> pipeline processor which ties all of this together with these injected service classes.

I will need to call methods on Sitecore.Events.Event in Sitecore.Kernel. I created the following interface/implementation for it:

using System;

using Sitecore.Events;

namespace Foundation.Kernel.Services.Events
{
	public interface IEventService
	{
		TParameter ExtractParameter<TParameter>(EventArgs args, int index) where TParameter : class;

		object ExtractParameter(EventArgs args, int index);

		void RaiseEvent(string eventName, IPassNativeEventArgs args);

		EventResult RaiseEvent(string eventName, params object[] parameters);
	}
}
using System;

using Sitecore.Events;

namespace Foundation.Kernel.Services.Events
{
	public class EventService : IEventService
	{
		public TParameter ExtractParameter<TParameter>(EventArgs args, int index) where TParameter : class => Event.ExtractParameter<TParameter>(args, index);

		public object ExtractParameter(EventArgs args, int index) => Event.ExtractParameter(args, index);

		public void RaiseEvent(string eventName, IPassNativeEventArgs args) => Event.RaiseEvent(eventName, args);

		public EventResult RaiseEvent(string eventName, params object[] parameters) => Event.RaiseEvent(eventName, parameters);
	}
}

I then created the following Config Object to provide the names of the two custom events (check out the patch configuration file at the end of this post to see what these values are):

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.RestartServer.Events
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/restartServerEventSettings", Lifetime = Lifetime.Singleton)]
	public class RestartServerEventSettings
	{
		public string RestartCurrentServerEventName { get; set; }

		public string RestartRemoteServerEventName { get; set; }
	}
}

Now, I need a way to raise events, both on a local Sitecore instance but also on a remote instance. I defined the following interface for such a service class:

namespace Foundation.Kernel.Services.Events
{
	public interface IEventTriggerer
	{
		void TriggerEvent(string eventName, params object[] parameters);

		void TriggerRemoteEvent<TEvent>(TEvent evt);

		void TriggerRemoteEvent<TEvent>(TEvent evt, bool triggerGlobally, bool triggerLocally);
	}
}

I then implemented the interface above:

using Sitecore.Abstractions;

namespace Foundation.Kernel.Services.Events
{
	public class EventTriggerer : IEventTriggerer
	{
		private readonly IEventService _eventService;
		private readonly BaseEventQueueProvider _eventQueueProvider; 
		
		public EventTriggerer(IEventService eventService, BaseEventQueueProvider eventQueueProvider)
		{
			_eventService = eventService;
			_eventQueueProvider = eventQueueProvider;
		}

		public void TriggerEvent(string eventName, params object[] parameters) => _eventService.RaiseEvent(eventName, parameters);

		public void TriggerRemoteEvent<TEvent>(TEvent evt) => _eventQueueProvider.QueueEvent(evt);

		public void TriggerRemoteEvent<TEvent>(TEvent evt, bool triggerGlobally, bool triggerLocally) => _eventQueueProvider.QueueEvent(evt, triggerGlobally, triggerLocally);
	}
}

The class above consumes the IEventService service class we defined above so that we can “trigger”/raise local events on the current Sitecore instance, and it also consumes the BaseEventQueueProvider service which comes with stock Sitecore so we can “trigger”/raise events to run on remote servers via the EventQueue.

I also need to use methods on the Sitecore.Eventing.EventManager class in Sitecore.Kernel. The following interface/implementation do just that:

using System;

using Sitecore.Eventing;

namespace Foundation.Kernel.Services.Events
{
	public interface IEventManagerService
	{
		SubscriptionId Subscribe<TEvent>(Action<TEvent> eventHandler);
	}
}
using System;

using Sitecore.Eventing;

namespace Foundation.Kernel.Services.Events
{
	public class EventManagerService : IEventManagerService
	{
		public SubscriptionId Subscribe<TEvent>(Action<TEvent> eventHandler) => EventManager.Subscribe(eventHandler);
	}
}

I do want to call out that there is an underlying service behind the Sitecore.Eventing.EventManager class in Sitecore.Kernel but it’s brought into this static class through some service locator method I had never seen before, and was afraid of traversing too much down this rabbit hole out of fear of sticking my hands into a hornets nest, or even worse, a nest of those murderer hornets we keep hearing about on the news these days; I felt it was best not to go much further into this today. ๐Ÿ˜‰

We can now dive into the <initialize> pipeline processor which binds the “subscribing and trigger remote event” functionality together.

I first created the following interface for the pipeline processor:

using Sitecore.Pipelines;

namespace Foundation.Kernel.Pipelines.Initialize.RestartServer
{
	public interface IRestartServerSubscriber
	{
		void Process(PipelineArgs args);
	}
}

I then implemented the interface above:

using System;

using Sitecore.Eventing;
using Sitecore.Pipelines;

using Foundation.Kernel.Services.Events;
using Foundation.Kernel.Services.FeatureToggle;
using Foundation.Kernel.Services.RestartServer;
using Foundation.Kernel.Models.RestartServer.Events;

namespace Foundation.Kernel.Pipelines.Initialize.RestartServer
{
	public class RestartServerSubscriber: IFeatureToggleable, IRestartServerSubscriber
	{
		private readonly RestartServerEventSettings _settings;
		private readonly IRestartServerFeatureToggleService _restartServerFeatureToggleService;
		private readonly IEventTriggerer _eventTriggerer;
		private readonly IEventManagerService _eventManagerService;

		public bool Enabled { get; set; }

		public RestartServerSubscriber(RestartServerEventSettings settings, IRestartServerFeatureToggleService restartServerFeatureToggleService, IEventTriggerer eventTriggerer, IEventManagerService eventManagerService)
		{
			_settings = settings;
			_restartServerFeatureToggleService = restartServerFeatureToggleService;
			_eventTriggerer = eventTriggerer;
			_eventManagerService = eventManagerService;
		}

		public void Process(PipelineArgs args)
		{
			if(!IsEnabled())
			{
				return;
			}

			Subscribe(GetRaiseRestartServerEventMethod());
		}

		protected virtual bool IsEnabled() => _restartServerFeatureToggleService.IsEnabled(this);

		protected virtual Action<RestartServerEventArgs> GetRaiseRestartServerEventMethod() => new Action<RestartServerEventArgs>(RaiseRestartServerEvent);

		protected virtual void RaiseRestartServerEvent(RestartServerEventArgs args) => RaiseEvent(GetRestartRemoteServerEventName(), args);

		protected virtual string GetRestartRemoteServerEventName() => _settings.RestartRemoteServerEventName;

		protected virtual void RaiseEvent(string eventName, params object[] parameters) => _eventTriggerer.TriggerEvent(eventName, parameters);

		protected virtual SubscriptionId Subscribe<TEvent>(Action<TEvent> eventHandler) => _eventManagerService.Subscribe(eventHandler);
	}
}

The Process() method of the pipeline processor class above uses the feature toggle service we had discuss earlier in this post to determine if it should execute or not.

If it can execute, it will subscribe to the remote event by listening for an RestartServerEventArgs instance being sent across by the EventQueue.

If it one is sent across, it will “trigger” (raise) the custom remote event on the CD server this pipeline processor lives on.

Are you still with me? ๐Ÿ˜‰

Now we need a service class which glues all of the stuff above into a nice simple API which we can call. I defined the following Config Object which will be consumed by this service class; this Config Object determines if Remote events should also run on local servers — I had set this up so I can turn this on for testing/troubleshooting/debugging on my local development instance:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.RestartServer.Events
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/restartServerRemoteEventSettings", Lifetime = Lifetime.Singleton)]
	public class RestartServerRemoteEventSettings
	{
		public bool TriggerRemoteEventLocally { get; set; }

		public bool TriggerRemoteEventGlobally { get; set; }
	}
}

The following interface is for our “simple” API for restarting Sitecore instances:

using System.Collections.Generic;

namespace Foundation.Kernel.Services.RestartServer
{
	public interface IRestartServerService
	{
		void RestartCurrentServer();

		void RestartRemoteServer(string serverName);

		void RestartRemoteServers(List<string> serverNames);
	}
}

Here’s the implementation of the interface above:

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

using Foundation.Kernel.Models.RestartServer.Events;
using Foundation.Kernel.Services.Events;
using Foundation.Kernel.Services.Server;

namespace Foundation.Kernel.Services.RestartServer
{
	public class RestartServerService : IRestartServerService
	{
		private readonly RestartServerEventSettings _eventSettings;
		private readonly RestartServerRemoteEventSettings _remoteEventSettings;
		private readonly IRestartServerFeatureToggleService _restartServerFeatureToggleService;
		private readonly IServerService _serverService;
		private readonly IEventTriggerer _eventTriggerer;

		public RestartServerService(RestartServerEventSettings eventSettings, RestartServerRemoteEventSettings remoteEventSettings, IRestartServerFeatureToggleService restartServerFeatureToggleService, IServerService serverService, IEventTriggerer eventTriggerer)
		{
			_eventSettings = eventSettings;
			_remoteEventSettings = remoteEventSettings;
			_restartServerFeatureToggleService = restartServerFeatureToggleService;
			_serverService = serverService;
			_eventTriggerer = eventTriggerer;
		}

		public void RestartCurrentServer()
		{
			if(!IsFeatureEnabled())
			{
				return;
			}

			TriggerEvent(GetRestartCurrentServerEventName(), CreateRestartServerEventArgs(CreateList(GetCurrentServerName())));
		}

		protected virtual string GetRestartCurrentServerEventName() => _eventSettings.RestartCurrentServerEventName;

		protected virtual string GetCurrentServerName() => _serverService.GetCurrentServerName();

		public void RestartRemoteServer(string serverName) => RestartRemoteServers(CreateList(serverName));

		protected virtual List<string> CreateList(params string[] values) => values?.ToList();

		public void RestartRemoteServers(List<string> serverNames)
		{
			if (!IsFeatureEnabled())
			{
				return;
			}

			TriggerRemoteEvent(CreateRestartServerEventArgs(serverNames));
		}
			

		protected virtual bool IsFeatureEnabled() => _restartServerFeatureToggleService.IsFeatureEnabled();

		protected virtual RestartServerEventArgs CreateRestartServerEventArgs(List<string> serverNames) => new RestartServerEventArgs(serverNames);

		protected virtual void TriggerEvent(string eventName, params object[] parameters) => _eventTriggerer.TriggerEvent(eventName, parameters);

		protected virtual void TriggerRemoteEvent<TEvent>(TEvent evt) => _eventTriggerer.TriggerRemoteEvent(evt, GetTriggerRemoteEventGlobally(), GetTriggerRemoteEventGlobally());

		protected virtual bool GetTriggerRemoteEventGlobally() => _remoteEventSettings.TriggerRemoteEventGlobally;

		protected virtual bool GetTriggerRemoteEventLocally() => _remoteEventSettings.TriggerRemoteEventLocally;
	}
}

The class above implements methods for restarting the current server, one remote server, or multiple remote servers — ultimately, it just delegates to the IEventTriggerer service class we defined further above, and uses other services discussed earlier in this post; there’s really not much to it.

I then stitched everything above together in the following Sitecore patch configuration file:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
	<sitecore>
		<events>
			<event name="server:restart">
				<handler type="Foundation.Kernel.Events.RestartServer.IRestartLocalServerEventHandler, Foundation.Kernel" method="OnRestartTriggered" resolve="true">
					<Enabled>true</Enabled>
				</handler>
			</event>
			<event name="server:restart:remote">
				<handler type="Foundation.Kernel.Events.RestartServer.IRestartRemoteServerEventHandler, Foundation.Kernel" method="OnRestartTriggeredRemote" resolve="true">
					<Enabled>true</Enabled>
				</handler>
			</event>
		</events>
		<pipelines>
			<initialize>
				<processor type="Foundation.Kernel.Pipelines.Initialize.RestartServer.IRestartServerSubscriber, Foundation.Kernel" resolve="true">
					<Enabled>true</Enabled>
				</processor>
			</initialize>
		</pipelines>
		<moduleSettings>
			<foundation>
				<kernel>
					<serverServiceSettings type="Foundation.Kernel.Models.Server.ServerServiceSettings, Foundation.Kernel" singleInstance="true">
						<InstanceNameSetting>InstanceName</InstanceNameSetting>
					</serverServiceSettings>
					<restartServerSettings type="Foundation.Kernel.Models.RestartServer.RestartServerSettings, Foundation.Kernel" singleInstance="true">
						<Enabled>true</Enabled>
					</restartServerSettings>
					<restartServerEventHandlerSettings type="Foundation.Kernel.Models.RestartServer.Events.RestartServerEventHandlerSettings, Foundation.Kernel" singleInstance="true">
						<RestartServerLogMessageFormat>Restart Server Event Triggered: Shutting down server {0}</RestartServerLogMessageFormat>
						<RestartServerRemoteLogMessageFormat>Restart Server Remote Event Triggered: Shutting down server {0}</RestartServerRemoteLogMessageFormat>
					</restartServerEventHandlerSettings>
					<restartServerEventSettings type="Foundation.Kernel.Models.RestartServer.Events.RestartServerEventSettings, Foundation.Kernel" singleInstance="true">
						<RestartCurrentServerEventName>server:restart</RestartCurrentServerEventName>
						<RestartRemoteServerEventName>server:restart:remote</RestartRemoteServerEventName>
					</restartServerEventSettings>
					<restartServerRemoteEventSettings type="Foundation.Kernel.Models.RestartServer.Events.RestartServerRemoteEventSettings, Foundation.Kernel" singleInstance="true">
						<!-- setting this to "true" so I can test/debug locally -->
						<TriggerRemoteEventLocally>true</TriggerRemoteEventLocally>
						<TriggerRemoteEventGlobally>true</TriggerRemoteEventGlobally>
					</restartServerRemoteEventSettings>
			</kernel>
			</foundation>
		</moduleSettings>
		<services>

			<!-- General Services -->
			<register
				serviceType="Foundation.Kernel.Services.Installer.IInstallerService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.Installer.InstallerService, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Services.Server.IServerService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.Server.ServerService, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Services.RestartServer.IRestartServerFeatureToggleService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.RestartServer.RestartServerFeatureToggleService, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Services.RestartServer.IRestartServerService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.RestartServer.RestartServerService, Foundation.Kernel"
				lifetime="Singleton" />
			
			<!-- Event Related Services -->
			<register
				serviceType="Foundation.Kernel.Services.Events.IEventService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.Events.EventService, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Services.Events.IEventManagerService, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.Events.EventManagerService, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Services.Events.IEventTriggerer, Foundation.Kernel"
				implementationType="Foundation.Kernel.Services.Events.EventTriggerer, Foundation.Kernel"
				lifetime="Singleton" />

			<!-- Event Handler Services -->
			
			<register
				serviceType="Foundation.Kernel.Events.RestartServer.IRestartLocalServerEventHandler, Foundation.Kernel"
				implementationType="Foundation.Kernel.Events.RestartServer.RestartLocalServerEventHandler, Foundation.Kernel"
				lifetime="Singleton" />
			<register
				serviceType="Foundation.Kernel.Events.RestartServer.IRestartRemoteServerEventHandler, Foundation.Kernel"
				implementationType="Foundation.Kernel.Events.RestartServer.RestartRemoteServerEventHandler, Foundation.Kernel"
				lifetime="Singleton" />

			<!-- Pipeline Processor Services -->
			<register
				serviceType="Foundation.Kernel.Pipelines.Initialize.RestartServer.IRestartServerSubscriber, Foundation.Kernel"
				implementationType="Foundation.Kernel.Pipelines.Initialize.RestartServer.RestartServerSubscriber, Foundation.Kernel"
				lifetime="Singleton" />
		</services>
		<settings>

			<!-- This is set here for testing. Ideally, you would have this set for every Sitecore instance you have in your specific custom patch file where identify your server -->
			<setting name="InstanceName">
				<patch:attribute name="value">Sandbox</patch:attribute>
			</setting>
		</settings>
	</sitecore>
</configuration>

Considering I had built this to be executed from a PowerShell script hooked into a custom button through the Content Editor Ribbon integration point via Sitecore PowerShell Extensions (SPE), I will be testing this using two simple PowerShell scripts; both will be executed from the Sitecore PowerShell Extensions ISE (why yes, Sitecore MVP Michael West, I had tested this on SPE v6.1.1 ๐Ÿ˜‰ ):

Let’s see how we did.

Let’s test this by restarting the current Sitecore instance:

$serviceType = [Foundation.Kernel.Services.RestartServer.IRestartServerService]
$service = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider.GetService($serviceType) -as $serviceType  #use service locator to get the IRestartServerService service
$service.RestartCurrentServer() #Let's call the method to restart the current server (CM)

As expected, my Sitecore instance froze up as it was restarting. I then saw this in my logs:

Let’s now restart the remote Sitecore instance:

$serviceType = [Foundation.Kernel.Services.RestartServer.IRestartServerService]
$service = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider.GetService($serviceType) -as $serviceType  #use service locator to get the IRestartServerService service
$service.RestartRemoteServer("Sandbox")  #Let's call the method to restart the remote server (CD)

Also as expected, my Sitecore instance froze up as it was restarting — remember, I am testing this on a single development instance of Sitecore where I don’t have a separate CM and CD . I then saw this in my logs:

Let me know if you have questions/comments/fears/dreams/hopes/apsirations/whatever by dropping a comment. ๐Ÿ˜‰

Turn the Key to Open the Door on Possibilities using the Key Attribute with the Sitecore Configuration Factory

So I wanted to dig a little bit further into some code I had shared on a previous post which taps into functionality of the Sitecore Configuration Factory which you may/may not be aware of but I’ll discuss it regardless as someone might benefit from this (I’m not aware of another post discussing this but if you know of one, drop a link to it in the comments below so we can web them together).

Btw, don’t fret — this will be one of my shortest blog posts in history, so you’ll be able to finish it over a coffee break. ๐Ÿ˜‰

The gist of this post is that you can leverage the Sitecore Configuration Factory to help you populate a Dictionary instance where you set the key and value pair in your Sitecore Configuration patch file — I’m sure there are other possiblies on using this feature but populating a Dictionary is where i have used this most often.

Wait, key attribute? What are you talking about Mike?!

The Sitecore configuration Factory looks specifically for an attribute named “key” in child elements of a parent element where either hint=”list:SomeMethod” or “hint=”raw:SomeMethod” are defined in your configuration; I’m sure you’ve used both hint=”list” and/or hint=”raw” for setting Lists in your class instances but this is a bit different. Let’s see how.

When using hint=”list:SomeMethod” with the “key” attribute set on child xml nodes, your method signature should look like this when you are just retrieving a string value from a child element:

void SomeMethod(string key, string value) // hey, this looks like we are set up to populate a Dictionary

If you are creating a key/value pair with a value which is more complex (i.e. you set the type attribute with the fully qualified type of some object on the child element, it should look like this:

void SomeMethod(string key, SomeClassYouDefined someObject) // no way, this also looks like we are set up to populate a Dictionary!

When using hint=”raw:SomeMethod”, your signature would look similarly to other methods you would define with “raw” but with the addition of the key string:

void SomeMethod(string key, XmlNode someNode) // wait, another method which could set us up for populating a Dictionary?!

Let’s look at the code you might have missed in that previous post where I had use this; you might have to go re-read it — or maybe just read it ๐Ÿ˜‰ — to fully understand some of the other objects/classes being used below. I’m not going to explain what this interface and its class are for as I had done this in my previous post but will add code comments describing how this Configuration Factory feature works.

Consider the following interface:

using Foundation.Kernel.Models.Client;

namespace Foundation.Kernel.Services.Client
{
	public interface IClientCommandService
	{
		string GetClientCommand(string name, params string[] arguments);

		Command GetCommand(string name);
	}
}

Here’s the implementation of the interface above:

using System.Collections.Generic;

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

using Foundation.Kernel.Models.Client;

namespace Foundation.Kernel.Services.Client
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/clientCommandService ", ServiceType = typeof(IClientCommandService), Lifetime = Lifetime.Singleton)]
	public class ClientCommandService : IClientCommandService
	{
		private readonly IDictionary<string, Command> _commands = new Dictionary<string, Command>();

		/* This method will be referenced in the configuration file below, and the Configuration Factory will call it */
		protected void AddClientCommand(string key, Command command)
		{
			if(string.IsNullOrWhiteSpace(key) || command == null)
			{
				return;
			}

			_commands[key] = command; // I'm adding the object instantiated by the Configuration Factory in a Dictionary on this class
		}

		public string GetClientCommand(string name, params string[] arguments)
		{
			string commandFormat = GetCommandFormat(name);
			if(string.IsNullOrWhiteSpace(commandFormat))
			{
				return string.Empty;
			}

			return string.Format(commandFormat, arguments);
		}

		protected virtual string GetCommandFormat(string name) => GetCommand(name)?.CommandFormat;

		public Command GetCommand(string name) => _commands[name];
	}
}

Here’s the Sitecore Configuration patch file which ties this all together (there are xml comments discussing how this ties to the subject of this blog post):

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
	<services>
		<configurator type="Foundation.Kernel.Configurators.KernelConfigurator, Foundation.Kernel"/>
	</services>
	<moduleSettings>
		<foundation>
			<kernel>
				<clientCommandService type="Foundation.Kernel.Services.Client.ClientCommandService, Foundation.Kernel" singleInstance="true">
					<!-- the AddClientCommand(string key, Command command) method will be invoked -->
					<Commands hint="list:AddClientCommand">
						<!-- I set a key attribute with a type attribute so the Configuration Factory will expect a method of this signature:

							AddClientCommand(string key, Foundation.Kernel.Models.Client.Command command)

							A Commmand instance will be created for the object defined below by the Configuration Factory, and passed to the AddClientCommand method on the ClientCommandService instance above.
						-->
						<command key="item:load" type="Foundation.Kernel.Models.Client.Command, Foundation.Kernel">
							<Name>$(key)</Name> <!-- don't be thrown off by this $(key) here as it's just a context token where its value is put on an instance of Foundation.Kernel.Models.Client.Command, and not related to the Configuration Factory feature being discussed here -->
							<CommandFormat>item:load(id={0})</CommandFormat>
						</command>
					</Commands>
				</clientCommandService>
			</kernel>
		</foundation>
	</moduleSettings>
</sitecore>
</configuration>

Let me know if you have questions/comments/good movie recommendations ๐Ÿ˜‰

Until next time, have a Sitecoretastic day!

Yet Another Post on Sitecore Content Editor Warnings

Over the years, I’ve written posts on adding custom Content Editor Warnings. Content Editor Warnings give visual cues at the top of an Item in the Content Editor to either take action on something about the Item, or to just convey information about the Item — perhaps the Item is read-only, or maybe there is something wrong with the item; you can do all kinds of stuff with these, just use your imagination on what you would like to convey to your content authors.

The way to add these is to create a custom processor for the <getContentEditorWarnings> pipeline in Sitecore. There really isn’t anything more to it.

Moreover, you can even use Sitecore PowerShell Extensions to create these though I did not do this for this post. Sorry, Sitecore MVP Michael West. ๐Ÿ˜‰

Today, I am sharing a recent example of two Content Editor Warnings which I had worked on which convey to content authors they almost have, or have too many child items within a Media Library folder.

Some code on this post reuses service classes found on my previous post where I discussed how to create a custom MasterDataView driven by a custom pipeline; I recommend having a read of that previous post first before proceeding further in order to have complete grounding on some of the service classes I am using in the solution below.

I had to make a tweak to the ITooManySubItemsService service found on my previous post — I had to make the GetNumberOfItemsToStartWarningUser() and GetMaximumNumberOfItemsInFolder() methods public as I needed to get these two values within the Content Editor Warnings in order to display these values in messages to the content authors via the Content Editor Warning. This service determines these values based on a Config Object service which can also be overriden by each individual piece of functionality in my solution (i.e. the maximum number of child items set on the pipeline processor would override the Config Object service’s value):

using Foundation.Validation.Models.TooManySubItems;

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsService
	{
		bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters);

		bool HasTooManySubItems(TooManySubItemsServiceParameters parameters);

		int GetNumberOfItemsToStartWarningUser(TooManySubItemsServiceParameters parameters); // I've added this 

		int GetMaximumNumberOfItemsInFolder(TooManySubItemsServiceParameters parameters); // I've added this 
	}
}

Here is the modified implementation of the interface above. All I did was change the signature on GetNumberOfItemsToStartWarningUser() and GetMaximumNumberOfItemsInFolder() to be public instead of protected:

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

using Sitecore.Data.Items;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems;

namespace Feature.Validation.Services.TooManySubItems
{
	public class TooManySubItemsService : ITooManySubItemsService
	{
		private readonly TooManySubItemsSettings _settings; 

		public TooManySubItemsService(TooManySubItemsSettings settings)
		{
			_settings = settings;
		}

		public bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters)
		{
			int numberOfItemsToStartWarningUser = GetNumberOfItemsToStartWarningUser(parameters);
			int maximumNumberOfItemsInFolder = GetMaximumNumberOfItemsInFolder(parameters);
			if (parameters?.Item == null || numberOfItemsToStartWarningUser < 1 || maximumNumberOfItemsInFolder < 1)
			{
				return false;
			}

			IEnumerable<Item> items = GetItemsWithoutTemplateIds(parameters?.Item.Children, parameters?.TemplateIdsToIgnore);
			return items.Count() >= numberOfItemsToStartWarningUser && items.Count() < maximumNumberOfItemsInFolder;
		}

		public bool HasTooManySubItems(TooManySubItemsServiceParameters parameters)
		{
			int maximumNumberOfItemsInFolder = GetMaximumNumberOfItemsInFolder(parameters);
			if (parameters?.Item == null || maximumNumberOfItemsInFolder < 1)
			{
				return false;
			}

			IEnumerable<Item> items = GetItemsWithoutTemplateIds(parameters?.Item.Children, parameters?.TemplateIdsToIgnore);
			return items.Count() >= maximumNumberOfItemsInFolder;
		}

		public int GetNumberOfItemsToStartWarningUser(TooManySubItemsServiceParameters parameters)
		{
			if (parameters == null || _settings == null)
			{
				return 0;
			}

			if (parameters.NumberOfItemsToStartWarningUser > 0)
			{
				return parameters.NumberOfItemsToStartWarningUser;
			}

			return _settings.NumberOfItemsToStartWarningUser;
		}

		public int GetMaximumNumberOfItemsInFolder(TooManySubItemsServiceParameters parameters)
		{
			if (parameters == null || _settings == null)
			{
				return 0;
			}

			if (parameters.MaximumNumberOfItemsInFolder > 0)
			{
				return parameters.MaximumNumberOfItemsInFolder;
			}

			return _settings.MaximumNumberOfItemsInFolder;
		}

		protected virtual IEnumerable<Item> GetItemsWithoutTemplateIds(IEnumerable<Item> items, IEnumerable<string> templateIds)
		{
			if (items == null)
			{
				return Enumerable.Empty<Item>();
			}

			if(templateIds == null || !templateIds.Any())
			{
				return items;
			}

			return items.Where(item => templateIds.All(templateId => templateId != item.TemplateID.ToString())).ToList();
		}
	}
}

The processors which are defined below will give content authors the ability to take action on the Content Editor Warnings. The options are basically just as collection of link text and Sheer UI commands. In this example, content authors are given the option to create new Media Library folders. The following class is used when sourcing these from each processor’s configuration definition (see the Sitecore patch configuration file further down in this post):

namespace Foundation.Kernel.Models.Pipelines.ContentEditorWarnings
{
	public class ContentEditorWarningOption
	{
		public string Text { get; set; }
		
		public string Link { get; set; }
	}
}

Since the two Content Editor Warning processors are doing very similiar things, I abstracted out most of their logic into a base abstract class, and put it hooks for overriding methods on it; this is an example of the Template Method Pattern for you Design Pattern junkies ๐Ÿ˜‰

using System.Collections.Generic;

using Sitecore.Data.Items;
using Sitecore.Pipelines.GetContentEditorWarnings;

using Foundation.Kernel.Models.Pipelines.ContentEditorWarnings;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems.Factories;
using Foundation.Validation.Services.TooManySubItems;
using Foundation.Kernel.Services.FeatureToggle;

namespace Feature.ContentEditor.Pipelines.GetContentEditorWarnings
{
	public abstract class BaseTooManyChildItemsWarningProcessor : IFeatureToggleable, ITooManySubItemsFeature
	{
		private readonly ITooManySubItemsFeatureToggleService _tooManySubItemsFeatureToggleService;
		private readonly ITooManySubItemsServiceParametersFactory _tooManySubItemsServiceParametersFactory;
		private readonly ITooManySubItemsService _tooManySubItemsService;

		public bool Enabled { get; set; }

		protected string MediaLibraryBasePath { get; set; }

		public List<string> TemplateIdsToIgnore { get; set; } = new List<string>();

		public int NumberOfItemsToStartWarningUser { get; set; }

		public int MaximumNumberOfItemsInFolder { get; set; }

		protected List<ContentEditorWarningOption> ContentEditorWarningOptions { get; set; } = new List<ContentEditorWarningOption>();

		public BaseTooManyChildItemsWarningProcessor(ITooManySubItemsFeatureToggleService tooManySubItemsFeatureToggleService, ITooManySubItemsServiceParametersFactory tooManySubItemsServiceParametersFactory, ITooManySubItemsService tooManySubItemsService)
		{
			_tooManySubItemsFeatureToggleService = tooManySubItemsFeatureToggleService;
			_tooManySubItemsServiceParametersFactory = tooManySubItemsServiceParametersFactory;
			_tooManySubItemsService = tooManySubItemsService;
		}

		public void Process(GetContentEditorWarningsArgs args)
		{
			if(!IsEnabled() || !IsInMediaLibrary(args?.Item))
			{
				return;
			}

			TooManySubItemsServiceParameters parameters = CreateParameters(args?.Item, this);
			if(parameters == null)
			{
				return;
			}

			if(!ShouldDisplayWarning(parameters))
			{
				return;
			}

			int maximumNumberOfItemsInFolder = GetMaximumNumberOfItemsInFolder(parameters);
			string warningTitle = GetWarningTitle(args, maximumNumberOfItemsInFolder);
			string warningMessage = GetWarningMessage(args, maximumNumberOfItemsInFolder);
			AddWarning(args, warningTitle, warningMessage, ContentEditorWarningOptions);
		}

		protected virtual bool IsEnabled() => _tooManySubItemsFeatureToggleService.IsEnabled(this);

		protected virtual bool IsInMediaLibrary(Item item)
		{
			if(string.IsNullOrWhiteSpace(item.Paths.FullPath))
			{
				return false;
			}

			return item.Paths.FullPath.Contains(MediaLibraryBasePath);
		}

		protected virtual TooManySubItemsServiceParameters CreateParameters(Item item, ITooManySubItemsFeature feature) => _tooManySubItemsServiceParametersFactory.CreateParameters(item, feature);

		protected abstract bool ShouldDisplayWarning(TooManySubItemsServiceParameters parameters);

		protected abstract string GetWarningTitle(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder);

		protected abstract string GetWarningMessage(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder);

		protected virtual int GetMaximumNumberOfItemsInFolder(TooManySubItemsServiceParameters parameters) =>_tooManySubItemsService.GetMaximumNumberOfItemsInFolder(parameters);

		protected virtual bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters) => _tooManySubItemsService.HasAlmostTooManySubItems(parameters);

		protected virtual bool HasTooManySubItems(TooManySubItemsServiceParameters parameters) => _tooManySubItemsService.HasTooManySubItems(parameters);

		protected virtual void AddWarning(GetContentEditorWarningsArgs args, string title, string message, IEnumerable<ContentEditorWarningOption> options)
		{
			if(args == null)
			{
				return;
			}
			
			GetContentEditorWarningsArgs.ContentEditorWarning warning = CreateNewContentEditorWarning(args); 
			if(warning == null)
			{
				return;
			}

			warning.Title = title;
			warning.Text = message;
			AddOptions(warning, options);
		}

		protected virtual GetContentEditorWarningsArgs.ContentEditorWarning CreateNewContentEditorWarning(GetContentEditorWarningsArgs args) => args?.Add();

		protected virtual void AddOptions(GetContentEditorWarningsArgs.ContentEditorWarning warning, IEnumerable<ContentEditorWarningOption> options)
		{
			if(warning == null || options == null)
			{
				return;
			}

			foreach(ContentEditorWarningOption option in options)
			{
				if(string.IsNullOrWhiteSpace(option.Text) || string.IsNullOrWhiteSpace(option.Link)) continue;
				warning.AddOption(option.Text, option.Link);
			}
		}
	}
}

The class above will only display the Content Editor Warning when the feature is enabled (see my previous post where I discuss how this works using Sitecore configuration feature toggles); the item is in the Media Library; and the ShouldDisplayWarning() method returns true — this must be implemented by subclasses of this abstract base class.

If the Content Editor Warning should display, the Content Editor Warning’s title is retrieved via the GetWarningTitle() method, and its message is retrieved via the GetWarningMessage() method — both of these methods must be implemented by its subclasses.

These are then added to the a new GetContentEditorWarningsArgs.ContentEditorWarning instance created from the GetContentEditorWarningsArgs instance with the options defined in the configuration for the processor.

I then created the following interface for the purposes of registering its implementation in the Sitecore IoC container; this is optional as you could just register it with its implementation type being its service type.

using Sitecore.Pipelines.GetContentEditorWarnings;

namespace Feature.ContentEditor.Pipelines.GetContentEditorWarnings
{
	public interface IAlmostTooManyChildItemsWarningProcessor
	{
		void Process(GetContentEditorWarningsArgs args);
	}
}

Here is the implementation of the interface above. This is the processor class to show content authors when they are approaching too many child items:

using Sitecore.Pipelines.GetContentEditorWarnings;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems.Factories;
using Foundation.Validation.Services.TooManySubItems;

namespace Feature.ContentEditor.Pipelines.GetContentEditorWarnings
{
	public class AlmostTooManyChildItemsWarningProcessor : BaseTooManyChildItemsWarningProcessor, IAlmostTooManyChildItemsWarningProcessor
	{
		private string AlmostAtMaxiumTitle { get; set; }

		private string AlmostAtMaxiumMessageFormat { get; set; }

		public AlmostTooManyChildItemsWarningProcessor(ITooManySubItemsFeatureToggleService tooManySubItemsFeatureToggleService, ITooManySubItemsServiceParametersFactory tooManySubItemsServiceParametersFactory, ITooManySubItemsService tooManySubItemsService)
			: base(tooManySubItemsFeatureToggleService, tooManySubItemsServiceParametersFactory, tooManySubItemsService)
		{
		}

		protected override bool ShouldDisplayWarning(TooManySubItemsServiceParameters parameters) => HasAlmostTooManySubItems(parameters);

		protected override string GetWarningTitle(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder) => AlmostAtMaxiumTitle;

		protected override string GetWarningMessage(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder) => string.Format(AlmostAtMaxiumMessageFormat, args?.Item?.Children?.Count, maximumNumberOfItemsInFolder);
	}
}

The implementation above is using the AlmostAtMaxiumTitle and AlmostAtMaxiumMessageFormat strings set via the Sitecore Configuration Factory onto the class instance; these are used when displaying messaging to content authors.

Also, this implementation is using the HasAlmostTooManySubItems() method defined on its base class which ultimately makes a call to the ITooManySubItemsService service class to ascertain whether the folder/item almost has too many child items.

Just as I had done above, I created an interface for the other Content Editor Warning, only for the purpose of registering it in the Sitecore IoC container.

using Sitecore.Pipelines.GetContentEditorWarnings;

namespace Feature.ContentEditor.Pipelines.GetContentEditorWarnings
{
	public interface ITooManyChildItemsWarningProcessor
	{
		void Process(GetContentEditorWarningsArgs args);
	}
}

Here is the implementation of the interface above:

using Sitecore.Pipelines.GetContentEditorWarnings;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems.Factories;
using Foundation.Validation.Services.TooManySubItems;

namespace Feature.ContentEditor.Pipelines.GetContentEditorWarnings
{
	public class TooManyChildItemsWarningProcessor : BaseTooManyChildItemsWarningProcessor, ITooManyChildItemsWarningProcessor
	{
		private string AtMaxiumTitle { get; set; }

		private string AtMaxiumMessageFormat { get; set; }

		public TooManyChildItemsWarningProcessor(ITooManySubItemsFeatureToggleService tooManySubItemsFeatureToggleService, ITooManySubItemsServiceParametersFactory tooManySubItemsServiceParametersFactory, ITooManySubItemsService tooManySubItemsService)
			: base(tooManySubItemsFeatureToggleService, tooManySubItemsServiceParametersFactory, tooManySubItemsService)
		{
		}

		protected override bool ShouldDisplayWarning(TooManySubItemsServiceParameters parameters) => HasTooManySubItems(parameters);

		protected override string GetWarningTitle(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder) => AtMaxiumTitle;

		protected override string GetWarningMessage(GetContentEditorWarningsArgs args, int maximumNumberOfItemsInFolder) => string.Format(AtMaxiumMessageFormat, args?.Item?.Children?.Count, maximumNumberOfItemsInFolder);
	}
}

The class above is using the AtMaxiumTitle and AtMaxiumMessageFormat strings set via the Sitecore Configuration Factory from the processor’s configuration definition (see the Sitecore configuration patch file below for both processor definitions), and uses the HasTooManySubItems() method defined on the base class which also just delegates to the ITooManySubItemsService service class.

I then registered everything above in the following Sitecore patch configuration file:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
	<sitecore>
		<pipelines>
			<getContentEditorWarnings>
				<processor type="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.IAlmostTooManyChildItemsWarningProcessor, Feature.ContentEditor" patch:before="processor[1]" resolve="true">
					<Enabled>true</Enabled>
					<MediaLibraryBasePath>/sitecore/media library/</MediaLibraryBasePath>
					<AlmostAtMaxiumTitle>This Item Almost Has Too Many Subitems Underneath It!</AlmostAtMaxiumTitle>
					<AlmostAtMaxiumMessageFormat>This item has {0} media libary items underneath it!  The maximum number of subitems allowed is {1}. Consider creating a new media library folder at this time.</AlmostAtMaxiumMessageFormat>
					<!-- By setting these, you can override the default values set for the entire feature set
										<NumberOfItemsToStartWarningUser>95</NumberOfItemsToStartWarningUser>
										<MaximumNumberOfItemsInFolder>100</MaximumNumberOfItemsInFolder>
					-->
					<ContentEditorWarningOptions hint="list">
						<Option type="Foundation.Kernel.Models.Pipelines.ContentEditorWarnings.ContentEditorWarningOption, Foundation.Kernel">
							<Text>New Media Folder</Text>
							<Link>media:newfolder</Link>
						</Option>
					</ContentEditorWarningOptions>
				</processor>
				<processor type="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.ITooManyChildItemsWarningProcessor, Feature.ContentEditor" patch:before="processor[1]" resolve="true">
					<Enabled>true</Enabled>
					<MediaLibraryBasePath>/sitecore/media library/</MediaLibraryBasePath>
					<AtMaxiumTitle>This Item Has Too Many Subitems Underneath It!</AtMaxiumTitle>
					<AtMaxiumMessageFormat>This item has {0} media libary items underneath it! The maximum number of subitems allowed is {1}. It's time to create a new media library folder for more items to upload.</AtMaxiumMessageFormat>
					<!-- By setting these, you can override the default values set for the entire feature set
										<NumberOfItemsToStartWarningUser>95</NumberOfItemsToStartWarningUser>
										<MaximumNumberOfItemsInFolder>100</MaximumNumberOfItemsInFolder>
					-->
					<ContentEditorWarningOptions hint="list">
						<Option type="Foundation.Kernel.Models.Pipelines.ContentEditorWarnings.ContentEditorWarningOption, Foundation.Kernel">
							<Text>New Media Folder</Text>
							<Link>media:newfolder</Link>
						</Option>
					</ContentEditorWarningOptions>
				</processor>
			</getContentEditorWarnings>	
		</pipelines>
		<services>
			<register
				serviceType="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.IAlmostTooManyChildItemsWarningProcessor, Feature.ContentEditor"
				implementationType="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.AlmostTooManyChildItemsWarningProcessor, Feature.ContentEditor"
				lifetime="Singleton" />
			<register
				serviceType="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.ITooManyChildItemsWarningProcessor, Feature.ContentEditor"
				implementationType="Feature.ContentEditor.Pipelines.GetContentEditorWarnings.TooManyChildItemsWarningProcessor, Feature.ContentEditor"
				lifetime="Singleton" />
		</services>
	</sitecore>
</configuration>

Let’s see what these two processors do.

When looking at an Item which is approaching too many child items, we see the following:

When we have a look at an Item which has more than the maximum number set for child items, we see the following:

Please drop a comment if you have questions/comments, or would like to share how you’ve used Content Editor Warnings on projects you have worked on.

Alter the Appearance of the Sitecore Content Tree using a Pipeline-backed MasterDataView

About 4 years ago, I blogged about creating a custom MasterDataView class to change the appearance of Items in the content tree.

One thing that bugged me back then was how this particular piece of Sitecore functionality wasn’t backed by a pipeline of some sort which gave me an idea on creating a custom MasterDataView which would delegate to a custom pipeline to alter how Items display in the content tree but I never got to it; as a matter of fact, I forgot all about it once I moved to Australia at the time — it’s easy to forget things when you are trying to dodge viscious magpies and venomous spiders ๐Ÿ˜‰

However, I recently rethought of this idea due to a project I had worked on where I had to notify content authors that they had almost or too many child items in Media Folders in the Media Library. In this post, I am going to share this solution with you, and it heavily uses code from my previous post — I suggest having a read of that before proceeding.

I also want to call out that I’ve omitted code which registers most services used on this post in the Sitecore IoC container for brevity. If you want to learn about Dependency Injection on Sitecore, I highly recommend watching this presentation on YouTube.

Like any Sitecore pipeline, we need a PipelineArgs class of some sort, and the following is just that:

using Sitecore.Collections;
using Sitecore.Data.Items;
using Sitecore.Pipelines;

namespace Foundation.Kernel.Pipelines.DataViewChildItems
{
	public class DataViewChildItemsArgs : PipelineArgs
	{
		public ItemCollection Children { get; set; }

		public Item Parent { get; set; }

		public DataViewChildItemsArgs()
		{
		}

		public DataViewChildItemsArgs(ItemCollection children, Item parent)
		{
			Children = children;
			Parent = parent;
		}
	}
}

The GetChildItems() method on Sitecore.Web.UI.HtmlControls.MasterDataView, or those which inherit from it, take in an ItemCollection of children and their parent Item in the content tree. This is why I have these two properties on the DataViewChildItemsArgs class above — we are going to pass these to all processors of our custom pipeline.

On my recent project, I wanted to give the ability to have things be turned on and off via a feature toggle in Sitecore configuration, both at a global and invidual piece functionality level (i.e. have a global settings object with an Enabled property but also another Enabled property on each pipeline processor so we can turn the entire thing off, or just a piece of it).

The follow interface is to go with each bit of functionality that can be turned on/off:

namespace Foundation.Kernel.Services.FeatureToggle
{
	public interface IFeatureToggleable
	{
		bool Enabled { get; set; }
	}
}

We also need a service to read these Enabled properties, and determine if something should be turned on/off. The following is the interface for this service:

namespace Foundation.Kernel.Services.FeatureToggle
{
	public interface IFeatureToggleService
	{
		bool IsEnabled(params IFeatureToggleable[] toggleables);
	}
}

Here’s the implementation of the interface above:

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

namespace Foundation.Kernel.Services.FeatureToggle
{
	public class FeatureToggleService : IFeatureToggleService
	{
		public bool IsEnabled(params IFeatureToggleable[] toggleables) => !ShouldTurnOff(toggleables);

		protected virtual bool ShouldTurnOff(IEnumerable<IFeatureToggleable> toggleables)
		{
			if (toggleables == null || !toggleables.Any())
			{
				return true;
			}

			return toggleables.Any(toggleable => !toggleable.Enabled);
		}
	}
}

It takes in a collection of IFeatureToggleable, and returns false if any of the IFeatureToggleable has an Enabled property value of “false”.

I then define a base class for pipeline processors of the custom pipeline:

using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Kernel.Pipelines.DataViewChildItems
{
	public abstract class DataViewChildItemsProcessor : IFeatureToggleable
	{
		private readonly IFeatureToggleService _featureToggleService;

		public bool Enabled { get; set; }

		protected bool AbortPipelineAfterExecution { get; set; }

		protected DataViewChildItemsProcessor(IFeatureToggleService featureToggleService)
		{
			_featureToggleService = featureToggleService;
		}

		public void Process(DataViewChildItemsArgs args)
		{
			if (!IsEnabled() || !ShouldExecute(args))
			{
				return;
			}

			GetChildItems(args);
			if (!ShouldAbortPipeline(args))
			{
				return;
			}

			args.AbortPipeline();
		}

		protected virtual bool IsEnabled() => _featureToggleService.IsEnabled(this);

		protected abstract bool ShouldExecute(DataViewChildItemsArgs args);

		protected abstract void GetChildItems(DataViewChildItemsArgs args);

		protected virtual bool ShouldAbortPipeline(DataViewChildItemsArgs args) => AbortPipelineAfterExecution;
	}
}

Any pipeline processor which implements the base class above must consume the IFeatureToggleService instance above — ideally from the Sitecore IoC container which I have done further down below but you could also use Poor Man’s DI for this which I do not recommend as we have a native IoC container in Sitecore ๐Ÿ˜‰

Now, let’s dive into setting up the custom MasterDataView. The following Config Object are settings for this class, and it contains values for both the custom pipeline’s domain and the pipeline’s name (I decided to group this by pipeline domain as I can see entry points on other overridable methods on the MasterDataView class which could be driven by other custom pipelines in this domain):

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.DataViews
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/pipelineDrivenDataViewSettings", Lifetime = Lifetime.Singleton)]
	public class PipelineDrivenDataViewSettings
	{
		public string PipelineDomain { get; set; }

		public string PipelineName { get; set;  }
	}
}

I then created the following MasterDataView which inherits from the OOTB Sitecore.Buckets.Forms.BucketDataView in Sitecore.Buckets.dll as the OOTB MasterDataView which ships with Sitecore is this one — I could have gone ahead and created yet another pipeline processor for Buckets but I decided against this for now:

using Sitecore.Abstractions;
using Sitecore.Buckets.Forms;
using Sitecore.Collections;
using Sitecore.Data.Items;
using Sitecore.DependencyInjection;

using Foundation.Kernel.Pipelines.DataViewChildItems;
using Foundation.Kernel.Models.DataViews;

namespace Foundation.Kernel.DataViews
{
	public class PipelineDrivenDataView : BucketDataView
	{
		protected override void GetChildItems(ItemCollection children, Item parent)
		{
			base.GetChildItems(children, parent);
			DataViewChildItemsArgs args = CreateDataViewChildItemsArgs(children, parent);
			if(args == null)
			{
				return;
			}

			ICorePipeline corePipeline = GetService<ICorePipeline>();
			PipelineDrivenDataViewSettings settings = GetSettings();

			if (corePipeline == null || string.IsNullOrWhiteSpace(settings?.PipelineDomain) || string.IsNullOrWhiteSpace(settings?.PipelineName))
			{
				return;
			}

			corePipeline.Run(settings.PipelineName, args, settings.PipelineDomain);
		}

		protected virtual ICorePipeline GetCorePipeline() => GetService<ICorePipeline>();

		protected virtual PipelineDrivenDataViewSettings GetSettings() => GetService<PipelineDrivenDataViewSettings>();

		protected virtual TService GetService<TService>() where TService : class => ServiceLocator.ServiceProvider.GetService(typeof(TService)) as TService;

		protected virtual DataViewChildItemsArgs CreateDataViewChildItemsArgs(ItemCollection children, Item parent) => new DataViewChildItemsArgs(children, parent);
	}
}

The MasterDataView above creates a new DataViewChildItemsArgs instance by passing the Children ItemCollection and parent; the custom pipeline will ultimately modify just the Children collection but I built this being mindful that other pipeline processors might need to change the Parent Item for their purposes; I just don’t have this as an example on this post.

This DataViewChildItemsArgs instance is then passed to a call to the custom pipeline within the defined domain.

I then defined the new pipeline along with the custom MasterDataView, both defined above, in the Sitecore configuration patch file below:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
	<sitecore>
		<dataviews>
			<dataview name="Master">
				<patch:attribute name="assembly">Foundation.Kernel</patch:attribute>
				<patch:attribute name="type">Foundation.Kernel.DataViews.PipelineDrivenDataView</patch:attribute>
			</dataview>
		</dataviews>
		<moduleSettings>
			<foundation>
				<kernel>
					<pipelineDrivenDataViewSettings type="Foundation.Kernel.Models.DataViews.PipelineDrivenDataViewSettings, Foundation.Kernel" singleInstance="true">
						<PipelineDomain>masterDataView</PipelineDomain>
						<PipelineName>dataviewChildItems</PipelineName >
					</pipelineDrivenDataViewSettings>
				</kernel>
			</foundation>
		</moduleSettings>
		<pipelines>
			<group groupName="masterDataView" name="masterDataView">
				<pipelines>
					<dataviewChildItems>
					</dataviewChildItems>
				</pipelines>
			</group>
		</pipelines>
	</sitecore>
</configuration>

I wanted to abstract out the logic which determines if an Item has almost or too many child items as the project I was working on had more than one customization of the content editor to let content authors know it’s time to create a new folder for their items — dont worry I’ll blog about some of these in the future ๐Ÿ˜‰ — so I defined the following interface for turning these individual bits of functionality on and off:

using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsFeatureToggleService
	{
		bool IsEnabled(IFeatureToggleable toggleable);
	}
}

Here’s the implementation of the IFeatureToggleable interface above — this is a service Config Object which will be the global settings object to turn on and off the entire feature set of these Content Editor customizations — and will be injected into the implementation of the ITooManySubItemsFeatureToggleService further below:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

using Foundation.Kernel.Services.FeatureToggle;

namespace Foundation.Validation.Models.TooManySubItems
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/validation/tooManySubItemsSettings ", Lifetime = Lifetime.Singleton)]
	public class TooManySubItemsSettings : IFeatureToggleable
	{
		public bool Enabled { get; set; }

		public int NumberOfItemsToStartWarningUser{ get; set; }

		public int MaximumNumberOfItemsInFolder { get; set; }
	}
}

The Config Object above also has values on the number of child items on when to start warning the content authors they have almost too many child items, and also a value on when there are too many child items.

I then defined the TooManySubItemsSettings Config Object in the Sitecore patch configuration file below:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
	<sitecore>
		<moduleSettings>
			<foundation>
				<validation>
					<tooManySubItemsSettings type="Foundation.Validation.Models.TooManySubItems.TooManySubItemsSettings, Foundation.Validation" singleInstance="true">
						<Enabled>true</Enabled>
						<!-- <MaximumNumberOfItemsInFolder> must be set and greater than zero in order for the feature to work.  In other words, default Sitecore functionality will execute 
							when this isn't set (it's essentially like setting <Enabled>false</Enabled> above; you can't warn users they are approaching a maximum number of items in a folder
							when there is no maximum value set.
						-->
						<NumberOfItemsToStartWarningUser>2</NumberOfItemsToStartWarningUser>
						<MaximumNumberOfItemsInFolder>4</MaximumNumberOfItemsInFolder>
					</tooManySubItemsSettings>
				</validation>
			</foundation>
		</moduleSettings>
	</sitecore>
</configuration>

For testing, I set the values on when to warning content authors to a low number for testing but ideally, MaximumNumberOfItemsInFolder should be 100 child Items, and I chose 95 child Items for NumberOfItemsToStartWarningUser in the production version of this.

Now, we need an implementation of the ITooManySubItemsFeatureToggleService interface above. The following is just that:

using Foundation.Kernel.Services.FeatureToggle;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems;

namespace Feature.Validation.Services.TooManySubItems
{
	public class TooManySubItemsFeatureToggleService : ITooManySubItemsFeatureToggleService
	{
		private readonly TooManySubItemsSettings _settings;
		private readonly IFeatureToggleService _featureToggleService;

		public TooManySubItemsFeatureToggleService(TooManySubItemsSettings settings, IFeatureToggleService featureToggleService)
		{
			_settings = settings;
			_featureToggleService = featureToggleService;
		}

		public bool IsEnabled(IFeatureToggleable toggleable) => _featureToggleService.IsEnabled(_settings, toggleable);
	}
}

The class above will delegate to the IFeatureToggleService instance to determine if the entire feature set of visual cues to the content authors should be turned on/off, or if an invidual piece of functionality should be turned on/off; each IFeatureToggleable will also pass itself to this service so that it can determine whether it should be turned on/off.

Most of the features I had built for this will warn content authors for when they are approaching too many child Items and also convey there are too many child items but there were a few where I only had to let content authors know when they had reached the maximum number of child Items under an item. Due to this, I broke all of these values out into the following interfaces:

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsMaxItemsInFolderFeature
	{
		int MaximumNumberOfItemsInFolder { get; set; }
	}
}

The above interface is only for features which will let the content authors know when they are reached too many child Items.

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsWarnUserFeature
	{
		int NumberOfItemsToStartWarningUser { get; set; }
	}
}

The ITooManySubItemsWarnUserFeature is only for features that will warn users that they approaching too many child Items.

using System.Collections.Generic;

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsFeature : ITooManySubItemsMaxItemsInFolderFeature, ITooManySubItemsWarnUserFeature
	{
		List<string> TemplateIdsToIgnore { get; set; }
	}
}

The above interface is an amalgam of the two interfaces above, and also includes a collection of Template IDs to ignore during the almost or has too many child Items check — I had included this in case there are reasons for ignoring certain child Items with certain templates but am not using this in this blog post.

Due to the need of passing a bunch of stuff to the service which determines that an Item has almost or too many child Items, I created the following parameters object class:

using System.Collections.Generic;

using Sitecore.Data.Items;

namespace Foundation.Validation.Models.TooManySubItems
{
	public class TooManySubItemsServiceParameters
	{
		public Item Item { get; set; }

		public int NumberOfItemsToStartWarningUser { get; set; }

		public int MaximumNumberOfItemsInFolder { get; set; }

		public List<string> TemplateIdsToIgnore { get; set; } = new List<string>();
	}
}

I then created a factory object to create TooManySubItemsServiceParameters instances above. The following is an interface for this service:

using System.Collections.Generic;

using Sitecore.Data.Items;

using Foundation.Validation.Models.TooManySubItems;

namespace Foundation.Validation.Services.TooManySubItems.Factories
{
	public interface ITooManySubItemsServiceParametersFactory
	{
		TooManySubItemsServiceParameters CreateParameters(TooManySubItemsCommandServiceParameters parameters); // not used in this post; I will discuss in a future post
		
		TooManySubItemsServiceParameters CreateParameters(Item item, ITooManySubItemsFeature feature);

		TooManySubItemsServiceParameters CreateParameters(Item item, int numberOfItemsToStartWarningUser, int maximumNumberOfItemsInFolder, List<string> templateIdsToIgnore);
	}
}

Here’s the implementation of the interface above:

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

using Sitecore.Data.Items;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems.Factories;

namespace Feature.Validation.Services.TooManySubItems.Factories
{
	public class TooManySubItemsServiceParametersFactory : ITooManySubItemsServiceParametersFactory
	{
		// not used in this post; I will discuss in a future post
		public TooManySubItemsServiceParameters CreateParameters(TooManySubItemsCommandServiceParameters parameters) => CreateParameters(GetItem(parameters), 0, parameters.Feature.MaximumNumberOfItemsInFolder, parameters.TemplateIdsToIgnore);

		protected virtual Item GetItem(TooManySubItemsCommandServiceParameters parameters) => parameters?.Context.Items.FirstOrDefault();

		public TooManySubItemsServiceParameters CreateParameters(Item item, ITooManySubItemsFeature feature) => CreateParameters(item, feature.NumberOfItemsToStartWarningUser, feature.MaximumNumberOfItemsInFolder, feature.TemplateIdsToIgnore);

		public TooManySubItemsServiceParameters CreateParameters(Item item, int numberOfItemsToStartWarningUser, int maximumNumberOfItemsInFolder, List<string> templateIdsToIgnore)
		{ 
			return new TooManySubItemsServiceParameters
			{
				Item = item,
				NumberOfItemsToStartWarningUser = numberOfItemsToStartWarningUser,
				MaximumNumberOfItemsInFolder = maximumNumberOfItemsInFolder,
				TemplateIdsToIgnore = templateIdsToIgnore
			};
		}
	}
}

It’s basically just creating TooManySubItemsServiceParameters instances based on values passed.

We are ready to define the service which determines if an Item has almost or too many child Items. The following interface is for that service:

using Foundation.Validation.Models.TooManySubItems;

namespace Foundation.Validation.Services.TooManySubItems
{
	public interface ITooManySubItemsService
	{
		bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters);

		bool HasTooManySubItems(TooManySubItemsServiceParameters parameters);
	}
}

The following is the implementation of the interface defined above:

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

using Sitecore.Data.Items;

using Foundation.Validation.Models.TooManySubItems;
using Foundation.Validation.Services.TooManySubItems;

namespace Feature.Validation.Services.TooManySubItems
{
	public class TooManySubItemsService : ITooManySubItemsService
	{
		private readonly TooManySubItemsSettings _settings; 

		public TooManySubItemsService(TooManySubItemsSettings settings)
		{
			_settings = settings;
		}

		public bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters)
		{
			int numberOfItemsToStartWarningUser = GetNumberOfItemsToStartWarningUser(parameters);
			int maximumNumberOfItemsInFolder = GetMaximumNumberOfItemsInFolder(parameters);
			if (parameters?.Item == null || numberOfItemsToStartWarningUser < 1 || maximumNumberOfItemsInFolder < 1)
			{
				return false;
			}

			IEnumerable<Item> items = GetItemsWithoutTemplateIds(parameters?.Item.Children, parameters?.TemplateIdsToIgnore);
			return items.Count() >= numberOfItemsToStartWarningUser && items.Count() < maximumNumberOfItemsInFolder;
		}

		public bool HasTooManySubItems(TooManySubItemsServiceParameters parameters)
		{
			int maximumNumberOfItemsInFolder = GetMaximumNumberOfItemsInFolder(parameters);
			if (parameters?.Item == null || maximumNumberOfItemsInFolder < 1)
			{
				return false;
			}

			IEnumerable<Item> items = GetItemsWithoutTemplateIds(parameters?.Item.Children, parameters?.TemplateIdsToIgnore);
			return items.Count() >= maximumNumberOfItemsInFolder;
		}

		protected virtual int GetNumberOfItemsToStartWarningUser(TooManySubItemsServiceParameters parameters)
		{
			if (parameters == null || _settings == null)
			{
				return 0;
			}

			if (parameters.NumberOfItemsToStartWarningUser > 0)
			{
				return parameters.NumberOfItemsToStartWarningUser;
			}

			return _settings.NumberOfItemsToStartWarningUser;
		}

		protected virtual int GetMaximumNumberOfItemsInFolder(TooManySubItemsServiceParameters parameters)
		{
			if (parameters == null || _settings == null)
			{
				return 0;
			}

			if (parameters.MaximumNumberOfItemsInFolder > 0)
			{
				return parameters.MaximumNumberOfItemsInFolder;
			}

			return _settings.MaximumNumberOfItemsInFolder;
		}

		protected virtual IEnumerable<Item> GetItemsWithoutTemplateIds(IEnumerable<Item> items, IEnumerable<string> templateIds)
		{
			if (items == null)
			{
				return Enumerable.Empty<Item>();
			}

			if(templateIds == null || !templateIds.Any())
			{
				return items;
			}

			return items.Where(item => templateIds.All(templateId => templateId != item.TemplateID.ToString())).ToList();
		}
	}
}

The HasAlmostTooManySubItems() method above determines if the passed Item has almost too many child items but not greater than or equal to the maximum number of child items as that check is governed by the HasTooManySubItems() method — it determines if the number of child items equals or exceeds the maximum number of child Items passed via the Parameters object; both of these methods only look at Items who do not have Template IDs which are in the TemplateIdsToIgnore list though we are not using this on this blog post.

Since we are modifying the appear of Item names in the Content Tree, I wanted to put markup for this in a nice place. I decided to use Handlebars.Net for this solution — in an earlier iteration of this project, I had this markup in a Sitecore configuration file all HTML encoded but it seemed like a cumbersome solution especially if the markup had to be changed so I went with this alternative approach instead as I had a good experience using Handlebars.Net over 2 years ago — but to my dismay, the current version of Handlebars.Net did not come with its OOTB ViewEngineFileSystem any longer as older versions had, so I had to create one myself. This required me to create the following service class for dealing with files but I’m ultimately just delegating to methods on Sitecore.IO.FileUtil (this lives in Sitecore.Kernel.dll) through this service:

namespace Foundation.Kernel.Services.IO
{
	public interface IFileUtilService
	{
		bool Exists(string path);

		string MakePath(string part1, string part2);

		string ReadFromFile(string path);
	}
}

The following implements the interface above but just delegates to methods on Sitecore.IO.FileUtil:

using Sitecore.IO;

namespace Foundation.Kernel.Services.IO
{
	public class FileUtilService : IFileUtilService
	{
		public bool Exists(string path) => FileUtil.Exists(path);

		public string MakePath(string part1, string part2) => FileUtil.MakePath(part1, part2);

		public string ReadFromFile(string path) => FileUtil.ReadFromFile(path);
	}
}

I then created a subclass of HandlebarsDotNet.ViewEngineFileSystem; this adapter class talks to the file system for HandlebarsDotNet:

using HandlebarsDotNet;

using Foundation.Kernel.Services.IO;

namespace Feature.Token.Services
{
	public class HandlebarsViewEngineFileSystem : ViewEngineFileSystem
	{
		private readonly IFileUtilService _fileUtilService;

		public HandlebarsViewEngineFileSystem(IFileUtilService fileUtilService)
		{
			_fileUtilService = fileUtilService;
		}

		public override bool FileExists(string filePath) => _fileUtilService.Exists(filePath);

		public override string GetFileContent(string filename) => _fileUtilService.ReadFromFile(filename);

		protected override string CombinePath(string dir, string otherFileName) => _fileUtilService.MakePath(dir, otherFileName);
	}
}

I then wrapped HandlebarsDotNet’s main static class in a service class so I can inject things together using DI. The following interface is for this service class:

using System;
using System.IO;

using HandlebarsDotNet;

namespace Feature.Token.Services
{
	public interface IHandlebarsService
	{
		Action<TextWriter, object> Compile(TextReader template);

		Func<object, string> Compile(string template);

		Func<object, string> CompileView(string templatePath);

		void RegisterHelper(string helperName, HandlebarsHelper helperFunction);

		void RegisterHelper(string helperName, HandlebarsBlockHelper helperFunction);

		void RegisterTemplate(string templateName, Action<TextWriter, object> template);

		void RegisterTemplate(string templateName, string template);
	}
}

We now need to implement the interface above:

using System;
using System.IO;

using HandlebarsDotNet;

namespace Feature.Token.Services
{
	public class HandlebarsService : IHandlebarsService
	{
		private ViewEngineFileSystem _viewEngineFileSystem;

		public HandlebarsService(ViewEngineFileSystem viewEngineFileSystem)
		{
			_viewEngineFileSystem = viewEngineFileSystem;
		}

		private readonly object _locker = new object();
		private IHandlebars _instance;
		private IHandlebars Instance
		{
			get
			{
				if(_instance  == null)
				{
					lock(_locker)
					{
						_instance = Create();
					}
				}

				return _instance;
			}
		}

		private IHandlebars Create(HandlebarsConfiguration configuration = null)
		{
			IHandlebars handlebars = Handlebars.Create(configuration);
			handlebars.Configuration.FileSystem = _viewEngineFileSystem;
			return handlebars;
		}

		public Action<TextWriter, object> Compile(TextReader template) => Instance.Compile(template);

		public Func<object, string> Compile(string template) => Instance.Compile(template);

		public Func<object, string> CompileView(string templatePath) => Instance.CompileView(templatePath);

		public void RegisterHelper(string helperName, HandlebarsHelper helperFunction) => Instance.RegisterHelper(helperName, helperFunction);

		public void RegisterHelper(string helperName, HandlebarsBlockHelper helperFunction) => Instance.RegisterHelper(helperName, helperFunction);

		public void RegisterTemplate(string templateName, Action<TextWriter, object> template) => Instance.RegisterTemplate(templateName, template);

		public void RegisterTemplate(string templateName, string template) => Instance.RegisterTemplate(templateName, template);
	}
}

I’m injecting the ViewEngineFileSystem service — this is an instance of the HandlebarsViewEngineFileSystem above but I stick it into the IoC contain with a service type of ViewEngineFileSystem — into this class so we can create a new IHandlebars instance using Handlebars’s Create() method, and then it gets stored in an internal Singleton in the class.

Next, we need a service to replace tokens (no, not Sitecore tokens such as $name, $id, etc) but tokens in handlebars template strings or files:

using System.Collections.Generic;

namespace Foundation.Token.Services
{
	public interface ITemplatedTokenReplacer
	{
		string ReplaceTokens(string input, IDictionary<string, string> tokens);

		string ReplaceTokens(string templateSource, object tokens);

		string ReplaceTokensFromView(string viewPath, IDictionary<string, string> tokens);

		string ReplaceTokensFromView(string viewPath, object tokens);

		void ClearAllCaches();

		void ClearTemplateCache();

		void ClearViewsCache();
	}
}

The implementation of the interface above will need to “cache” compiled Handlebars.Net templates as the documentation calls out that compiling their templates is an expensive operation and recommend caching these compilations so I am using the following interface to create services which cache things:

namespace Foundation.Kernel.Services.Cache
{
    public interface ICacher<TKey, TObject>
    {
        void Add(TKey key, TObject obj);

        bool ContainsKey(TKey key);

        TObject Get(TKey key);

        void Clear();
    }
}

Classes which implement this base class below will be caching their things in a ConcurrentDictionary:

using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Foundation.Kernel.Services.Cache
{
    public abstract class Cacher<TKey, TObject>
    {
        private IDictionary<TKey, TObject> _cache;

        protected Cacher()
        {
            _cache = CreateCache();
        }

        protected virtual IDictionary<TKey, TObject> CreateCache() => new ConcurrentDictionary<TKey, TObject>();

        public void Add(TKey key, TObject obj) => _cache[key] = obj;

        public TObject Get(TKey key) => ContainsKey(key) ? _cache[key] : default(TObject);

        public bool ContainsKey(TKey key) => _cache.ContainsKey(key);

        public void Clear() => _cache.Clear();
    }
}

We will be caching compilations of Handlebars.Net template strings:

using System;

using Foundation.Kernel.Services.Cache;

namespace Feature.Token.Services.Cachers
{
	public interface ICompiledTemplateCache : ICacher<string, Func<object, string>>
	{
	}
}
using System;

using Foundation.Kernel.Services.Cache;

namespace Feature.Token.Services.Cachers
{
	public class CompiledTemplateCache : Cacher<string, Func<object, string>>, ICompiledTemplateCache
	{
	}
}

We will also be caching compilations of Handlebars.Net template strings sourced from files:

using System;

using Foundation.Kernel.Services.Cache;

namespace Feature.Token.Services.Cachers
{
	public interface ICompiledViewTemplateCache : ICacher<string, Func<object, string>>
	{
	}
}
using System;

using Foundation.Kernel.Services.Cache;

namespace Feature.Token.Services.Cachers
{
	public class CompiledViewTemplateCache : Cacher<string, Func<object, string>>, ICompiledViewTemplateCache
	{

	}
}

Finally, we can talk about the implemenation of ITemplatedTokenReplacer ๐Ÿ˜‰ :

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;

using HandlebarsDotNet;

using Foundation.Token.Services;

using Feature.Token.Services.Cachers;

namespace Feature.Token.Services
{
	public class HandlebarsTokenReplacer : ITemplatedTokenReplacer
	{
		private readonly IHandlebarsService _handlebarsService;

		private readonly ICompiledTemplateCache _compiledTemplateCache;
		private readonly ICompiledViewTemplateCache _compiledViewTemplateCache;

		public HandlebarsTokenReplacer(IHandlebarsService handlebarsService, ICompiledTemplateCache compiledTemplateCache, ICompiledViewTemplateCache compiledViewTemplateCache)
		{
			_handlebarsService = handlebarsService;
			_compiledTemplateCache = compiledTemplateCache;
			_compiledViewTemplateCache = compiledViewTemplateCache;
		}

		public string ReplaceTokens(string input, IDictionary<string, string> tokens) => ReplaceTokens(input, (object)tokens);

		public string ReplaceTokens(string templateSource, object tokens)
		{
			var compiled = GetCompiledTemplateFromCache(templateSource);
			if (compiled == null)
			{
				compiled = Compile(templateSource);
				AddCompiledTemplateToCache(templateSource, compiled);
			}

			return ReplaceTokens(compiled, tokens);
		}

		protected virtual Func<object, string> GetCompiledTemplateFromCache(string templateSource) => _compiledTemplateCache.Get(templateSource);

		protected virtual Func<object, string> Compile(string viewPath) => _handlebarsService.Compile(viewPath);

		protected virtual void AddCompiledTemplateToCache(string templateSource, Func<object, string> compiled) => _compiledTemplateCache.Add(templateSource, compiled);

		protected virtual string ReplaceTokens(Func<object, string> template, object tokens)
		{
			if(template == null)
			{
				return string.Empty;
			}

			return template(tokens);
		}

		public string ReplaceTokensFromView(string viewPath, IDictionary<string, string> tokens) => ReplaceTokensFromView(viewPath, (object)tokens);

		public string ReplaceTokensFromView(string viewPath, object tokens)
		{
			var compiled = GetCompiledViewTemplateFromCache(viewPath);
			if(compiled == null)
			{
				compiled = CompileView(viewPath);
				AddCompiledViewTemplateToCache(viewPath, compiled);
			}

			return ReplaceTokens(compiled, tokens);
		}

		protected virtual Func<object, string> GetCompiledViewTemplateFromCache(string viewPath) => _compiledViewTemplateCache.Get(viewPath);

		protected virtual Func<object, string> CompileView(string viewPath) => _handlebarsService.CompileView(viewPath);

		protected virtual void AddCompiledViewTemplateToCache(string viewPath, Func<object, string> compiled) => _compiledViewTemplateCache.Add(viewPath, compiled);

		protected virtual Action<TextWriter, object> Compile(TextReader template) => _handlebarsService.Compile(template);

		protected virtual void RegisterHelper(string helperName, HandlebarsHelper helperFunction) => _handlebarsService.RegisterHelper(helperName, helperFunction);

		protected virtual void RegisterHelper(string helperName, HandlebarsBlockHelper helperFunction) => _handlebarsService.RegisterHelper(helperName, helperFunction);

		protected virtual void RegisterTemplate(string templateName, Action<TextWriter, object> template) => _handlebarsService.RegisterTemplate(templateName, template);

		protected virtual void RegisterTemplate(string templateName, string template) => _handlebarsService.RegisterTemplate(templateName, template);

		public void ClearAllCaches()
		{
			ClearTemplateCache();
			ClearViewsCache();
		}

		public void ClearTemplateCache() => _compiledTemplateCache.Clear();

		public void ClearViewsCache() => _compiledViewTemplateCache.Clear();
	}
}

Ultimately, the class above delegates calls to IHandlebarsService for the most part. Lookups are done to replace tokens in templates before compiling to see if these compilations were cached. If there were not cached, they are compiled and then cached. The resulting token replacement strings are returned for both template string replacements, and those sourced from template files.

I also have methods to clear the two caches.

Next, I created a custom FileWatcher to clear the Compile Views cache of Handlebars.Net template file compliations. Since FileWatchers are defined in the Web.config, I decided to create a service class which will control the logic which my cusotm FileWatcher will completely delegate its functionality to. The following interface is for that service class:

namespace Feature.Token.Services
{
	public interface IHandlebarsViewFilesWatcherService
	{
		void Created(string fullPath);

		void Deleted(string filePath);

		void Renamed(string filePath, string oldFilePath);
	}
}

The service class will take in a service Config Object defined in a Sitecore configuration file further below:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Feature.Token.Models.FileWatchers
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/feature/token/handlebarsViewFilesWatcherServiceSettings", Lifetime = Lifetime.Singleton)]
	public class HandlebarsViewFilesWatcherServiceSettings
	{
		public string CreatedLogInfoMessageFormat { get; set; }

		public string DeletedLogInfoMessageFormat { get; set; }

		public string RenamedLogInfoMessageFormat { get; set; }

		public string ClearViewsCacheLogInfoMessage { get; set; }
	}
}

Here is the implemenation of the interface above:

using Sitecore.Abstractions;

using Foundation.Token.Services;

using Feature.Token.Models.FileWatchers;

namespace Feature.Token.Services
{
	public class HandlebarsViewFilesWatcherService : IHandlebarsViewFilesWatcherService
	{
		private readonly HandlebarsViewFilesWatcherServiceSettings _settings;
		private readonly ITemplatedTokenReplacer _replacer;
		private readonly BaseLog _log;

		public HandlebarsViewFilesWatcherService(HandlebarsViewFilesWatcherServiceSettings settings, ITemplatedTokenReplacer replacer, BaseLog log)
		{
			_settings = settings;
			_replacer = replacer;
			_log = log;
		}

		public void Created(string fullPath)
		{
			LogInfo(string.Format(_settings.CreatedLogInfoMessageFormat, fullPath), this);
			ClearViewsCacheLogInfo();
		}

		public void Deleted(string filePath)
		{
			LogInfo(string.Format(_settings.DeletedLogInfoMessageFormat, filePath), this);
			ClearViewsCacheLogInfo();
		}

		public void Renamed(string filePath, string oldFilePath)
		{
			LogInfo(string.Format(_settings.RenamedLogInfoMessageFormat, filePath, oldFilePath), this);
			ClearViewsCacheLogInfo();
		}

		protected virtual void LogInfo(string message, object owner) => _log.Info(message, owner);

		protected virtual void ClearViewsCacheLogInfo()
		{
			ClearViewsCache();
			LogInfo(_settings.ClearViewsCacheLogInfoMessage, this);
		}

		protected virtual void ClearViewsCache() => _replacer.ClearViewsCache();
	}
}

If a Handlebars.Net template file is modified, added, renamed or deleted, the Handlebars.Net Views Cache is cleared so that changes will be reflected in the Content Tree immediately.

I then created the “real” FileWatcher class; this is the class which will be registered in my Web.config to make this work:

using Sitecore.DependencyInjection;
using Sitecore.IO;

using Feature.Token.Services;

namespace Feature.Token.FileWatchers
{
	public class HandlebarsViewFilesWatcher : FileWatcher
	{
		public HandlebarsViewFilesWatcher()
			: base("watchers/handlebars")
		{
		}

		protected override void Created(string fullPath) => GetService<IHandlebarsViewFilesWatcherService>().Created(fullPath);

		protected override void Deleted(string filePath) => GetService<IHandlebarsViewFilesWatcherService>().Deleted(filePath);

		protected override void Renamed(string filePath, string oldFilePath) => GetService<IHandlebarsViewFilesWatcherService>().Renamed(filePath, oldFilePath);

		protected TService GetService<TService>() where TService : class => ServiceLocator.ServiceProvider.GetService(typeof(TService)) as TService;
	}
}

With that in place, I defined it in my Web.config here:


  <!-- More stuff here -->
  
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
	
	  <!-- More stuff here -->
	  
	  <!-- Handlerbars view files watcher -->
	  <add type="Feature.Token.FileWatchers.HandlebarsViewFilesWatcher, Feature.Token" name="HandlebarsViewFilesWatcher"/>  

	    <!-- More stuff here -->
	</modules>
</system.webServer>

<!-- More stuff here -->

Now, we need a custom Sitecore patch configuration file to wire-up all of the services defined above for token replacement along with the settings object for the FileWatcher service:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
	  <moduleSettings>
		  <feature>
			  <token>
				  <handlebarsViewFilesWatcherServiceSettings type="Feature.Token.Models.FileWatchers.HandlebarsViewFilesWatcherServiceSettings, Feature.Token" singleInstance="true">
					  <CreatedLogInfoMessageFormat>Handlebars view file created or modified: {0}.</CreatedLogInfoMessageFormat>
					  <DeletedLogInfoMessageFormat>Handlebars view file deleted: {0}.</DeletedLogInfoMessageFormat>
					  <RenamedLogInfoMessageFormat>Handlebars view file renamed: {0}. Old path: {1}</RenamedLogInfoMessageFormat>
					  <ClearViewsCacheLogInfoMessage>Token Views Cache Cleared.</ClearViewsCacheLogInfoMessage>
				  </handlebarsViewFilesWatcherServiceSettings>
			  </token>	  
		  </feature>
	  </moduleSettings>	  
	  <services>
		  <register serviceType="Feature.Token.Services.IHandlebarsService, Feature.Token"
					implementationType="Feature.Token.Services.HandlebarsService, Feature.Token"
					lifetime="Singleton" />
		  <register serviceType="Foundation.Token.Services.ITemplatedTokenReplacer, Foundation.Token"
					implementationType="Feature.Token.Services.HandlebarsTokenReplacer, Feature.Token"
					lifetime="Singleton" />
		  <register serviceType="HandlebarsDotNet.ViewEngineFileSystem, Handlebars"
					implementationType="Feature.Token.Services.HandlebarsViewEngineFileSystem, Feature.Token"
					lifetime="Singleton" />
		  <register serviceType="Feature.Token.Services.IHandlebarsViewFilesWatcherService, Feature.Token"
					implementationType="Feature.Token.Services.HandlebarsViewFilesWatcherService, Feature.Token"
					lifetime="Singleton" />
		  <register serviceType="Feature.Token.Services.Cachers.ICompiledTemplateCache, Feature.Token"
					implementationType="Feature.Token.Services.Cachers.CompiledTemplateCache, Feature.Token"
					lifetime="Singleton" />
		  <register serviceType="Feature.Token.Services.Cachers.ICompiledViewTemplateCache, Feature.Token"
					implementationType="Feature.Token.Services.Cachers.CompiledViewTemplateCache, Feature.Token"
					lifetime="Singleton" />
	  </services>
	  <watchers>
		  <handlebars>
			  <folder>/Views</folder>
			  <filter>*.hbs</filter>
		  </handlebars>
	  </watchers>
  </sitecore>
</configuration>

Are you still with me? ๐Ÿ˜‰

Now, let’s define some other service classes which just wrap static method calls on things in the Sitecore Api; I wanted to source these all from the Sitecore IoC container, and not all things in the Sitecore Api are in the IoC container so I’ll just stick them in there. I’m not going to explain too much about these except that they are used in subsequent classes further down:

This interface with its implemenation wraps calls on the Sitecore.Data.ID class:

using System;

using Sitecore.Data;

namespace Foundation.Kernel.Services.UniqueIdentifier
{
    public interface IIDService
    {
        bool IsNullOrEmpty(ID id);

        bool TryParse(string value, out ID id);

        bool TryParse(object value, out ID id);

        ID Parse(string value);

        ID Parse(object value);

        ID CreateNewID();

        ID CreateNewID(string id); // not used in this post

        ID CreateNewID(Guid id);  // not used in this post
    }
}
using System;

using Sitecore.Data;

using Foundation.Kernel.Services.UniqueIdentifier.Factories;

namespace Foundation.Kernel.Services.UniqueIdentifier
{
    public class IDService : IIDService
    {
        private readonly IIDFactory _idFactory;   // not used in this post

        public IDService(IIDFactory idFactory)
        {
            _idFactory = idFactory;   // not used in this post
        }

        public bool IsNullOrEmpty(ID id) => ID.IsNullOrEmpty(id);

        public bool TryParse(string value, out ID id) => ID.TryParse(value, out id);

        public bool TryParse(object value, out ID id) => ID.TryParse(value, out id);

        public ID Parse(string value) => ID.Parse(value);

        public ID Parse(object value) => ID.Parse(value);

        public ID CreateNewID() => _idFactory.CreateNewID();

        public ID CreateNewID(string id) => _idFactory.CreateNewID(id);   // not used in this post

        public ID CreateNewID(Guid id) => _idFactory.CreateNewID(id);   // not used in this post
    }
}

This interface with its implemenation creates a FieldList instance from a FieldCollection instance along with pointers to methods for changing field values being placed from the FieldCollection into a new FieldList instance (this will be used further down in this post when modifying how Items appear in the content tree):

using System;

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

namespace Foundation.Kernel.Services.Fields.Factories
{
	public interface IFieldsFactory
	{
		FieldList CreateNewFieldList(FieldCollection fieldCollection, Func<Field, ID> idProvider, Func<Field, string> valueProvider);

		FieldList CreateNewFieldList();
	}
}
using System;

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

namespace Foundation.Kernel.Services.Fields.Factories
{
	public class FieldsFactory : IFieldsFactory
	{
		public FieldList CreateNewFieldList(FieldCollection fieldCollection, Func<Field, ID> idProvider, Func<Field, string> valueProvider)
		{
			FieldList fieldList = CreateNewFieldList();
			foreach (Field field in fieldCollection)
			{
				ID id = idProvider(field);
				string value = valueProvider(field);
				fieldList.Add(id, value);
			}

			return fieldList;
		}

		public FieldList CreateNewFieldList() => new FieldList();
	}
}

This interface and its implementation wrap calls to Sitecore.Globalization.Translate:

namespace Foundation.Kernel.Services.Globalization
{
	public interface ITranslateService
	{
		string TranslateText(string key);
	}
}
namespace Foundation.Kernel.Services.Globalization
{
	public class TranslateService : ITranslateService
	{
		public string TranslateText(string key) => Sitecore.Globalization.Translate.Text(key);
	}
}

This interface and its implementation wrap calls to Sitecore.Resources.Images; this will be used when dealing with Icon paths:

using Sitecore.Web.UI;

namespace Foundation.Kernel.Services.Media.Resources
{
	public interface IImagesService
	{
		string GetThemedImageSource(string image);

		string GetThemedImageSource(string image, ImageDimension dimension);
	}
}
using Sitecore.Resources;
using Sitecore.Web.UI;

namespace Foundation.Kernel.Services.Media.Resources
{
	public class ImagesService : IImagesService
	{
		public string GetThemedImageSource(string image) => Images.GetThemedImageSource(image);

		public string GetThemedImageSource(string image, ImageDimension dimension) => Images.GetThemedImageSource(image, dimension);
	}
}

This interface and its implementation will create instances of the Item class but with modified values sourced from another Item instance — this is used when changing the Item name for display in the content tree, and these items are “temporary”:

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

namespace Foundation.Kernel.Services.Items.Factories
{
	public interface IItemFactory
	{
		Item CreateAlteredItem(Item item, string itemName, string iconPath, ID templateId, ID branchId, Language language, Version version);

		Item CreateNewItem(ID itemID, ItemData data, Database database, bool isTemporary);
		
		ItemDefinition CreateItemDefinition(ID itemID, string itemName, ID templateID, ID branchId);

		ItemData CreateItemData(ItemDefinition definition, Language language, Version version, FieldList fields);
	}
}
using System;

using Sitecore;
using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Globalization;

using Foundation.Kernel.Services.Globalization;
using Foundation.Kernel.Services.Media.Resources;
using Foundation.Kernel.Services.UniqueIdentifier;
using Foundation.Kernel.Services.Fields.Factories;

namespace Foundation.Kernel.Services.Items.Factories
{
	public class ItemFactory : IItemFactory
	{
		private readonly IIDService _idService;
		private readonly IFieldsFactory _fieldsFactory;
		private readonly ITranslateService _translateService;
		private readonly IImagesService _imagesService;

		public ItemFactory(IIDService idService, IFieldsFactory fieldsFactory, ITranslateService translateService, IImagesService imagesService)
		{
			_idService = idService;
			_fieldsFactory = fieldsFactory;
			_translateService = translateService;
			_imagesService = imagesService;
		}

		public Item CreateAlteredItem(Item item, string itemName, string iconPath, ID templateId, ID branchId, Language language, Sitecore.Data.Version version)
		{
			if (item == null || IsNullOrEmpty(templateId))
			{
				return null;
			}

			ItemDefinition definition = CreateItemDefinition(item.ID, itemName, templateId, branchId);
			if (definition == null)
			{
				return null;
			}

			FieldList fields = CreateNewFieldList(item?.Fields, field => field.ID, field => GetAlteredItemFieldValue(field, itemName, iconPath));
			if (fields == null)
			{
				return null;
			}

			return CreateNewItem(item.ID, CreateItemData(definition, language, version, fields), item.Database, true);
		}

		protected virtual bool IsNullOrEmpty(ID id) => _idService.IsNullOrEmpty(id);

		protected virtual string GetAlteredItemFieldValue(Field field, string itemName, string iconPath)
		{
			string value = field.Value;
			if (field.ID == GetDisplayNameFieldId() && !string.IsNullOrWhiteSpace(itemName))
			{
				value = TranslateText(itemName);
			}
			else if (field.ID == GetIconFieldId() && !string.IsNullOrWhiteSpace(iconPath))
			{
				value = GetThemedImageSource(iconPath);
			}

			return value;
		}

		protected virtual ID GetDisplayNameFieldId() => FieldIDs.DisplayName;

		protected virtual ID GetIconFieldId() => FieldIDs.Icon;

		protected virtual string TranslateText(string key) => _translateService.TranslateText(key);

		protected virtual string GetThemedImageSource(string image) => _imagesService.GetThemedImageSource(image);

		protected virtual FieldList CreateNewFieldList(FieldCollection fieldCollection, Func<Field, ID> idProvider, Func<Field, string> valueProvider) => _fieldsFactory.CreateNewFieldList(fieldCollection, idProvider, valueProvider);

		public Item CreateNewItem(ID itemID, ItemData data, Database database, bool isTemporary)
		{
			return new Item(itemID, data, database)
			{
				RuntimeSettings = { Temporary = isTemporary }
			};
		}

		public ItemDefinition CreateItemDefinition(ID itemID, string itemName, ID templateID, ID branchId) => new ItemDefinition(itemID, itemName, templateID, branchId);

		public ItemData CreateItemData(ItemDefinition definition, Language language, Sitecore.Data.Version version, FieldList fields) => new ItemData(definition, language, version, fields);
	}
}

This interface and its implementation wrap calls to the Sitecore.Data.Version class:

using Sitecore.Data;

namespace Foundation.Kernel.Services.Versoning
{
	public interface IVersionService
	{
		Version GetLatestVersion();
	}
}
using Sitecore.Data;

namespace Foundation.Kernel.Services.Versoning
{
	public class VersionService : IVersionService
	{
		public Version GetLatestVersion() => Version.Latest;
	}
}

This interface and its implementation wrap calls to the Sitecore.Globalization.Language class:

using Sitecore;
using Sitecore.Globalization;

namespace Foundation.Kernel.Services.Globalization
{
    public interface ILanguageService
    {
        bool TryParse(string name, out Language result);

        Language Parse(string name);

        Language GetContextLanguage();

		Language GetLanguageInvariant();
	}
}
using Sitecore;
using Sitecore.Globalization;

namespace Foundation.Kernel.Services.Globalization
{
    public class LanguageService : ILanguageService
    {
        public bool TryParse(string name, out Language result) => Language.TryParse(name, out result);

        public Language Parse(string name) => Language.Parse(name);

        public Language GetContextLanguage() => Context.Language;

		public Language GetLanguageInvariant() => Language.Invariant;
	}
}

Let’s tie everything together in the following implentation of the DataViewChildItemsProcessor class defined towards the top of this post:

using System;
using System.Collections.Generic;

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

using Foundation.Token.Services;

using Foundation.Kernel.Pipelines.DataViewChildItems;
using Foundation.Kernel.Services.FeatureToggle;
using Foundation.Kernel.Services.Items.Factories;
using Foundation.Kernel.Services.Versoning;
using Foundation.Kernel.Services.Globalization;

using Foundation.Validation.Services.TooManySubItems.Factories;
using Foundation.Validation.Services.TooManySubItems;
using Foundation.Validation.Models.TooManySubItems;

namespace Feature.ContentEditor.Pipelines.DataViewChildItems
{
	public class MediaItemTooManyChildItems : DataViewChildItemsProcessor, IMediaItemTooManyChildItems
	{
		private readonly ITooManySubItemsFeatureToggleService _tooManySubItemsFeatureToggleService;
		private readonly ITooManySubItemsServiceParametersFactory _tooManySubItemsServiceParametersFactory;
		private readonly ITooManySubItemsService _tooManySubItemsService;
		private readonly ITemplatedTokenReplacer _templatedTokenReplacer;
		private readonly IItemFactory _itemFactory;
		private readonly IVersionService _versionService;
		private readonly ILanguageService _languageService;

		private string MediaLibraryBasePath { get; set; }

		public List<string> TemplateIdsToIgnore { get; set; } = new List<string>();

		public int NumberOfItemsToStartWarningUser { get; set; }

		private string AlmostAtMaxiumIconPath { get; set; }

		private string AlmostAtMaxiumMessageViewPath { get; set; }

		public int MaximumNumberOfItemsInFolder { get; set; }

		private string AtMaxiumIconPath { get; set; }

		private string AtMaxiumMessageViewPath { get; set; }

		public MediaItemTooManyChildItems(IFeatureToggleService featureToggleService, ITooManySubItemsFeatureToggleService tooManySubItemsFeatureToggleService, ITooManySubItemsServiceParametersFactory tooManySubItemsServiceParametersFactory, ITooManySubItemsService tooManySubItemsService, ITemplatedTokenReplacer templatedTokenReplacer,  IItemFactory itemFactory, IVersionService versionService, ILanguageService languageService)
			: base(featureToggleService)
		{
			_tooManySubItemsFeatureToggleService = tooManySubItemsFeatureToggleService;
			_tooManySubItemsServiceParametersFactory = tooManySubItemsServiceParametersFactory;
			_tooManySubItemsService = tooManySubItemsService;
			_templatedTokenReplacer = templatedTokenReplacer;
			_itemFactory = itemFactory;
			_versionService = versionService;
			_languageService = languageService;
		}

		protected override bool ShouldExecute(DataViewChildItemsArgs args)
		{
			return IsMediaLibraryBasePathSet()
				&& HasRequiredParameters(args)
				&& IsInMediaLibrary(args?.Parent);
		}

		protected override bool IsEnabled() => _tooManySubItemsFeatureToggleService.IsEnabled(this);

		protected virtual bool IsMediaLibraryBasePathSet() => !string.IsNullOrWhiteSpace(GetMediaLibraryBasePath());

		protected virtual bool HasRequiredParameters(DataViewChildItemsArgs args) => args?.Parent != null && args?.Children != null;

		protected virtual bool HasAlmostTooManySubItems(TooManySubItemsServiceParameters parameters) => _tooManySubItemsService.HasAlmostTooManySubItems(parameters);

		protected virtual bool HasTooManySubItems(TooManySubItemsServiceParameters parameters) => _tooManySubItemsService.HasTooManySubItems(parameters);

		protected override void GetChildItems(DataViewChildItemsArgs args)
		{
			if (!HasRequiredParameters(args))
			{
				return;
			}

			for (int i = args.Children.Count - 1; i >= 0; i--)
			{
				Item child = args.Children[i];
				if(!IsInMediaLibrary(child) || IsMediaLibraryRootItem(child))
				{
					continue;
				}

				TooManySubItemsServiceParameters parameters = CreateParameters(child, this);
				bool hasAlmostTooManySubItems = HasAlmostTooManySubItems(parameters);
				bool hasTooManySubItems = HasTooManySubItems(parameters);
				if (!hasAlmostTooManySubItems && !hasTooManySubItems)
				{
					continue;
				}

				string itemName = string.Empty;
				string iconPath = string.Empty;
				if (hasAlmostTooManySubItems)
				{
					itemName = GetAlmostAtMaxiumMessage(child, GetAlmostAtMaxiumIconPath());
				}
				else if (hasTooManySubItems)
				{
					itemName = GetAtMaxiumMessage(child, GetAtMaxiumIconPath());
				}

				Item alteredItem = GetAlteredItem(child, itemName, iconPath, child.TemplateID);
				if(alteredItem == null)
				{
					return;
				}

				args.Children.RemoveAt(i);
				args.Children.Insert(i, alteredItem);
			}
		}

		protected virtual bool IsInMediaLibrary(Item item)
		{
			string mediaLibraryBasePath = GetMediaLibraryBasePath();
			if (item == null || string.IsNullOrWhiteSpace(mediaLibraryBasePath))
			{
				return false;
			}

			return item.Paths.FullPath.StartsWith(mediaLibraryBasePath, StringComparison.OrdinalIgnoreCase);
		}

		protected virtual bool IsMediaLibraryRootItem(Item item)
		{
			string mediaLibraryBasePath = GetMediaLibraryBasePath();
			if (item == null || string.IsNullOrWhiteSpace(mediaLibraryBasePath))
			{
				return false;
			}

			return item.Paths.FullPath.Equals(mediaLibraryBasePath, StringComparison.OrdinalIgnoreCase);
		}

		protected virtual string GetMediaLibraryBasePath() => MediaLibraryBasePath;

		protected virtual TooManySubItemsServiceParameters CreateParameters(Item item, ITooManySubItemsFeature feature) => _tooManySubItemsServiceParametersFactory.CreateParameters(item, feature);

		protected virtual string GetAlmostAtMaxiumIconPath() => AlmostAtMaxiumIconPath;

		protected virtual string GetAtMaxiumIconPath() => AtMaxiumIconPath;

		protected virtual string GetAlmostAtMaxiumMessage(Item item, string iconPath) => ReplaceTokensFromView(GetAlmostAtMaxiumMessageViewPath(), new { ItemName = item.Name, IconPath = iconPath, ChildItemsCount = GetChildItemsCount(item) });

		protected virtual string GetAlmostAtMaxiumMessageViewPath() => AlmostAtMaxiumMessageViewPath;

		protected virtual string GetAtMaxiumMessage(Item item, string iconPath) => ReplaceTokensFromView(GetAtMaxiumMessageViewPath(), new { ItemName = item.Name, IconPath = iconPath, ChildItemsCount = GetChildItemsCount(item) });

		protected virtual string GetAtMaxiumMessageViewPath() => AtMaxiumMessageViewPath;

		protected virtual int GetChildItemsCount(Item item) => item.Children.Count;

		protected virtual string ReplaceTokensFromView(string viewPath, object tokens) => _templatedTokenReplacer.ReplaceTokensFromView(viewPath, tokens);

		protected virtual Item GetAlteredItem(Item item, string itemName, string iconPath, ID templateId) => CreateAlteredItem(item, itemName, iconPath, templateId, ID.Null, GetLanguageInvariant(), GetLatestVersion());

		protected virtual Item CreateAlteredItem(Item item, string itemName, string iconPath, ID templateId, ID branchId, Language language, Sitecore.Data.Version version) => _itemFactory.CreateAlteredItem(item, itemName, iconPath, templateId, branchId, language, version);

		protected virtual Language GetLanguageInvariant() => _languageService.GetLanguageInvariant();

		protected virtual Sitecore.Data.Version GetLatestVersion() => _versionService.GetLatestVersion();
	}
}

I’m not going to explain this entire class as there’s a lot of service delegation happening here but the gist is we will only create an “altered” item when the item in the Children collection on the DataViewChildItemsArgs instance is in the media library, and has almost, or does have too many child items. We then replace the child item in the DataViewChildItemsArgs Children collection with the “altered” item whose name includes the original item’s name and the icon associated with “almost has too many child items” or “has too many child items”; these are retrieved from their respective methods.

I then registered the pipeline processor above in the Sitecore configuration patch file below:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
	<sitecore>
		<pipelines>
			<group name="masterDataView">
				<pipelines>
					<dataviewChildItems>
						<processor type="Feature.ContentEditor.Pipelines.DataViewChildItems.IMediaItemTooManyChildItems, Feature.ContentEditor" resolve="true">
							<Enabled>true</Enabled>
							<AbortPipelineAfterExecution>false</AbortPipelineAfterExecution>
							<MediaLibraryBasePath>/sitecore/media library/</MediaLibraryBasePath>
							<AlmostAtMaxiumIconPath>-/icon/Applicationsv2/16x16/sign_warning.png</AlmostAtMaxiumIconPath>
							<AtMaxiumIconPath>-/icon/Apps/16x16/Stop.png</AtMaxiumIconPath>
							<AlmostAtMaxiumMessageViewPath>/Views/DataViewChildItems/MediaItemTooManyChildItems/AlmostAtMaxiumMessageTemplate.hbs</AlmostAtMaxiumMessageViewPath>
							<AtMaxiumMessageViewPath>/Views/DataViewChildItems/MediaItemTooManyChildItems/AtMaxiumMessageTemplate.hbs</AtMaxiumMessageViewPath>
							<!-- By setting these, you can override the default values set for the entire feature set
										<NumberOfItemsToStartWarningUser>95</NumberOfItemsToStartWarningUser>
										<MaximumNumberOfItemsInFolder>100</MaximumNumberOfItemsInFolder>
							-->
						</processor>
					</dataviewChildItems>
				</pipelines>
			</group>
		</pipelines>
		<services>
			<register
				serviceType="Feature.ContentEditor.Pipelines.DataViewChildItems.IMediaItemTooManyChildItems, Feature.ContentEditor"
				implementationType="Feature.ContentEditor.Pipelines.DataViewChildItems.MediaItemTooManyChildItems, Feature.ContentEditor"
				lifetime="Singleton" />
		</services>
	</sitecore>
</configuration>

This is what’s inside of /Views/DataViewChildItems/MediaItemTooManyChildItems/AlmostAtMaxiumMessageTemplate.hbs; this a Handlebars.Net template file:

{{ItemName}}&nbsp;<img src="{{IconPath}}" />&nbsp;<span style="color: #999900;">({{ChildItemsCount}} child items)</span>

This is what’s inside of /Views/DataViewChildItems/MediaItemTooManyChildItems/AtMaxiumMessageTemplate.hbs; this a Handlebars.Net template file:

{{ItemName}}&nbsp;<img src="{{IconPath}}" />&nbsp;<span style="color: red;">({{ChildItemsCount}} child items)</span>

Let’s have a look at what this does. The following is what the tree in my Media Library looks like with this turned on:

One thing I want to point out is that I have not rigorously tested this solution so use at your own risk.

Also, after discussing this solution with Sitecore MVPs Akshay Sura and Kamruz Jaman, Akshay brought up a great idea of having a custom MasterDataView being driving by the Sitecore Rules Engine. I thought it was a great idea, and maybe some day in the future I might blog about this but, honestly, I think this might be something that you, my dear reader, should have a stab at, and give back to the community if you find such a solution.

Until next time, keep on Sitecoring.

Magically Register Sitecore Configuration Objects in the Sitecore IoC Container using a custom Attribute

About a year and half ago, Sitecore MVP Alan Coates blogged about having Sitecore Configuration Objects (aka Config Objects) being sourced from the Sitecore IoC container, and then injected into service classes that need them. He did this on a theme of Helix Principles but in reality, the ability to create Config Objects has existed since the Configuration Factory was released on version 6.x — don’t ask me which exact version the Configuration Factory was released as this was many projects, many grey hairs, and many country moves ago albeit it’s not something new (you can search through some of my vintage blog posts all the way back to the beginning where I have used these), and the ability to stick these into the Sitecore IoC container has existed since version 8.2 — this is when Sitecore rolled out its IoC container with native Dependency Injection support.

However, he was correct on the statement that it is something which is often overlooked as I continue to ยฏ\_(ใƒ„)_/ยฏ (/shrug on Slack ๐Ÿ˜‰ ) — or maybe even (ใƒŽเฒ ็›Šเฒ )ใƒŽๅฝกโ”ปโ”โ”ป — when I see solutions where everyone dumps everything configuration-driven in a Sitecore setting. I hope this blog post will further reinforce the practice of employing config objects in your solutions — or hopefully make the Sitecore settings junkies adopt this alternative approach instead — especially when I’m going to discuss how I’ve been wiring-up these config objects into the Sitecore IoC container using a custom Attribute decorating classes which represent these Config Objects along with a Foundation layer module configurator to put these into the IoC container; this is an approach I have been doing for the past 2 years.

Virtually all of my posts in 2018 — see my last post of 2018 for an example — created and stuck Config Objects into the IoC container for injection into servlice classes where needed. I had done all of these using code which created and registered these into the IoC container in a Configurator for a particular Helix layer module. At the time, it felt a bit awkward to me as I felt the knowledge of the configuration path to these was a bit removed from the classes which represent these objects, so I came up with the following way to define these configuration paths closer to the class definitions of the Config Objects (you can’t really get any closer than having the path be somewhere on the class, and this is done through a custom Attribute).

First, we need to custom Attribute which will decorate classes which represent the Config Objects:

using System;

using Foundation.DependencyInjection.Enums;

namespace Foundation.DependencyInjection
{
    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class ServiceConfigObjectAttribute : Attribute
    {
        public Lifetime Lifetime { get; set; } = Lifetime.Singleton;

		public string ConfigPath { get; set; }

		public Type ServiceType { get; set; }
	}
}

This solution involves assembly scanning using wildcards. I adapted Kam Figy‘s solution around registering MvC Controllers into the IoC container (see the end of https://kamsar.net/index.php/2016/08/Dependency-Injection-in-Sitecore-8-2/ for this) to make some of this magic happen but created a class with interface to abstract some of this out:

using System.Collections.Generic;
using System.Reflection;

namespace Foundation.DependencyInjection.Services.Assemblies
{
    public interface IAssemblyRepository
    {
        IEnumerable<Assembly> GetAssemblies(IEnumerable<string> assemblyFilters);
        
        IEnumerable<Assembly> GetAssemblies();

        Assembly GetCallingAssembly();
    }
}
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Foundation.DependencyInjection.Services.Assemblies
{
    public class AssemblyRepository : IAssemblyRepository
    {
        public IEnumerable<Assembly> GetAssemblies(IEnumerable<string> assemblyFilters)
        {
            var assemblyNames = new HashSet<string>(assemblyFilters.Where(filter => !filter.Contains('*')));
            var wildcardNames = assemblyFilters.Where(filter => filter.Contains('*')).ToArray();

            return GetAssemblies().Where(assembly =>
            {
                var nameToMatch = assembly.GetName().Name;
                if (assemblyNames.Contains(nameToMatch)) return true;

                return wildcardNames.Any(wildcard => IsWildcardMatch(nameToMatch, wildcard));
            }).ToList();
        }

        protected virtual bool IsWildcardMatch(string input, string wildcards)
        {
            return Regex.IsMatch(input, "^" + Regex.Escape(wildcards).Replace("\\*", ".*").Replace("\\?", ".") + "$", RegexOptions.IgnoreCase);
        }

        public IEnumerable<Assembly> GetAssemblies() => AppDomain.CurrentDomain.GetAssemblies();

        public Assembly GetCallingAssembly() => Assembly.GetCallingAssembly();
    }
}

The class above returns a collection of Assemblies which match a collection of wildcards passed to it.

I then created a factory class with interface to create the class instance above:

namespace Foundation.DependencyInjection.Services.Assemblies.Factories
{
    public interface IAssemblyRepositoryFactory
    {
        IAssemblyRepository CreateAssemblyRepository();
    }
}
namespace Foundation.DependencyInjection.Services.Assemblies.Factories
{
    public class AssemblyRepositoryFactory : IAssemblyRepositoryFactory
    {
        public IAssemblyRepository CreateAssemblyRepository() => new AssemblyRepository();
    }
}

The class above has a method which creates the instance of the AssemblyRepository class instance as its interface.

Next, I create an enumeration to define the lifetimes of the service classes — I can’t think of a reason why you would want these Config Objects to be anything but a Singleton but who knows, you might have a reason:

namespace Foundation.DependencyInjection.Enums
{
    public enum Lifetime
    {
        Transient,
        Singleton,
        Scoped
    }
}

Following this, I created some Extension Methods of IServiceCollection so I can find all classes decorated with the ServiceConfigObjectAttribute class defined above; use the Sitecore Configuration Factory service to create their instances; and register them in the IoC container with the appropriate service type — if none is provided, it’ll use the class type — and lifetime defined:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web.Http;
using System.Web.Mvc;

using Microsoft.Extensions.DependencyInjection;

using Sitecore.Abstractions;

using Foundation.DependencyInjection.Enums;
using Foundation.DependencyInjection.Services.Assemblies;
using Foundation.DependencyInjection.Services.Assemblies.Factories;

namespace Foundation.DependencyInjection.Extensions
{
    public static class ServiceCollectionExtensions
    {
		private static readonly IAssemblyRepository _assemblyRepository;

        static ServiceCollectionExtensions()
        {
            _assemblyRepository = CreateAssemblyRepository();
        }

        private static IAssemblyRepository CreateAssemblyRepository() => CreateAssemblyRepositoryFactory()?.CreateAssemblyRepository();

        private static IAssemblyRepositoryFactory CreateAssemblyRepositoryFactory() => new AssemblyRepositoryFactory();
		
		public static void AddClassesWithServiceConfigObjectAttribute(this IServiceCollection serviceCollection, params string[] assemblyFilters)
		{
			var assemblies = GetAssemblies(assemblyFilters);
			serviceCollection.AddClassesWithServiceConfigObjectAttribute(assemblies);
		}

		public static Assembly[] GetAssemblies(IEnumerable<string> assemblyFilters) => _assemblyRepository.GetAssemblies(assemblyFilters)?.ToArray();
		
		public static void AddClassesWithServiceConfigObjectAttribute(this IServiceCollection serviceCollection, params Assembly[] assemblies)
        {
            var typesWithAttributes = assemblies
                .Where(assembly => !assembly.IsDynamic)
                .SelectMany(GetExportedTypes)
                .Where(type => !type.IsAbstract && !type.IsGenericTypeDefinition)
                .Select(type => new { type.GetCustomAttribute<ServiceConfigObjectAttribute>()?.ServiceType, ImplementationType = type, type.GetCustomAttribute<ServiceConfigObjectAttribute>()?.ConfigPath, type.GetCustomAttribute<ServiceConfigObjectAttribute>()?.Lifetime })
                .Where(t => t.Lifetime != null);

            foreach (var type in typesWithAttributes)
            {
                AddConfigObject(serviceCollection, type.ServiceType == null ? type.ImplementationType : type.ServiceType, type.Lifetime.Value, type.ConfigPath);
            }
        }
		
		private static void AddConfigObject(IServiceCollection serviceCollection, Type serviceType, Lifetime lifetime, string configPath)
        {
            if (serviceCollection == null || serviceType == null || string.IsNullOrWhiteSpace(configPath))
            {
                return;
            }

            serviceCollection.Add(CreateServiceDescriptor(serviceType, provider => CreateConfigObject(provider, configPath), GetServiceLifetime(lifetime)));
        }
		
		private static ServiceDescriptor CreateServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) => new ServiceDescriptor(serviceType, factory, lifetime);
		
		private static object CreateConfigObject(IServiceProvider provider, string configPath)
        {
            BaseFactory factory = provider.GetService<BaseFactory>();
            return factory.CreateObject(configPath, true);
        }
		
		private static ServiceLifetime GetServiceLifetime(Lifetime lifetime)
        {
            if (lifetime == Lifetime.Singleton)
            {
                return ServiceLifetime.Singleton;
            }

            if (lifetime == Lifetime.Transient)
            {
                return ServiceLifetime.Transient;
            }

            return ServiceLifetime.Transient;
        }
	}
}

Now, we need to have a configurator to call the extension method in the class above. I first defined a base configurator which will have a method to return the assembly wildcards — it’s virtual just in case you need to target different assemblies (I’m sure there’s a better place to put these wildcards but I stuck them here for now):

namespace Foundation.DependencyInjection.Configurators
{
    public abstract class BaseAssemblyFiltersServicesConfigurator : IServicesConfigurator
    {
		private static readonly string[] _defaultAssemblyFilters = new string[] { "Foundation.*", "Feature.*" };

		protected virtual string[] GetAssemblyFilters() => _defaultAssemblyFilters;
    }
}

The following configurator inherits the base configurator above, and just calls the AddClassesWithServiceConfigObjectAttribute() extension method defined in the ServiceCollectionExtensions class above, and passes the assembly wildcard collection defined in the BaseAssemblyFiltersServicesConfigurator class above:

using Microsoft.Extensions.DependencyInjection;

using Foundation.DependencyInjection.Extensions;

namespace Foundation.DependencyInjection.Configurators
{
    public class ServiceConfigObjectAttributeServicesConfigurator : BaseAssemblyFiltersServicesConfigurator
	{
		public override void Configure(IServiceCollection serviceCollection) => serviceCollection.AddClassesWithServiceConfigObjectAttribute(GetAssemblyFilters());
	}
}

I then registered the configurator above in a Sitecore patch configuration file:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
    <services>
        <configurator type= "Foundation.DependencyInjection.Configurators.ServiceConfigObjectAttributeServicesConfigurator, Foundation.DependencyInjection"/>
    </services>
  </sitecore>
</configuration>

Alright, now that we have all of this out of the way, let’s see how we can use all of the stuff above.

I created all of the following for a future blog post — and also for a project I had recently worked on — but I’ll show these now to demonstrate how this all works, and to also save me time on writing that future post ๐Ÿ˜‰

The following class is a Config Object which has the name of a Sheer UI client command, and a delay value for that command to be invoked inside the Sitecore client:

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

namespace Foundation.Kernel.Models.Client
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/clientServiceSettings", Lifetime = Lifetime.Singleton)]
	public class ClientServiceSettings
	{
		public string LoadItemClientCommandName { get; set; }

		public int LoadItemClientCommandDelay { get; set; }
	}
}

Here’s what it looks like in a Sitecore patch configuration file:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
	  <moduleSettings>
		  <foundation>
			  <kernel>
				  <clientServiceSettings type="Foundation.Kernel.Models.Client.ClientServiceSettings, Foundation.Kernel" singleInstance="true">
					  <LoadItemClientCommandName>item:load</LoadItemClientCommandName>
					  <LoadItemClientCommandDelay>1</LoadItemClientCommandDelay>
				  </clientServiceSettings>
			  </kernel>
		  </foundation>
	  </moduleSettings>
  </sitecore>
</configuration>

Let’s define another Config Object but something which is a little more “complex” than the example above.

I created the following class to represent a Sheer UI command — ultimately, these will be stored in a Dictionary so I can find a command format by key:

namespace Foundation.Kernel.Models.Client
{
	public class Command
	{
		public string Name { get; set; }

		public string CommandFormat { get; set; }
	}
}

Next, I need a service type/implementation to manage Command class instances above, and ultimately wrap a Dictionary containing information for these Commands:

using Foundation.Kernel.Models.Client;

namespace Foundation.Kernel.Services.Client
{
	public interface IClientCommandService
	{
		string GetClientCommand(string name, params string[] arguments);

		Command GetCommand(string name);
	}
}

Here’s the implementation of the interface above:

using System.Collections.Generic;

using Foundation.DependencyInjection;
using Foundation.DependencyInjection.Enums;

using Foundation.Kernel.Models.Client;

namespace Foundation.Kernel.Services.Client
{
	[ServiceConfigObject(ConfigPath = "moduleSettings/foundation/kernel/clientCommandService ", ServiceType = typeof(IClientCommandService), Lifetime = Lifetime.Singleton)]
	public class ClientCommandService : IClientCommandService
	{
		private readonly IDictionary<string, Command> _commands = new Dictionary<string, Command>();

		protected void AddClientCommand(string key, Command command)
		{
			if(string.IsNullOrWhiteSpace(key) || command == null)
			{
				return;
			}

			_commands[key] = command;
		}

		public string GetClientCommand(string name, params string[] arguments)
		{
			string commandFormat = GetCommandFormat(name);
			if(string.IsNullOrWhiteSpace(commandFormat))
			{
				return string.Empty;
			}

			return string.Format(commandFormat, arguments);
		}

		protected virtual string GetCommandFormat(string name) => GetCommand(name)?.CommandFormat;

		public Command GetCommand(string name) => _commands[name];
	}
}

So if I were to call the GetClientCommand() method on the service class above like this:

IClientCommandService clientCommandService; // make pretend this was injected in a class that's using it
clientCommandService.GetClientCommand("item:load") // this would return item:load(id={0}) so that we can do a string.Format() on it while providing an Item ID (this is used to load (or reload) an Item in the Content Editor

We would get a item:load(id={0}) so that we could supply an Item ID to replace {0}.

Here’s the Sitecore patch configuration file which represents the Config Object above:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
	  <services>
		  <configurator type="Foundation.Kernel.Configurators.KernelConfigurator, Foundation.Kernel"/>
	  </services>
	  <moduleSettings>
		  <foundation>
			  <kernel>
				  <clientCommandService type="Foundation.Kernel.Services.Client.ClientCommandService, Foundation.Kernel" singleInstance="true">
					  <Commands hint="list:AddClientCommand">
						  <command key="item:load" type="Foundation.Kernel.Models.Client.Command, Foundation.Kernel">
							  <Name>$(key)</Name>
							  <CommandFormat>item:load(id={0})</CommandFormat>
						  </command>
					  </Commands>
				  </clientCommandService>
			  </kernel>
		  </foundation>
	  </moduleSettings>
  </sitecore>
</configuration>

Here’s what both Config Objects looking like on /sitecore/admin/showservicesconfig.aspx after all the code above runs:

Registered in IoC container

Now that the two configuration objects are in the IoC container, we can inject them into the follow service. Here’s the interface of that service:

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Web.UI.HtmlControls;

namespace Foundation.Kernel.Services.Client
{
	public interface IClientService
	{
		void RefreshItem(Item item);

		void RefreshItem(ID itemId);

		ClientCommand Timer(string eventName, int delay);

		void Alert(string message);
	}
}

Here’s the implementation the service:

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Web.UI.HtmlControls;

using Foundation.Kernel.Services.Client.SheerUI;
using Foundation.Kernel.Services.UniqueIdentifier;
using Foundation.Kernel.Models.Client;

namespace Foundation.Kernel.Services.Client
{
	public class ClientService : IClientService
	{
		private readonly ClientServiceSettings _settings;
		private readonly IIDService _idService;
		private readonly ISheerResponseService _sheerResponseService;
		private readonly IClientCommandService _clientCommandService;
		private readonly IClientResponseService _clientResponseService;
		
		public ClientService(ClientServiceSettings settings, IIDService idService, ISheerResponseService sheerResponseService, IClientCommandService clientCommandService, IClientResponseService clientResponseService)
		{
			_settings = settings; // config object was injected here
			_idService = idService; 
			_sheerResponseService = sheerResponseService;
			_clientCommandService = clientCommandService; // another config object injected here 
			_clientResponseService = clientResponseService;
		}

		public void RefreshItem(Item item) => RefreshItem(item?.ID);

		public void RefreshItem(ID itemId)
		{
			if(IsNullOrEmpty(itemId))
			{
				return;
			}

			string command = GetClientCommand(GetLoadItemClientCommandName(), itemId.ToString());
			if(string.IsNullOrWhiteSpace(command))
			{
				return;
			}

			Timer(command, GetLoadItemClientCommandDelay());
		}

		protected virtual bool IsNullOrEmpty(ID id) => _idService.IsNullOrEmpty(id);

		protected virtual string GetLoadItemClientCommandName() => _settings.LoadItemClientCommandName;

		protected virtual string GetClientCommand(string name, params string[] arguments) => _clientCommandService.GetClientCommand(name, arguments);

		protected virtual int GetLoadItemClientCommandDelay() => _settings.LoadItemClientCommandDelay;

		public ClientCommand Timer(string eventName, int delay) => _clientResponseService.Timer(eventName, delay);

		public void Alert(string message) => _sheerResponseService.Alert(message);
	}
}

The class above consumes instances of the ClientServiceSettings and IClientCommandService Config Objects along with other injected services which I am omitting for brevity – I believe I may have covered these other service classes in previous blog posts, and may cover some others in future blog posts — but the basic idea of this class is to wrap methods to functionality of Sheer UI to send Alert messages, refresh an item in the content tree of the Contend Editor, or to invoke another client command (via the Timer() method).

Most of my posts moving forward will use the ServiceConfigObjectAttribute above so be sure to understand what’s going on here in order to fully know what’s going on in those future posts.

magic