Tuesday, March 4, 2014

Dependency injection in Sitecore event handlers

Following my previous article about Dependency injection in Sitecore custom commands, I think it is only appropriate to continue with something similar for Sitecore event handlers. And when I say similar I mean very similar - in fact reading this article after having read the previous one may induce some sense of deja vu :-) To learn more about Sitecore events visit Using Events.

This article assumes an understanding of Sitecore events and the concept of dependency injection. The purpose is to show how to use dependency injection in Sitecore events.

The normal way of creating an event handler for a Sitecore event is to create a handler class with an EventHandler delegate, i.e. a method with the EventHandler signature, and then add some config to Sitecore's <events> section defining where to find the event handler implementation, so that Sitecore can instantiate the event handler and trigger the delegate when the event occurs.

The problem with this approach is that nowadays it is common to use dependency injection in software solutions, and letting Sitecore take care of creating instances of your custom code means that you loose the possibility of injecting the needed dependencies. Luckily there is also a way out of this morass.

Sitecore has created a class called Event, which is used for subscribing, unsubscribing, and raising events. The good news is that it is available for use.

So here is a suggestion on how to use it to obtain dependency injection in Sitecore events. It is based on using Autofac as IoC container.

First, create a base class for your event handlers:

namespace TestApp.Events
{
  public abstract class BaseEventHandler
  {
    public string FullName { get; private set; }

    protected BaseEventHandler(string fullName)
    {
      FullName = fullName;
    }

    public abstract void OnEvent(object sender, System.EventArgs args);
  }
}
This base class defines the EventHandler delegate method signature that all derived event handler classes must implement, but it also has one property, FullName, for holding the event name for registration purposes.

Next, create your event handler inheriting from BaseEventHandler like this:
namespace TestApp.Events
{
  public class MyEventHandler : BaseEventHandler
  {
    private readonly IMyDependency _myDependency;

    public MyEventHandler(string fullName, IMyDependency myDependency)
      : base(fullName)
    {
      _myDependency = myDependency;
    }

    public override void OnEvent(object sender, System.EventArgs args)
    {
      // event handler implementation
    }
  }
}
As you can see we inject a dependency in the constructor. The constructor furthermore calls the base constructor to set the event name.

Now, create a class for registering events using the Sitecore Event class:
namespace TestApp.Events
{
  public static class EventConfigurator
  {
    public static void Configure(System.Collections.Generic.IEnumerable<BaseEventHandler> eventHandlers)
    {
      foreach (var eventHandler in eventHandlers)
      {
        Sitecore.Events.Event.Subscribe(eventHandler.FullName, eventHandler.OnEvent);
      }
    }
  }
}
The Configure method takes a collection of BaseEventHandler objects (our event handler instances), then uses Subscribe method on the Event class to subscribe the events.

That is basically all the pieces we need. We just have to fit everything together in our bootstrapper (the place where all the dependencies are set up using the IoC container). This could look something like this:
...
var builder = new ContainerBuilder();

builder.RegisterType<MyDependency>().As<IMyDependency>().InstancePerLifetimeScope();

builder.RegisterType<MyEventHandler>().As<BaseEventHandler>().WithParameter("fullName", "mynamespance:mycategory:myevent").InstancePerLifetimeScope();

var rootContainer = builder.Build();

var eventHandlers = rootContainer.Resolve<IEnumerable<BaseEventHandler>>();
EventConfigurator.Configure(eventHandlers);
...
So we just register dependencies as usual. The new thing is that we now register our event handlers in code, instead of using a Sitecore config file. And then we call our EventConfigurator with a collection of instances of all our event handlers.

That's it. Plain and simple :-)

Update:
Please note that since the event handlers are resolved only once (at app startup), any injected dependencies are effectively singletons.

Saturday, March 1, 2014

Dependency injection in custom Sitecore commands

