Using using to unbind event handlers

Dynamically binding event handlers is a common source of bugs, and memory leaks.

The traditional approach is to use a finally block:

	EventHandler eventHandler = (s, e) => fooService.Bar();
	eventSource.AnEvent += eventHandler;
	try
	{
		// do something that raises the event
	} 
	finally
	{
		eventSource.AnEvent -= eventHandler;
	}

An alternative way to ensure that your handler is always unbound correctly is to (ab)use IDisposable (again!) and use the using sugar:

		using (_eventHandlerFactory.Attach(_eventSource, _fooService))
		{
			// do something that raises the event
		}
	public class EventHandlerFactory
	{
		public IDisposable Attach(IEventSource eventSource, IFooService fooService)
		{
			EventHandler eventHandler = (s, e) => fooService.Bar();
			eventSource.AnEvent += eventHandler;
			return new EventHandlerCookie(eventSource, eventHandler);
		}

		private class EventHandlerCookie : IDisposable
		{
			private readonly IEventSource _eventSource;
			private readonly EventHandler _eventHandler;

			public EventHandlerCookie(IEventSource eventSource, EventHandler eventHandler)
			{
				_eventSource = eventSource;
				_eventHandler = eventHandler;
			}

			public void Dispose()
			{
				_eventSource.AnEvent -= _eventHandler;
			}
		}
	}

	public interface IFooService 
	{
		void Bar();
	}

	public interface IEventSource 
	{
		event EventHandler AnEvent;
	}

	[TestFixture]
	public class EventHandlerFactoryTests
	{
		private IEventSource _eventSource = MockRepository.GenerateStub<IEventSource>();
		private IFooService _fooService = MockRepository.GenerateStub<IFooService>();
		private EventHandlerFactory _eventHandlerFactory;

		[SetUp]
		public void SetUp()
		{
			_eventHandlerFactory = new EventHandlerFactory();
		}

		[Test]
		public void Event_handler_is_attached()
		{		
			_eventHandlerFactory.Attach(_eventSource, _fooService);
			_eventSource.Raise(es => es.AnEvent += null, _eventSource, EventArgs.Empty);

			_fooService.AssertWasCalled(fs => fs.Bar());
		}

		[Test]
		public void Event_handler_is_detached_when_disposed()
		{
			using (_eventHandlerFactory.Attach(_eventSource, _fooService))
			{
				_eventSource.Raise(es => es.AnEvent += null, _eventSource, EventArgs.Empty);
			}
			_eventSource.Raise(es => es.AnEvent += null, _eventSource, EventArgs.Empty);

			_fooService.AssertWasCalled(fs => fs.Bar(), o => o.Repeat.Once());
		}
	}

TransactionController

Transactions are a common cross-cutting concern, that need to be managed carefully.

You often want a transaction to be shared between multiple repositories, but you don’t want low level details (e.g. what ORM you are using) to bleed out of the persistence layer.

There’s also a lot of boiler plate code, and forgetting to commit the transaction is a common (and easy) mistake to make.

Bring the Func!

	public class TransactionController : ITransactionController
	{
		private readonly ISession _session;

		public TransactionController(ISession session)
		{
			_session = session;
		}

		public void InTransaction(Action action)
		{
			using (var transaction = _session.BeginTransaction())
			{
				action();
				transaction.Commit();
			}
		}
	}

	[TestFixture]
	public class TransactionControllerTests
	{
		private TransactionController _transactionController;
		private ISession _session;

		[SetUp]
		public void SetUp()
		{
			_session = MockRepository.GenerateStub<ISession>();
			_transactionController = new TransactionController(_session);
		}

		[Test]
		public void Begin_transaction()
		{
			StubTransaction();

			_transactionController.InTransaction(() => { });

			_session.AssertWasCalled(s => s.BeginTransaction());
		}

		[Test]
		public void Perform_action()
		{
			StubTransaction();
			var flag = false;

			_transactionController.InTransaction(() => { flag = true; });

			Assert.That(flag, Is.True);
		}

		[Test]
		public void Commit_transaction()
		{
			var transaction = StubTransaction();

			_transactionController.InTransaction(() => { });

			transaction.AssertWasCalled(t => t.Commit());
		}

		[Test]
		public void Dispose_transaction()
		{
			var transaction = StubTransaction();

			_transactionController.InTransaction(() => { });

			transaction.AssertWasCalled(t => t.Dispose());
		}

		[Test]
		public void Rollback_on_error()
		{
			var transaction = StubTransaction();

			try
			{
				_transactionController.InTransaction(() => { throw new Exception(); });
			}
			catch (Exception)
			{ }

			transaction.AssertWasNotCalled(t => t.Commit());
			transaction.AssertWasCalled(t => t.Dispose());
		}

		private ITransaction StubTransaction()
		{
			var transaction = MockRepository.GenerateStub<ITransaction>();
			_session.Stub(s => s.BeginTransaction()).Return(transaction);
			return transaction;
		}
	}

