Tuesday, July 15, 2014

AutoMapper Children Value Resolver

When exposing data to the outside world (e.g. through a service) one could easily find oneself thinking about such matters as performance and load on the wire.

We may have a scenario where we need to expose a customer service, which could be used in different scenarios, where sometimes callers just want customer master data, and at other times callers want customers with their order history. Depending on the system landscape order data may come from another system than where the customer data is stored; and these systems may perform differently, so that retrieval of customer data could be a relatively inexpensive operation, whereas retrieval of order data could be more expensive.

A common practice when creating services is to transform the entities from the domain into DTO objects, and a widely used component for this is AutoMapper. But how to get AutoMapper to deal with the scenario above?

As stated, sometimes we want to expose only customer data, and sometimes order data should be included. The domain may have been implemented as an aggregate, where a customer has a collection of orders, like this:

public class Order
{
    public Guid Id { get; set; }
    public DateTime Created { get; set; }
    public string Text { get; set; }
}

public class Customer
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public IEnumerable<order> Orders { get; set; }
}

And DTOs like this (for some reason we don't want to expose the internal IDs):

public class OrderDto
{
    public DateTime Created { get; set; }
    public string Text { get; set; }
}

public class CustomerDto
{
    public string Name { get; set; }
    public string Address { get; set; }
    public IEnumerable<Order> Orders { get; set; }
}

The data retrieval code may have been implemented with lazy load, so that order data is only queried if used. However, since AutoMapper will map the Orders collection by default, orders will be queried. So we need to modify the way customers are mapped. To that end I've devised an IValueResolver called ChildrenResolver. It is a general resolver that can be used for any child collection, and it looks like this:

public class ChildrenResolver<TSource, TMember> : IValueResolver
{
    private readonly Func<TSource, IEnumerable<TMember>> _childrenExpression;

    public ChildrenResolver(Expression<Func<TSource, IEnumerable<TMember>>> childrenExpression)
    {
        _childrenExpression = childrenExpression.Compile();
    }

    public ResolutionResult Resolve(ResolutionResult source)
    {
        bool includeChildren = false;
        if (source.Context.Options.Items.ContainsKey("IncludeChildren"))
        {
            includeChildren = (bool)source.Context.Options.Items["IncludeChildren"];
        }
        return source.New(includeChildren ? _childrenExpression.Invoke((TSource)source.Value) : null);
    }
}

The constructor takes an expression selecting the children collection member from the source entity, i.e. in our scenario it tells the resolver that we want to map the Orders property of the Customer entity. The Resolve method first looks up an options item called IncludeChildren, which is a boolean that we will set from the outside. It tells the resolver whether or not we want it to resolve the specified children collection property, and if so it returns a ResolutionResult with the children collection.

The ChildrenResolver is then used when defining a mapping, like this:

Mapper.CreateMap<Customer, CustomerDto>()
    .ForMember(dto => dto.Orders, opt => opt
        .ResolveUsing<ChildrenResolver<Customer, Order>>()
        .ConstructedBy(() => new ChildrenResolver<Customer, Order>(entity => entity.Orders)));

The mapping defines that we want to map from Customer entity to CustomerDto, and for the Orders member of the DTO we want to use the ChildrenResolver, which is instructed to grab the Orders collection of the Customer entity (this gives the flexibility of not having a one-to-one naming relationship between source and target properties.) Notice the usage of ResolveUsing is a bit more complex than typically seen. Since the ChildrenResolver takes a constructor parameter, we need to tell AutoMapper that we will handle the resolver instantiation ourselves, which we do by using ConstructedBy method.

Finally, we are ready to use the whole thing in our customer service, which may be a WebApi controller with the following method:

[Route("api/customers/{id}")]
public CustomerDto GetCustomer(Guid id, bool includeChildren = false)
{
    var customer = _customerRepository[id];
    if (customer == null)
    {
        // todo: handle if customer not found
    }

    var customerDto = Mapper.Map<CustomerDto>(customer, opts =>
    {
        opts.Items["IncludeChildren"] = includeChildren;
    });
    
    return customerDto;
}

Notice that when we do the mapping, we set the IncludeChildren options item to specify whether or not we want children collections mapped, and in this case that information comes from a service parameter.

That's it. I hope someone finds this useful :-)

Notes:
The code is based on usage of AutoMapper version 3.2.1.

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 :-)