Custom commands are probably one of the more ignored features in Sitecore, but they can be quite powerful. They could for example be used for insert options on templates, thereby allowing code to run on creation of content items. To learn more about commands (or specifically Command Templates) visit "Sitecore CMS 6.0 or later Data Definition Cookbook" chapter 4.

This article assumes an understanding of Command Templates and the concept of dependency injection. The purpose is to show how to use dependency injection in custom commands in Sitecore.

The normal way of creating a Sitecore custom command is to create a class inheriting from Sitecore.Shell.Framework.Commands.Command, overriding the Execute method, and then adding some config to Sitecore's <commands> section defining where to find the command implementation, so that Sitecore can instantiate the command.

The problem with this approach is that nowadays it is common to use dependency injection in software solutions, and letting Sitecore take care of creating instances of your custom code means that you loose the possibility of injecting the needed dependencies. Luckily there is a way out of this morass.

Sitecore has created something called a CommandManager, which is used for registering, instantiating and looking up commands. The good news is that it is available for use.

So here is a suggestion on how to use it to obtain dependency injection in custom commands. It is based on using Autofac as IoC container.

First, create a base class for your commands:

namespace TestApp.Commands
{
public abstract class BaseCommand : Sitecore.Shell.Framework.Commands.Command
{
public string FullName { get; private set; }

protected BaseCommand(string fullName)
{
FullName = fullName;
}
}
}
Basically, we will just use this base class to "label" our custom commands, but it also has one property, FullName, for holding the command name for registration purposes.

Next, create your custom command inheriting from BaseCommand like this:
namespace TestApp.Commands
{
public class MyCommand : BaseCommand
{
private readonly IMyDependency _myDependency;

public MyCommand(string fullName, IMyDependency myDependency)
: base(fullName)
{
_myDependency = myDependency;
}

public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
{
// command implementation
}
}
}
As you can see we inject a dependency in the constructor. The constructor furthermore calls the base constructor to set the command name.

Now, create a class for registering custom commands using the Sitecore CommandManager:
namespace TestApp.Commands
{
public static class CommandConfigurator
{
public static void Configure(IEnumerable<BaseCommand> commands)
{
foreach (var command in commands)
{
Sitecore.Shell.Framework.Commands.CommandManager.RegisterCommand(command.FullName, command);
}
}
}
}
The Configure method takes a collection of BaseCommand objects (our custom command instances), then uses RegisterCommand method on the CommandManager to register the commands.

That is basically all the pieces we need. We just have to fit everything together in our bootstrapper (the place where all the dependencies are set up using the IoC container). This could look something like this:
...
var builder = new ContainerBuilder();

builder.RegisterType<MyDependency>().As<IMyDependency>().InstancePerLifetimeScope();

builder.RegisterType<MyCommand>().As<BaseCommand>().WithParameter("fullName", "mynamespance:mycategory:mycommand").InstancePerLifetimeScope();

var rootContainer = builder.Build();

var commands = rootContainer.Resolve<IEnumerable<BaseCommand>>();
CommandConfigurator.Configure(commands);
...
So we just register dependencies as usual. The new thing is that we now register our custom commands in code, instead of using a Sitecore config file. And then we call our CommandConfigurator with a collection of instances of all our custom commands.

That's it. Plain and simple :-)

Tuesday, December 10, 2013

Syncing a forked git repository with changes in the original repository

Using the built-in support for Git in Visual Studio 2013 is great... to a certain extent. Because eventually it will happen that you need to do some Git operation that is simply not supported. Having used Git on only one project so far it happened two times already that the built-in functionality wasn't enough.

The first situation was when I needed to revert a pushed commit. So I looked and looked in VS to locate such an action, but to no avail. Searching the Internet turned out people recommend using the command prompt. I opened a standard command prompt from Windows start menu and tried out the recommended Git commands, only to find out that it didn't work because it wasn't in a context of a repository (or something like that), and as I remembered it this was the case even if I navigated to the correct 'workspace' folder. After some more research it turns out that it is possible to open a Git-ish command prompt from VS (it is in the 'action' menu, available many places in the built-in Git client). Opening the command prompt this way places it in the correct context (not entirely sure how - maybe some environment variable is set). Anyway I was able to do the revert from there.