This can also be done using an AOP framework (like PostSharp) but, having tried that, I prefer it to be explicit in the code.

A better XmlWriter

I’m not a huge fan of the XmlWriter API. In particular, remembering to close every tag.

It would be nice to have something like Haml, where the nesting takes care of it. A bit tricky in C#, but you can get some of the effect by (ab)using IDisposable:

public class SelfClosingXmlWriter
{
    private readonly XmlWriter _xmlWriter;

    public SelfClosingXmlWriter(XmlWriter xmlWriter)
    {
        _xmlWriter = xmlWriter;
    }

    public XmlElementCookie WriteStartElement(string localName)
    {
        _xmlWriter.WriteStartElement(localName);
        return new XmlElementCookie(_xmlWriter);
    }

    public XmlAttributeCookie WriteStartAttribute(string localName)
    {
        _xmlWriter.WriteStartAttribute(localName);
        return new XmlAttributeCookie(_xmlWriter);
    }

    public void WriteRaw(string xml)
    {
        _xmlWriter.WriteRaw(xml);
    }

    public void WriteString(string xml)
    {
        _xmlWriter.WriteString(xml);
    }

    public void WriteAttributeString(string localName, string value)
    {
        _xmlWriter.WriteAttributeString(localName, value);
    }

    public class XmlElementCookie : IDisposable
    {
        private readonly XmlWriter _xmlWriter;

        public XmlElementCookie(XmlWriter xmlWriter)
        {
            _xmlWriter = xmlWriter;
        }

        public void Dispose()
        {
            _xmlWriter.WriteEndElement();
        }
    }

    public class XmlAttributeCookie : IDisposable
    {
        private readonly XmlWriter _xmlWriter;

        public XmlAttributeCookie(XmlWriter xmlWriter)
        {
            _xmlWriter = xmlWriter;
        }

        public void Dispose()
        {
            _xmlWriter.WriteEndAttribute();
        }
    }
}

Which lets you go from this:

var writer = XmlWriter.Create("out.xml", settings);
writer.WriteStartElement("book");
writer.WriteStartElement("author");
writer.WriteStartElement("name");
writer.WriteString("Big John");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteStartElement("title");
writer.WriteString("Amazing Cakes!");
writer.WriteEndElement();
writer.WriteEndElement();

To this:

var writer = new SelfClosingXmlWriter(XmlWriter.Create("out.xml", settings));
using (writer.WriteStartElement("book"))
{
    using (writer.WriteStartElement("author"))
    {
        using (writer.WriteStartElement("name"))
        {
            writer.WriteString("Big John");
        }
    }
    using (writer.WriteStartElement("title"))
    {
        writer.WriteString("Amazing Cakes!");
    }
}

Encrypting external config sections (using PowerShell)

The .Net framework allows you to encrypt sections of your configuration files, e.g. connection strings. If they live in the web.config it’s very simple:

aspnet_regiis -pe "connectionStrings"

Unfortunately, for those of us who like to keep our connection strings in an external config section, it can be a little more convoluted.

A bit of Googling turned up a couple of blog posts & Stack Overflow answers pointing in the right direction, and after a few hiccups (encrypting the machine.config by accident!) here’s a script that does the job:

param(
  [String] $configFilePath = $(throw "Config file path is mandatory"),
  [String] $sectionName = "connectionStrings",
  [String] $dataProtectionProvider = "DataProtectionConfigurationProvider"
)
 
#The System.Configuration assembly must be loaded
$configurationAssembly = "System.Configuration, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"
[void] [Reflection.Assembly]::Load($configurationAssembly)
 
$configurationFileMap = New-Object -TypeName System.Configuration.ExeConfigurationFileMap
$configurationFileMap.ExeConfigFilename = $configFilePath
$configuration = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($configurationFileMap, [System.Configuration.ConfigurationUserLevel]"None")
$section = $configuration.GetSection($sectionName)
 
if (-not $section.SectionInformation.IsProtected)
{
  Write-Host "Encrypting configuration section..."
  $section.SectionInformation.ProtectSection($dataProtectionProvider);
  $section.SectionInformation.ForceSave = [System.Boolean]::True;
  $configuration.Save([System.Configuration.ConfigurationSaveMode]::Modified);
  Write-Host "Succeeded!"
}

