Damian Hickey

Mostly software and .NET related. Mostly.

Testing your OWIN application

One of the great things about OWIN is the ability to write tests without having any environmental dependencies (i.e. IIS)  or complicated setup with sperate AppDomains (System.Web.Hosting.ApplicationHost).

Given the following contrived OWIN Startup class that returns OK to all requests...

public class Startup
{
	public void Configuration(IAppBuilder appBuilder)
	{
		appBuilder.UseHandler((request, response) =>
			{
				response.StatusCode = 200;
				response.ReasonPhrase = "OK";
			});
	}
}

('UseHandler' is from the Owin.Extensions package which provides a typed wrapper of convenience around the environment dictionary.)

How do we test this?

First add a package reference to Microsoft.Owin.Testing. As of writing it's prerelease, so don't forget the -pre flag.

Then simply create a TestServer to host your OWIN app, and using the supplied HttpClient, invoke a request like you would against any other web site:

[Fact]
public async Task Should_get_OK()
{
	TestServer testServer = TestServer.Create(appBuilder => new Startup().Configuration(appBuilder));
	HttpResponseMessage response = await testServer.HttpClient.GetAsync("/");
	Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

How sweet is that!

Now you can write simple, fast, in-memory, multiple-web-framework acceptence tests. This, to me, is one of the killer features of OWIN.

Browse sample project on github.

Owin HttpMessageHandler

Your typical web service call to an OWIN based application goes through the following path:

The purpose of OwinHttpMessageHandler is to allow you to do this:

This is useful for:

  1. End-to-end testing where you don't want to hit the network stack for performance or build server reasons.
  2. Testing your owin middleware or owin compatible framework.
  3. Invoking web service http endpoints or issuing requests against web applications in embedded scenarios through a common pipeline.

Feeback welcome, as always.

Running RavenDB with OWIN and Katana

Just completed this spike and I'm happy with the outcome. Will post solution to Github soon.

Edit: Code available.

How I am using OWIN

Using OWIN has enabled me to build an application server with the following features:

  • Self-hosted web apps and services using various frameworks
  • Unified authentication mechanism
  • Ability to DI my application's services into Fubu controllers, ServiceStack services, SignalR PersistentConnections etc
  • Simpler end-to-end acceptance tests without having to go through the network stack
  • All assets (html, css, js, etc) are embedded resources
  • A delightfully simple deployment - a single .exe

I like this..  a lot! Nice job OWIN crew and supporting framework devs.

It is not possible to do this with asp.net due to it's tight coupling with IIS, but it looks like it will support OWIN in the future.

* Just a note on the diagram - RavenDB doesn't support owin yet, but I intend to tackle it soon.

Update: I'm in the process of reducing the number of components in this, specifically replacing the FubuMVC component with NancyFX. Mostly because of maintainance and future development and not anything owin specific.

Ensuring that Dispose() gets called on your IDisposable types

Here is a neat trick to make sure you IDisposable classes have their dispose method called. In the finalizer, call Debug.Fail and only include it in Debug builds:

public class DisposableClass : IDisposable
	{
		public void Dispose()
		{
			//The usual cleanup
#if DEBUG
			GC.SuppressFinalize(this);
#endif
		}

#if DEBUG
		~DisposableClass()
		{
			Debug.Fail(string.Format("Undisposed {0}", GetType().Name));
		}
#endif
	}

This will give you an in-your-face dialog to let you know of your fail:

I can't claim that I came up with this, but I can't remember where I saw it either.

Getting contextual state into a RavenDB's document store listener

Scenario: In multi-thread message driven application, I want to add contextual metadata to each and every modified and stored document. I would like to encapsulate this feature in such a way as so that it is done in one place and does not burden the event handlers with the responsibility.

An event handler may be supplied by seperate assembly and a contrived one that creates documents from events may look something like this:

public class MyEventHandler : IHandle<MyEvent>()
{
    private readonly IDocumentStore _store;
    
    public MyEventHandler(IDocumentStore store)
    {
        _store = store;
    }
    
    public void Handle(MyEvent @event)
    {
        using(var session = _store.OpenSession())
        {
            var doc = new MyDocument { // Populate properties from message };
            session.Store(doc);
            session.SaveChanges();
        }
    }
}

This handler is typically invoked at the point where the message enters this system in the main application and then

public void OnMessage<T>(Message<T> message)
{
    var handlers = _handlerResolver.ResolveAll<T>();
    foreach(var handler in handlers)
    {
        handler.Handle(message.Body);
    }
}

This method is reentrant and may (will) be called from more than one thread as the same time.

I would like to add contextual information, here message.Id, to each document that is created or modified as a result handling this message. Do do so I need to intercept the document etity instance just before it is saved. This is achieved through implementing the IDocumentStoreListener interface which looks like...

public interface IDocumentStoreListener
{
    void AfterStore(string key, object entityInstance, RavenJObject metadata);
    bool BeforeStore(string key, object entityInstance, RavenJObject metadata);
}

DocumentStoreListeners are registered before initializing the document store and like the DocumentStore, the listener's lifecyle is singleton with respect to the main application. Therefore it must be reentrant and thread safe.

var store = new DocumentStore { // Uri = etc };
store.RegisterListener(new EventIdDocumentStoreListener);
store.Initialize();

...where my implementation may look something like this (just BeforeStore() implemention shown for berevity):

public class EventIdDocumentStoreListener : IDocumentStoreListener
{
    public const string PropertyName = "LastMessageId";
    
    public bool BeforeStore(string key, object entityInstance, RavenJObject metadata)
    {
        RavenJToken token = RavenJToken.FromObject(messageId);
        if (metadata[PropertyName] == null)
        {
            metadata.Add(PropertyName, token);
        }
        else
        {
            metadata[PropertyName] = token;
        }
        return false;
    }
}

See the problem here? I have no obvious mechanism to supply the messageId into this method from which the RavenJToken is then constructed from. The solution I have arrived at is to use thread local storage, specifically .NET4's ThreadLocal<T>. This will allow me to store messageId value in a place that is specific to the running thread. I set it in the OnMessage dispatcher and pick it up in the listener. This ThreadLocal instance is also singleton with respect to the main application.

Now our listener will depend on a ThreadLocal:

public class EventIdDocumentStoreListener : IDocumentStoreListener
{
    public const string PropertyName = "LastMessageId";
    private readonly ThreadLocal<Guid> messageIdThreadLocal;
    
    public EventIdDocumentStoreListener(ThreadLocal<Guid> messageIdThreadLocal)
    {
        _messageIdThreadLocal = messageIdThreadLocal;
    }
    
    bool BeforeStore(string key, object entityInstance, RavenJObject metadata)
    {
            RavenJToken token = RavenJToken.FromObject(_messageIdThreadLocal.Value);
            if (metaData["LastMessageId"] == null)
            {
                metaData.Add(PropertyName, token);
            }
            else
            {
                metaData["LastMessageId"] = token;
            }
        }
    }
}

And our OnMessage dispatcher can set the message ID for the specific thread before calling the handlers:

public void OnMessage<T>(Message<T> message)
{
    var handlers = _handlerResolver.ResolveAll<T>();
    _messageIdThreadLocal.Value = message.Id;
    foreach(var handler in handlers)
    {
        handler.Handle(message.Body);
    }
}

So that is how I supply contextual state to a listeners in a safe and transparent manner.

Notes
- This code above is to demonstrate using ThreadLocal to pass contextual state into a RavenDB IDocumentStoreListener. It does not represent a production quality solution :)
- This solution does not work in an asp.net / wcf environment. Modifying above to do that is left as an exercise to the reader (hint: HttpContext.Items)

Getting a document's metadata in RavenDB via client API without loading the document

In an upcoming build of RavenDB (current is 588) you will be able get document's metadata wiithout having to loading it:

JsonDocumentMetadata docMetaData = store.DatabaseCommands.Head(string key);
...where docMetaData will be null when the document does not exist.

If all you want to do is check if it exists, one can use an extension method (guards omitted for berevity):

public static cass IDocumentStoreExtensions
{
	public static bool Exists(this IDocumentStore documentStore, string key)
	{
		return documentStore.DatabaseCommands.Head(key) != null;
	}
}

Putting exception message into NLog's Chainsaw log4j xml output

It doesn't appear possible to get exception infomation into the chainsaw target renderer, so I got around this by extending the Log4JXmlEventLayout and butchering the xml.

Chalk this one up as a nasty hack, it's not pretty.

[Target("ChainsawExtended")]
public class ChainsawExtendedTarget : ChainsawTarget
{
    private readonly Log4JXmlEventLayoutExtended _layout = new Log4JXmlEventLayoutExtended();

    public override Layout Layout
    {
        get { return _layout; }
        set { }
    }

    private class Log4JXmlEventLayoutExtended : Log4JXmlEventLayout
    {
        protected override string GetFormattedMessage(LogEventInfo logEvent)
        {
            string s = base.GetFormattedMessage(logEvent);
            if(logEvent.Exception == null)
            {
                return s;
            }
            s = s.Replace("<log4j:event", "<log4j:event xmlns:log4j=\"http://nlog-project.org/dummynamespace/\"");
            var element = XDocument.Parse(s);
            var messageElement = element.Descendants().Where(e => e.Name.LocalName == "message").Single();
            messageElement.Value += Environment.NewLine + logEvent.Exception;
            s = element.ToString();
            s = s.Replace(" xmlns:log4j=\"http://nlog-project.org/dummynamespace/\"", string.Empty);
            return s;
        }
    }
}

Ninject's InjectAttribute on an interface member

Say you interface where you wish to property / method inject a service when activating implementors:

public interface IServiceConsumer
{
	[Inject]
	ISomeService Service { get; set; }

	[Inject]
	void SetService(ISomeService service);
}

The problem is that implementors of this interface will not 'inherit' these [Inject] attributes, by design. Thus Ninject won't see the attribute and won't inject when activating.

To solve this I've created a custom injection heuristic that inspects a member type's interface map to see if the member of concern:

  1. implements an interface method that ithat has the desired attribute.
  2. is a interface property set_ method whose corresponding property has the desired attribute.

 It also works with your own custom injection attribute if you are using one with via the T type paramater.

public class InterfaceInjectAttributeInjectionHeuristic<T> : NinjectComponent, IInjectionHeuristic
	where T:Attribute
{
	public bool ShouldInject(MemberInfo member)
	{
		foreach (Type @interface in member.DeclaringType.GetInterfaces())
		{
			InterfaceMapping interfaceMapping = member.ReflectedType.GetInterfaceMap(@interface);
			int index = Array.IndexOf(interfaceMapping.TargetMethods, member);
			if (index < 0)
			{
				continue;
			}
			MethodInfo interfaceMethod = interfaceMapping.InterfaceMethods[index];
			Contract.Assume(interfaceMethod != null);
			member = GetProperty(interfaceMethod) ?? interfaceMethod;
			return member.GetCustomAttributes(true).Any(a => a.GetType() == typeof(T));
		}
		return false;
	}

	static MemberInfo GetProperty(MethodInfo method)
	{
		bool takesArg = method.GetParameters().Length == 1;
		bool hasReturn = method.ReturnType != typeof(void);
		if (takesArg == hasReturn)
		{
			return null;
		}
		return takesArg ? method.DeclaringType.GetProperties().Where(prop => prop.GetSetMethod() == method).FirstOrDefault() : null;
	}
}

Now whether this is actually  a good idea or not, I'll leave it you to decide, but it helped me solve a problem. Feedback always welcome.

For completeness here are my tests:

using Ninject;
using Ninject.Selection.Heuristics;
using Xunit;

public class InterfaceInjectAttributeInjectionHeuristicTests
{
	public class Given_a_kernel_resolved_component
	{
		private readonly MyComponent _sut;

		public Given_a_kernel_resolved_component()
		{
			var standardKernel = new StandardKernel();
			standardKernel.Components.Add<IInjectionHeuristic, InterfaceInjectAttributeInjectionHeuristic<InjectAttribute>>();
			standardKernel.Bind<ISomeService>().To<SomeServiceImpl>();
			_sut = standardKernel.Get<MyComponent>();
		}

		[Fact]
		public void Then_Service_should_not_be_null()
		{
			Assert.NotNull(_sut.Service);
		}

		[Fact]
		public void Then_SetSerervice_should_be_called()
		{
			Assert.True(_sut.SetServiceCalled);
		}
	}
}

public interface ISomeService {}

public interface IServiceConsumer
{
	[Inject]
	ISomeService Service { get; set; }

	[Inject]
	void SetService(ISomeService service);
}

public class SomeServiceImpl : ISomeService { }

public class MyComponent : IServiceConsumer
{
	public ISomeService Service { get; set; }

	public void SetService(ISomeService service)
	{
		SetServiceCalled = service != null;
	}

	public bool SetServiceCalled { get; private set; }
}

CA1810 - A reason to not disable this rule

Run this code and you'll see why the rule is there in the first place.

 

using System;
using System.Diagnostics;
using System.Windows;

internal class Program
{
	private static void Main(string[] args)
	{
		const int upper = 1000000;
		var stopwatch = new Stopwatch();
		stopwatch.Start();
		for (int i = 0; i < upper; i++)
		{
			string name = WithoutStaticCtor.DependencyProperty.Name;
		}
		stopwatch.Stop();
		long withoutStaticCtorTicks = stopwatch.ElapsedTicks;
		stopwatch.Restart();
		for (int i = 0; i < upper; i++)
		{
			string name = WithStaticCtor.DependencyProperty.Name;
		}
		stopwatch.Stop();
		long withStaticCtorTicks = stopwatch.ElapsedTicks;
		Console.WriteLine(string.Format("With static ctor: {0} ticks", withStaticCtorTicks));
		Console.WriteLine(string.Format("Without static ctor: {0} ticks", withoutStaticCtorTicks));
		Console.WriteLine(string.Format("Without static ctor is over {0} times faster!", withStaticCtorTicks / withoutStaticCtorTicks));
		Console.ReadLine();
	}
}

public class WithStaticCtor : DependencyObject
{
	public static readonly DependencyProperty DependencyProperty = DependencyProperty.Register("Prop", typeof(int), typeof(WithStaticCtor));

	static WithStaticCtor()
	{
		int i = 1;
	}
}

public class WithoutStaticCtor : DependencyObject
{
	public static readonly DependencyProperty DependencyProperty = DependencyProperty.Register("Prop", typeof(int), typeof(WithoutStaticCtor));
}

The performance penalty for a single access to a static field on a class with a static contructor s almost immeasurable, but for something like WPF, it could add up.