But this is really not what this article is about :-) No, what I want to describe here is how to synchronize a forked Git repository with changes in the original repository. So again I start a Git-ish command prompt, e.g. from 'Unsynched Commits' page in the Git client in VS. From there I execute the following commands:

First, link our repository with the remote (the original):
git remote add upstream [full-git-url-to-remote-repo]
Now, fetch changes:
git fetch upstream
Finally, do a merge, where [branch] can be master or some other branch:
git merge upstream/[branch]
That should do the trick. If there are any conflicts, they will now show up in VS and you can resolve them from there.

Thursday, October 24, 2013

Installing Solr 4.5 as a Windows service

I've recently had the good fortune to use the Solr search platform for a project. One thing, though, that is not straight forward is how to install Solr as a Windows service. There are several articles on the internet, but I couldn't find any that worked with Solr 4.5. So I gathered information from a number of out-dated articles and came up with the following approach, which has worked fine for me:

  1. Download Solr 4.5 (http://lucene.apache.org/solr/)
  2. Download the Non-Sucking Service Manager NSSM (http://nssm.cc/)
  3. Create a folder to be used for the Solr service (e.g. D:\solr). From now on this will be called <solrdir>
  4. From the example folder of the Solr package copy the following files and folders to <solrdir>:
    1. etc
    2. lib
    3. logs
    4. solr
    5. webapps
    6. start.jar
  5. In a command prompt go to <solrdir> and run the command java -jar start.jar to check that the Solr installation works. If it works then just stop it again.
  6. From the NSSM package copy nssm.exe to <solrdir>
  7. In a command prompt go to <solrdir> and run the command below. Note: it may be necessary to replace back-slashes in <solrdir> with forward-slashes.
    nssm.exe install Solr C:\Windows\System32\java.exe "-Dsolr.solr.home=<solrdir>/solr -Djetty.home=<solrdir>/ -Djetty.logs=<solrdir>/logs/ -cp <solrdir>/lib/*.jar;<solrdir>/start.jar -jar <solrdir>/start.jar"
To remove the service run the following command:
nssm.exe remove Solr

For convenience I've created the following batch script, which performs the nssm.exe install part. The script should be placed in <solrdir>.
@echo off
set currentdir=%~dp0
set parameters=-Dsolr.solr.home=""%currentdir%solr"" -Djetty.home=""%currentdir%"" -Djetty.logs=""%currentdir%logs/"" -cp ""%currentdir%lib/*.jar;%currentdir%start.jar"" -jar ""%currentdir%start.jar""

REM replace back-slashes with forward-slashes
set javaWeirdnessParameters=%parameters:\=/%

nssm.exe install Solr C:\Windows\System32\java.exe "%javaWeirdnessParameters%"

Wednesday, March 23, 2011

NServiceBus and SQLite in .NET 4.0

I've just used the better part of a day trying to figure out how to get System.Data.SQLite.dll to work with NServiceBus in a .NET 4.0 project in VS2010.


The problem is if you just set it up like normal, you'll get the following error:
"Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information."

This is because there's no .NET 4.0 version of the dll released yet (2011-03-23). There's only a .NET 2.0 version and it contains unmanaged code. So what we must do it to explicitly tell the project that it is ok to use the dll by adding some configuration. This solution is documented in many articles on the Internet, but I could not get it to work with NServiceBus - or rather the NServiceBus.Host.exe to be precise which actually makes all the difference.

As mentioned in various articles on the Internet I put the configuration in app.config of the project and then exactly nothing happened. After much frustration I stumbled over this article:
http://tech.dir.groups.yahoo.com/group/nservicebus/message/8951

The trick is to put the configuration in the NServiceBus.Host.exe.config file like this:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This is needed in order to get System.Data.SQLite to work in .NET 4.0, at least
until a .NET 4.0 compatible version of System.Data.SQLite is released. -->
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
</configuration>

NOTE: you must also ensure that the "Copy to Output Directory" setting for the config file is set to one of the copy options.

This did the trick.

Friday, March 18, 2011

Fuzzy text in VS2010

So I finally moved to Visual Studio 2010. This is a very nice IDE, but one thing that annoys me is that the text (code) seems fuzzy compared to VS2008. My eyes don't like it.


I googled it and there were several suggestions of using the free Visual Studio theme editor "Visual Studio Color Theme Editor":

However, this only allows for changing the theme of everything around the code area - not the code area itself.

Then I found some articles about the fonts used in VS2010 and it turned out that it uses a font called Consolas for the code whereas VS2008 uses Courier New. So I simply changed Consolas to Courier New in VS2010 and my eyes were instantly happy :-)

Tuesday, October 26, 2010

Transforming XML containing namespaces

Whenever I get the task of transforming some XML to some other XML using XSL and namespaces are involved it is always a struggle for some reason. And I've experienced that I'm not the only one having problems with that.

Most examples of XML transformation that I stumble over on the web deals with transforming XML to HTML and almost never use namespaces. Therefore I've decided to write a little article where I describe how to transform from XML to XML including the usage of namespaces.

The task
I want to transform an XML document containing information about CDs from one format into another using XSL. The source XML will use one namespace and the output XML another.

Source XML document
This is the source XML document that I want to transform. Notice that it uses the "http://schemas.maze-dev.blogspot.com/2010/catalog" namespace.

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog xmlns="http://schemas.maze-dev.blogspot.com/2010/catalog">
<name>Absolute Whatever Vol. 1</name>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
<cd>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
</catalog>
XSL transformation document
This is the transformation document. The xmlns:xsl="http://www.w3.org/1999/XSL/Transform" defines the standard 'xsl' transform namespace. However, the interesting part is xmlns="http://schemas.maze-dev.blogspot.com/2010/archive" which defines the output namespace (i.e. namespace in output XML) and xmlns:cat="http://schemas.maze-dev.blogspot.com/2010/catalog" which defines the namespace 'cat' used to reference elements in the input XML. The attribute exclude-result-prefixes="cat" states that the 'cat' namespace should not be included in the output XML.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://schemas.maze-dev.blogspot.com/2010/archive"
xmlns:cat="http://schemas.maze-dev.blogspot.com/2010/catalog" exclude-result-prefixes="cat">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
<archive>
<xsl:apply-templates select="cat:catalog"/>
</archive>
</xsl:template>
<xsl:template match="cat:catalog">
<name><xsl:value-of select="cat:name"/></name>
<xsl:apply-templates select="cat:cd"/>
</xsl:template>
<xsl:template match="cat:cd">
<album>
<title>Title: <xsl:value-of select="cat:title"/></title>
<artist>Artist: <xsl:value-of select="cat:artist"/></artist>
</album>
</xsl:template>
</xsl:stylesheet>
Output XML document
This is the output XML document. Notice that it uses the "http://schemas.maze-dev.blogspot.com/2010/archive" namespace that was specified in the XSL document.

<?xml version="1.0" encoding="UTF-8"?>
<archive xmlns="http://schemas.maze-dev.blogspot.com/2010/archive">
<name>Absolute Whatever Vol. 1</name>
<album>
<title>Title: Empire Burlesque</title>
<artist>Artist: Bob Dylan</artist>
</album>
<album>
<title>Title: Hide your heart</title>
<artist>Artist: Bonnie Tyler</artist>
</album>
<album>
<title>Title: Greatest Hits</title>
<artist>Artist: Dolly Parton</artist>
</album>
</archive>
So basically, that's it. Hope somebody finds it useful.