StructureMapAssert

Following on from a previous post, here’s an updated set of StructureMap assertions:

public static class StructureMapAssert
{
	public static void AssertSingleton<T>(this IContainer container)
	{
		var instance1 = AssertResolvable<T>(container);
		var instance2 = AssertResolvable<T>(container);
		Assert.That(instance1, Is.SameAs(instance2));
	}

	public static void AssertTransient<T>(this IContainer container)
	{
		var instance1 = AssertResolvable<T>(container);
		var instance2 = AssertResolvable<T>(container);
		Assert.That(instance1, Is.Not.SameAs(instance2));
	}

	public static void AssertHttpRequestScoped<T>(this IContainer container)
	{
		T instance2;
		using (new MockHttpContext())
		{
			var instance1 = AssertResolvable<T>(container);
			instance2 = AssertResolvable<T>(container);
			Assert.That(instance1, Is.SameAs(instance2));
		}
		var instance3 = AssertResolvable<T>(container);
		Assert.That(instance3, Is.Not.SameAs(instance2));
	}

	private static T AssertResolvable<T>(this IContainer container)
	{
		try
		{
			return container.GetInstance<T>();
		}
		catch (Exception)
		{
			Console.WriteLine(container.WhatDoIHave());
			throw;
		}
	}

	private class MockHttpContext : IDisposable
	{
		private readonly StringWriter _stringWriter;
		private readonly HttpContext _httpContext;

		public MockHttpContext()
		{
			_httpContext = HttpContext.Current;
			var httpRequest = new HttpRequest("test.aspx", "http://localhost", "?a=1&amp;b=2");
			_stringWriter = new StringWriter();
			var httpResponse = new HttpResponse(_stringWriter);
			HttpContext.Current = new HttpContext(httpRequest, httpResponse);
		}

		public void Dispose()
		{
			_stringWriter.Dispose();
			HttpContext.Current = _httpContext;
		}
	}
}
public class RegistryTests
{
    private IContainer container;
    [TestFixtureSetUp]
    public void FixtureSetUp()
    {
        container = BootstrapContainer();
    }

    [Test]
    public void SessionFactory()
    {
        container.AssertSingleton<ISessionFactory>();
    }

    [Test]
    public void Session()
    {
        container.AssertHttpRequestScoped<ISession>();
    }

    [Test]
    public void ThingyRepository()
    {
        container.AssertTransient<IThingyRepository>();
    }
}

Rewriting operations with OpenRasta

One of the myriad of extension points that OpenRasta offers, is the operation interceptor. There’s a base class, called OperationInterceptor, that makes it convenient to override the method(s) you are interested in and provides a default (null) implementation for the others.

The IOperationInterceptor interface provides three methods:

  • BeforeExecute: returns a boolean, allowing you to stop the pipeline. Useful for validation, for example.
  • RewriteOperation
  • AfterExecute: post-processing, also returns a boolean.

RewriteOperation is particularly interesting. The signature:

Func<IEnumerable<OutputMember>> RewriteOperation(Func<IEnumerable<OutputMember>> operationBuilder);

while a little frightening, reveals the intention. It’s basically a decorator, allowing you to wrap your operation with some other behaviour. Logging, for example, or exception handling.

public class ExceptionHandlerOperationInterceptor : OperationInterceptor
{
	private readonly ILogger _logger;

	public ExceptionHandlerOperationInterceptor(ILogger logger) 
	{
		_logger = logger;
	}

	public override Func<IEnumerable<OutputMember>> RewriteOperation(Func<IEnumerable<OutputMember>> operationBuilder)
	{
		return () => TryExecute(operationBuilder);
	}

	private IEnumerable<OutputMember> TryExecute(Func<IEnumerable<OutputMember>> operationBuilder) 
	{
		try
		{
			return operationBuilder();
		}
		catch (TargetInvocationException ex)
		{
			_logger.WriteException(ex.InnerException);
			return ReturnBadRequest(ex.InnerException);
		}
	}

	private static IEnumerable<OutputMember> ReturnBadRequest(Exception ex) {
		var errors = new List<Error> 
		{ 
			new Error
			{
				Exception = ex,
				Message = ex.Message,
			}
		};

		return new[]
		{
			new OutputMember
			{
				Value = new OperationResult.BadRequest
				{
					ResponseResource = new ErrorResource(),
					Errors = errors
				}
			}
		};
	}
}

