Damian Hickey

Mostly software and .NET related. Mostly.

Introducing Owin.Testing

Owin.Testing is discontinued. Use Microsoft.Owin.Testing instead.

Continuing in my mini-series of introductions, Owin.Testing (nuget, github) is an OSS helper library to host your OWIN application and, by using Owin.HttpMessageHandler, make in-memory testing of OWIN applications simple, fast, and environment dependency free. The method by which your application is invoked is using an HttpClient - a similar mechansim from which your users will be interacting with your application. Cookies support is supported by default (and can be turned off).

An example best demonstrates how this works:

OwinTestServer owinTestServer = OwinTestServer.Create(builder => new Startup().Configuration(builder));
HttpClient httpClient = owinTestServer.CreateHttpClient();

HttpResponseMessage response = await httpClient.GetAsync("http://localhost");

  1. Line #1 is how we create the test server. The Startup class is the class that defines your OWIN application.
  2. Line #2 is how we create the HttpClient that is internally configured to invoke your OWIN app's root application delegate.
  3. Line #3 & #4 is how we invoke and assert our application. (The assertion here uses the excellent FluentAssertions library).

And that's it! Fast, in-memory, CI friendly OWIN testing :)

A note on Owin.Testing history - I originally started this based of code from Gate. Later, Microsoft.Owin.Testing appeared which is similar, but has since been delisted. I have used some of the code from that. As far as I know at this point, there are no plans to revive Microsoft.Owin.Testing. So for the time being, I'll be continuing to maintain this.

Introducing Owin.SiteMapping

Owin.SiteMapping (nuget, github) is an OWIN middleware analgous to IIS's site mapping. That is, it allows you to partition your OWIN app according to host header, http scheme and port number.

Sometimes an example is best:

public class Startup
  public void Configuration(IAppBuilder builder)
      .MapSite(new SiteMap("www.example.com"), main => main.Use(...))
      .MapSite(new SiteMap("admin.example.com", HttpScheme.Https, 443), admin => admin.Use(...));

Here, all requests with host header 'www.example.com', regardless of http scheme or port will be routed down the 'main' OWIN branch. Whereas all requests for 'admin.example.com', only on Https and port 443, will be routed down the admin branch.


Bug reports, suggestions and contributions welcome.

Introducing Owin.EmbeddedResources

Update: this post is out of date. The core functionality has been imported into  Microsoft.Owin.StaticFiles. I've de-listed the Owin.EmbeddedResources package.

This library contains an implementation of IFileSystem which is a file system abstraction used by Microsoft.Owin.StaticFiles - a OWIN middleware for serving static content, directory browsing etc. (It isn't available on nuget.org yet, pending security review. It can be obtained from katana CI feed for now).

How to use.

1. Embed your static content as a resource: 

2a. In your OWIN Startup class, specify the IFileSystem implementation, EmbeddedResourceFileSystem:

public class Startup
  public void Configuration(IAppBuilder builder)
    builder.UseStaticFiles(config => config.WithFileSystem(new EmbeddedResourceFileSystem())));

This will default to using the calling assembly as the source of the embedded content.

2b. If your resources are in a different assembly you can specify the assembly in the EmbeddedResourceFileSystem constuctor:

public class Startup
  public void Configuration(IAppBuilder builder)
    builder.UseStaticFiles(config => config.WithFileSystem(new EmbeddedResourceFileSystem(typeof(Foo).Assembly)));

The Static files middleware has full support for generating etags and response content types based on extensions.


Embedded resources lose their folder structure when compiled in. For instance, embedding Resources\Area\Foo.bar will become Resources.Area.Foo.Bar, and embedding Resources\Area.Foo.Bar will also become Resources.Area.Foo.Bar. (Trying to do this with two files won't compile). Due to this non-transitive nature, it is not possible infer the directory from whence an embedded resource originally came from. Thus, directory browsing is not supported in this IFileSystem implementation.

Owin.HttpMessageHandler is now portable

As of version 0.3, Owin.HttpMessageHandler (nuget.org, github) is now shipped as portable class library supporting .NET 4.0 and later, Silverlight 4.0 and later, Windows 8.0 and WindowsPhone 7.1. The ability to customize the owin environment before and after handling the request has been added as well as better support for http 1.1 that requires a host header.

A word NEventStore concurrency

NEventStore implements optomistic concurrency for Commits based on the StreamId and CommitSequence (and BucketId in v5). The exact implementation of which depends on the persistence engine. For instance, for SQL storage engines it is enforced by a primary key. This means if you open the same stream twice concurrently, add a commit, and close, you will get a ConcurrencyException:

IStoreEvents store = Wireup

Guid streamId = Guid.NewGuid();
using (var stream1 = store.OpenStream(streamId, 0, int.MaxValue))
using (var stream2 = store.OpenStream(streamId, 0, int.MaxValue))
	stream1.Add(new EventMessage{ Body = "test"});
	stream2.Add(new EventMessage{ Body = "test"});
	stream2.CommitChanges(Guid.NewGuid()); // throws ConcurrencyException

Making Visual Studio 2012 extensions work with VS 2013 Preview

I 've been taking the new VS preview for a spin, mainly because of the new task aware call stack. Unfortunately, many of the extensions in the Visual Studio gallery are not "compatible". Well, many of them probably are compatible as VS2013 does not have major architectural changes from VS2012. Not being able to live without StopOnFirstBuildError, and Hide Main Menu here is a trick to make them compatible again. Warning: may void your warranty!

  1. Download the VSIX 
  2. Open the VSIX in 7-zip 
  3. Right-Click and edit 'extension.vsixmanifest':

  4. Add entry for VS2013:

  5. Close notepad. 7-Zip will prompt you to save the archive.
  6. Install :)

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:

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.

An async await anti-pattern - awaiting tasks instead of just returning them.

I've seen this sort of thing being written, especially by people who are new to the async/await features of C#5/.NET4.5, when delegating to an async method, from an async method:

public async Task FooAsync()
    await _m.BarAsync();

Instead, they should just be writing:

public Task FooAsync()
    return _m.BarAsync();

The reason is because, in the former, the C# compiler will create a state machine (as viewed with DotPeek), which is simply unnecessary:

The C# compiler is not smart enough to optimize this out.

Edit: Don't do this either, for the reasons stated above:

public async Task<ActionResult> Index()
    return await Task.FromResult<ActionResult>(View());

This should be written as:

public Task<ActionResult> Index()
    return Task.FromResult<ActionResult>(View());

(Thx to @tourismgeek)

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.