Managing multiple Session Factories using named instances

If you are using NHibernate for data access, and have to access more than one database, then you need a way of managing multiple Session Factories.

Ideally, your repositories (or whatever) would only take a dependency on an ISession, without needing to know where it came from (DIP). But if you’re getting these repositories out of a container, then you have a problem. How do you provide a different ISession to different instances?

One solution is to use named instances. The following example is for StructureMap, other containers are available. :)

public class NHibernateRegistry : Registry
{
    public NHibernateRegistry()
    {
        const string connectionString1 = "theNameOfAConnectionStringInAppConfig";
        const string connectionString2 = "theNameOfADifferentConnectionStringInAppConfig";

        For<ISessionFactory>()
            .Singleton()
            .Use(SessionFactory.BuildFor(connectionString1))
            .Named(connectionString1);

        For<ISessionFactory>()
            .Singleton()
            .Use(SessionFactory.BuildFor(connectionString2))
            .Named(connectionString2);

        For<ISession>()
            .Use(c => c.GetInstance<ISessionFactory>(connectionString1).OpenSession())
            .Named(connectionString1);

        For<ISession>()
            .Use(c => c.GetInstance<ISessionFactory>(connectionString2).OpenSession())
            .Named(connectionString2);

        For<ISomethingRepository>()
            .Ctor<ISession>("session").Use(c => c.GetInstance<ISession>(connectionString1));

        For<ISomethingElseRepository>()
            .Ctor<ISession>("session").Use(c => c.GetInstance<ISession>(connectionString2));
    }
}

Or maybe, in the future, just:

For<ISomethingElseRepository>()
    .Ctor<ISession>("session").Named(connectionString2);

Register concrete types against the first interface

Most of my IoC experience has been using StructureMap, with the default conventions:

container.Configure(c => c.Scan(s =>
    {
        s.Assembly(GetType().Assembly);
        s.LookForRegistries();
        s.WithDefaultConventions();
    }));

Which registers any components whose name matches the interface, minus the I, e.g. ThingyController : IThingyController, but not DefaultThingyRepository : IThingyRepository.

Recently however, I’ve worked on a few projects using Castle Windsor, whose auto-registration uses the first interface:

 container.Register(AllTypes
    .FromAssembly(GetType().Assembly)
    .Pick()
    .WithService.FirstInterface()
    .Configure(req => req.LifeStyle.Transient));

What a great idea, I thought! Why can’t I do that with StructureMap? Well the short answer is, you can:

container.Configure(c => c.Scan(s =>
    {
        s.Assembly(GetType().Assembly);
        s.LookForRegistries();
        s.RegisterConcreteTypesAgainstTheFirstInterface();
    }));

Hurray!

Releasing http scoped objects when using OpenRasta with StructureMap

StructureMap isn’t quite as pro-active as Castle Windsor when it comes to releasing (and disposing) of http scoped objects. So it’s generally a good practice to do so explicitly at the end of a web request:

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

My first attempt to reproduce this with OpenRasta used a pipeline contributor:

using OpenRasta.Pipeline;
using OpenRasta.Web;
using StructureMap.Pipeline;

namespace OpenRasta.DI.StructureMap.Pipeline.Contributors
{
	public class ReleaseAndDisposeAllHttpScopedObjects : IPipelineContributor
	{
		public void Initialize(IPipeline pipelineRunner)
		{
			pipelineRunner.Notify(ReleaseAndDispose)
				.After<KnownStages.IOperationExecution>()
				.And.Before<KnownStages.IOperationResultInvocation>();
		}

		private static PipelineContinuation ReleaseAndDispose(ICommunicationContext communicationContext)
		{
			HttpContextLifecycle.DisposeAndClearAll();
			return PipelineContinuation.Continue;
		}
	}
}

Thankfully, Seb pointed out that it made more sense to hook into IDependencyResolver.HandleIncomingRequestProcessed():

public void HandleIncomingRequestProcessed()
{
    HttpContextLifecycle.DisposeAndClearAll();
}

Assert.Throws with NHamcrest

NHamcrest is a C# port of Hamcrest, a popular matching library. I recently added support for Assert.Throws:

    [Test]
    public void Throws()
    {
        Assert.That(() => { throw new ArgumentNullException(); }, 
            Throws.An<ArgumentNullException>());

        // with a predicate
        Assert.That(() => 
            { 
                throw new ArgumentNullException("message", new Exception()); 
            }, Throws.An<ArgumentNullException>()
            .With(e => e.Message == "message" && e.InnerException.GetType() == typeof(Exception)));
    }