Thinktecture IdentityModel with ASP.NET Web Api

I’m writing this post as a reminder to myself on how to fix the following error message …

Attempted to access an element as a type incompatible with the array

… when firing up a Web Api project which is using Thinktecture IdentityModel.

My initialisation code looks like this …

                    var authenticationConfig = CreateAuthenticationConfiguration();
                    var handler = new AuthenticationHandler(authenticationConfig);

The problem is caused by the wrong version of the System.Net.Http being used. The solution is to remove the bindingRedirect you see below.

<?xml version="1.0" encoding="utf-8"?>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="" newVersion="" />

Note to future me: You will eventually remember this without having to come and look at this blog post!


I’m all Moq’d out!

I’m currently working on creating a Hypermedia API, or at least getting as close as I can to one!

In order to avoid the client hitting a dead end when an error occurs, either internally within my code or as a result of a bad request from the client, I wanted to provide links that the client can follow. So, I created an ApiError model class to send in my response in such a case.

    public class ApiError : Resource
        public string ParentId { get; set; }
        public string ErrorMessage { get; set; }

The [Hypermedia] attribute is just a place holder I use within my Delegating Handler which “enriches” the resources with links. The ParentId is the id used in order to construct links to the home resource and it’s also used for constructing self links and so on.

The links are generated by way of Mark Seamann’s excellent HyprLinkr library, available via Nuget (

My first attempt was to create an extension method to create the response, much like the built in HttpRequestMessage.CreateErrorResponse extension method. This worked great when I tested it using my current favourite chrome extension, POSTman. It returned the error, along with a “back” and “home” link so the client didn’t just hit a dead-end.

For example …

  "errorMessage" : "The was an error, run for the hills!",
  "_links" :
      "rel" : "home",
      "href" : "http://server/api/home/",
      "title" : "home",
      "verb" : "GET"

So, all is well. I’m a happy bunny….

Until I run my unit tests.

What The Flip?

Why is there red everywhere?!

As it turns out I wrote some legacy (read: un-testable) code. Here’s what I’d come up with …

    public static class HttpRequestMessageExtensions
        public static HttpResponseMessage CreateErrorResponse(
            this HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks)
            var apiError = new ApiError
                ParentId = parentId,
                ErrorMessage = errorMessage

            if (addLinks != null)
                var routeLinker = _resourceLinkerFactory.GetResourceLinker(request);
                addLinks(routeLinker, apiError);

            return request.CreateResponse(statusCode, apiError);

After spending some time in the debugger trying to figure out why I was getting a null reference exception, I started looking at Mark’s code on github and eventually figured out that the GetRouteData() call was returning null. So, I spent more time trying to figure out a way of getting that to *not* be null. I ended up getting the source code for the aspnetwebstack from codeplex and looking at the code for GetRouteData().

Veering off-topic slightly, I didn’t have git installed on my pc, so I fired up powershell and …

  PS> cinst git

… I used chocolately to install it, restarted powershell and …

  PS> git clone

… I was rummaging around the web stack code 😀

Back on to topic …

After a few failed attempts at getting the null reference to go away it dawned on me that with another layer or two or abstraction I could Moq (on nuget too – my way out of trouble.

So, thinking about it for a little while I came up with a way of doing all this so I could moq it. Firstly I needed to change CreateApiErrorResponse from an extension method into a “service”, which I could then pass into the relevant controllers. Once I get past the unit test stage I could easily set it up using Castle Windsor. I would also need an IResourceLinker factory.

The Service

    public interface IHttpRequestMessageService
        HttpResponseMessage CreateErrorResponse(
            HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks);

    public class HttpRequestMessageService : IHttpRequestMessageService
        private readonly IResourceLinkerFactory _resourceLinkerFactory;

        public HttpRequestMessageService(IResourceLinkerFactory resourceLinkerFactory)
            _resourceLinkerFactory = resourceLinkerFactory;

        public HttpResponseMessage CreateErrorResponse(
            HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks)
            var apiError = new ApiError
                ParentId = parentId,
                ErrorMessage = errorMessage

            if (addLinks != null)
                var routeLinker = _resourceLinkerFactory.GetResourceLinker(request);
                addLinks(routeLinker, apiError);

            return request.CreateResponse(statusCode, apiError);

The Factory

    public interface IResourceLinkerFactory
        IResourceLinker GetResourceLinker(HttpRequestMessage request);

    public class ResourceLinkerFactory : IResourceLinkerFactory
        public IResourceLinker GetResourceLinker(HttpRequestMessage request)
            return new RouteLinker(request, new AttributeBasedRouteDispatcher());

Once I sorted out a few built errors it was time to do some Moqing…

    public class MyControllerTests
        private Mock<IResourceLinkerFactory> _mockResourceLinkerFactory;
        private Mock<IResourceLinker> _mockResourceLinker;
        private IHttpRequestMessageService _httpRequestMessageService;
        private MyController _controller;

        public void SetUp()
            const string id = "";

            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://localhost/api/user/{0}", id));

            _mockResourceLinkerFactory = new Mock<IResourceLinkerFactory>();
            _mockResourceLinker = new Mock<IResourceLinker>();
            _httpRequestMessageService = new HttpRequestMessageService(_mockResourceLinkerFactory.Object);

            _mockResourceLinkerFactory.Setup(x => x.GetResourceLinker(It.IsAny<HttpRequestMessage>()))

            _mockResourceLinker.Setup(x => x.GetUri(It.IsAny<Expression<Action<MyController>>>()))
                           .Returns(new Uri(string.Format("http://localhost/api/user/{0}", id)));

            _controller = new MyController(_httpRequestMessageService);

Hurrah! It all worked and I could get back to testing what I was actually trying to, which was unrelated to providing links when sending errors to the client. But, I needed this anyway 😀

Since the tests I was working on weren’t testing the presence of the links, I suppose I could have done something like this …

    var _mockHttpRequestMessageService = new Mock<IHttpRequestMessageService>();
        .Setup(x => x.CreateErrorResponse(
            It.IsAny<Action<IResourceLinker, ApiError>>())
        .Returns(new HttpResponseMessage(...));

Anyway, I hope that helps someone out. It’ll probably be me at some point in the future as my memory is not the best 😉

Trentham Regatta 2013

On Sunday 9th June 2013 I travelled to Trentham Gardens, near Stoke-on-Trent to compete at the regatta. I would be competing in 2 events, the IM3 coxless quad (IM3 4x-) and the masters coxless quad (

The first race of the day for me was at 13:10 against Leicester RC. Our crew had never actually rowed together before as a quad. We’ve rowed together in other boats, but never as a crew. I say never, we may have in the dim and distant past!! It was pretty close all the way down the 750m course, we managed a win by a length or two. It was hard work, but very nice to get a win at my first regatta since August 2009.

Trentham operate a “winner stays on” system, so we paddled back up to the start for the final of the event. The boat was moving well, we’d got a good start in the semi-final and we decided to do a few more exercises on the way back up to the start. Things were looking better than I’d expected for what was effectively a scratch crew.

We came up against a crew from Agecroft Rowing Club in the final. They got a slight jump on us at the start, but we pulled level with them quite quickly and we starting to row through them. But, they came back at us and we ended up in a mad sprint for the line apart from a small section at the start! We made 2 or 3 pushes, but so did they. We crossed the line and both crews looked at the other, neither of us knew who’d got it. Unfortunately we didn’t get the usual quick announcement from the officials, so we hung around waving arms and shouting at the officials for 5 minutes!! Eventually we found out that Agecroft had won by a foot. I was sure we’d won as when we looked over after the finish we were the faster boat at that point. But, I guess Agecroft took their final stroke just before the finish line and nudged in front of us. If we’d done that we’d have got it.

We were all gutted as we’d given our all. Oh well, there is always next time!

IM3 Quad Final

The other event for me was the Masters Quad. We’d got a bye into the final, which was scheduled for 18:19. So, I had plenty of time to kill and spent a while sitting with Team Trent watching some of the other races and getting very hot under the baking sun. The setting for Trentham is beautiful, and there are plenty of shady spots to cool down in.


By the time our race time arrived I was actually quite chilled out, so a short warm up run was called for to wake myself up!

We’d rowed together for the first time as a crew the previous day and it had gone really well. During some “up 2s” we’d done the boat was really shifting and we’d figured out a good start that was smooth and fast. We were optimistic. However, as the other crew were Masters D and we were only Masters C, they were entitled to a 5 second head start. That 5 seconds probably equates to 3 or 4 boat lengths. So, we were always chasing them. I think we got to within a length of them but they just had too much of a lead and too much experience to let us young upstarts take the lead. We finished about 2 seconds behind.

Masters Quad

Unfortunately we didn’t row as well as we had the previous day in training. We were scheduled to be the last race of the day but as things turned out we were 2nd to last. So, the banks were empty apart from Trent supporters. All in all a very enjoyable day which gives promise of more success in the future.

Displaying embedded web pages in Winforms

I had an application/plugin I wanted to display some license information in and also attribute my use of a public API. So, I figured a nice way to do that would be to drop a web browser control in my winform and then have an embedded resource as the content. So, I created a little webpage and set it’s Build Action to Embedded Resource. A tiny bit of css in the head section and it looked good.

But, I wanted to also display an image in there. I tried a few different ways, but eventually stumbled upon an answer on stackoverflow which suggested encoding the image as a Base64 string. So, I set to work creating a little helper method to load my embedded web page and automatically encode all images on it. I decided to go with using a placeholder to the image, like so …


In order to find out the name of the resource, you may find running this little piece of code helpful …

var names = Assembly.GetExecutingAssembly().GetManifestResourceNames();

So, I used a little regex magic (courtesey of to find those placeholders, extract the path and do the encoding for me.

    public static class EmbeddedWebPageLoader
        public static string LoadWebPage(string name)
            const string regexPattern = @"%IMG\(\""(?<ImagePath>[^\""]*)\""\)%";
            var assembly = Assembly.GetExecutingAssembly();
            var pageStream = assembly.GetManifestResourceStream(name);
            if (pageStream != null)
                using (var webPageStreamReader = new StreamReader(pageStream))
                    var pageContent = webPageStreamReader.ReadToEnd();
                    var matches = Regex.Matches(pageContent, regexPattern);
                    foreach (Match match in matches)
                        var imagePath = match.Groups["ImagePath"];
                        var extension = Path.GetExtension(imagePath.Value).Trim(".".ToCharArray());
                        var imageStream = assembly.GetManifestResourceStream(imagePath.Value);
                        if (imageStream != null)
                            var buffer = new byte[imageStream.Length];
                            imageStream.Read(buffer, 0, (int) imageStream.Length);
                            var imageBase64String = Convert.ToBase64String(buffer);
                            var imgTag = string.Format("<img src='data:image/{0};base64,{1}'/>", extension, imageBase64String);

                            pageContent = Regex.Replace(pageContent, regexPattern, imgTag);
                    return pageContent;
            return null;

It works like a dream, I can now use images inside my about box, like so …

webBrowser.DocumentText = EmbeddedWebPageLoader.LoadWebPage("MyProgram.About.html");

Now I really do have a “home cinema”

I say “now”, I’ve actually had a proper home cinema for coming up 2 years now! I’ve just never got around to writing about it.

I am very difficult to buy Birthday/Christmas gifts for. If I want something I just buy it! Not that I buy an awful lot, but if I do want something I know what I want, I research it and get it. That, together with wanting expensive stuff makes Christmas/Birthday time tricky for those around me!

Anyway, a couple of years ago I mentioned I was annoyed with my pull down projector screen having a “bump” in it. So, my girlfriend said she’d get me a new screen for my birthday. We figured we get the long HDMI cable hidden in the ceiling and walls to. So, we called someone in the area specialising in home cinema installations and they said something that changed out thinking completely. He said “it’d be much easier if we had a clean slate to work with”. Things were getting complicated with me wanting an acoustically transparent screen, which then meant it had to be electric, which opened up a whole new can of worms!!

I’m not quite sure how we thought of using the garage, but we did. Once we got that idea into our heads there was no stopping us. I spent many weekends clearing out all the accumulated “stuff” that had found it’s way in there over the years. We got a few quotes to transform our garage into a little cinema. We still need some storage space at both ends, so the first thing to do was to replace the up-and-over garage door with a barn door style one. The reason being that we’d lose too much space because of the mechanism and also that we wanted to make use of the loft space above the garage and we’d be unable to access it with an up-and-over style door.

So, we ended up with a metre of space behind the new door where we keep our bikes, tools, etc. I have to say the 30/70 split barn door is brilliant, so much easier than an up-and-over. All houses should come with them as standard.

Next, the builders came and put in the new walls and floor, finishing off with putting in a new door to access the room from our hallway. I didn’t take many pictures of it all being done as it seemed to happen pretty quickly.

Stud work 1

We, also ended up with a cloakroom with loads of hooks for coats, hats, etc. The tumble dryer also lives in there, only just though as the room was made to measure. It’s about 650mm deep, and standard appliances are 600mm wide! We had a kitchen worktop that was in the garage before, so that was cut down and formed a useful work surface above the tumble dryer. I eventually put up another shelf in there and now my TVServer PC and Drobo live on that shelf, with the networked printer and UPS sitting on the kitched worktop. So, it’s a cloak/laundy/computer room. We do prop the door open when the tumble dryer is on otherwise it gets very hot and humid in there. So, far there haven’t been any issue with the computer gear in there.

We project managed it all ourselves, if you can call it that with it being just the one room.

Once the builders had got the stud work in place we got an electrician in to do the lighting, move the circuit box a little and put in all the power sockets in just the right places. 4 doubles at floor level, and a double high up on the large shelf we were having installed. I then wired up all the speaker and network cabling. Since all the AV gear was going to live on a big shelf at the back of the room, there was no need for video cabling.

Once all the wiring was done, the builders came back and put the high density sound insulation in the stud walls, floor and ceiling. We also had acoustic plasterboard installed, a thick black (obviously!) carpet and a fire door. Normal internal doors are very light and don’t cut out much noise at all.

We painted it ourselves, using a very matt charcoal colour, which just seems to absorb light! The skirting board, architrave and door were also paint in a very similar matt colour.

Once that was done the large shelf was installed, which we eventually covered in black material. We had a long struggle to find something suitable. I had to allow a feminine touch in there somewhere, so it’s patterned instead of plain. I used the same material to cover a small frame I made to conceal the circuit breaker box.


I’d got the builders to feed the speaker wire through the plasterboard in just the right places, so it looks quite neat.


We bought a couple of Lazyboy power recliner chairs, which are awesome. I’ve had no discomfort sitting on them for 3-4 hours straight. Originally we were going to get a sofa, but that would have been a little awkward when having mates round, as we’re not “that” close!!


It took me quite a while to get all the wiring done for the Mitsubishi HC6000 Projector, PS3, XBox360, HTPC and Denon AV-1910 Receiver. I did manage to get the projector setup with zero keystone correction and almost perfect geometry. It took a long time, but with the aid of a laser level and a tape measure I managed to get the screen exactly in the centre of the wall with only 1mm difference in one dimension. Which all means it looks perfect to me!

I used goo systems paint rather than having a fabric screen. It’s taken a few more top coats than recommended, but it looks amazing now. I did have a few “sparklies” for a while, but a couple of extra coats of top coat sorted that out. I think there is one that I notice occasionally, but I can live with that.

Since there is no ventilation in there it can get quite warm in the summer and cold in the winter. So, I’ve added one essential “gadget” to the room …


… an oil-filled radiator!

I’ll finish off with some more pictures …





The pictures don’t show the screen with the flock tape applied to form a border. I’ll post another picture of that soon.

I always used to say I was “into” home cinema, even when all I had was a 29″ CRT TV and a VHS player. Now I can say it and know I’m not exaggerating. Even though it’s only got 2 seats, it’s still a “home cinema” 😀

Running Raven DB Server from VS2012 Solution Explorer

I needed to run the full RavenDB Server as part of a development I’m currently working on. So, I knocked up a little powershell script to do that for me …

$path = (gci packages\RavenDB.Server.* | select -First 1).FullName
$exe = (gci $path -Recurse -Include Raven.Server.exe).FullName
cmd.exe /c start "$exe"

It assumes you’ve installed the nuget package into your solution. This shouldn’t be done via the package manager, as stated on the nuget page.

Use this package if you want to run RavenDB as a standalone application. This package is not intented to be used in Visual Studio. RavenDB is a document database for the .NET platform, offering a flexible data model design to fit the needs of real world systems.

PM> Install-Package RavenDB.Server

So, I added the script (at the top of this post) as a solution item. I also have an external tool defined like so …

Powershell External Tool in VS2012

So, to run my RavenDB Server I just highlight “Raven.ps1” in the solution explorer …

Solution Explorer - Solution Items - Raven.ps1

… and select Run Powershell (x64) Script (output window)

VS2012 Tools Menu

… and there you have it. Full RavenDB Server running.

I hope that helps someone else out there.

Have fun with RavenDB, it’s pretty awesome from what I’ve seen so far.

Over the last few (work) days I have been having problems getting CDC (Change Data Capture) to work. After looking in the SQL Server Agent job history and finding the error “Cannot find the principal ‘dbo’, because it does not exist or you do not have permission” a colleague suggested changing the db owner to “sa”. As soon as I did that everything (CDC related) sprung into life, without me even needed to restart the SQL Server Agent windows service.

Stanley Johns's Database Blog

There are times when a DB is created and the dbo user is mapped to another user name like ‘mike’, instead of being mapped to the sa login. Usually, sp_change_users_login can be used to change the logins of a DB user, but this SP cannot be used for dbo users. This is when sp_changedbowner will have to be used. Execute sp_changedbowner ‘sa’, and now your dbo DB user will be mapped to the sa login.

View original post

Why do motherboard manufacturers ship out-of-date drivers?

I’ve just built myself a new HTPC to replace my aging machine in the lounge. It dutifully installed all the drivers from the supplied CD, after having copied them to my USB pen drive in order to load them onto my optical disc free HTPC. I also went onto the manufacturers website to make sure I got the latest network driver as I’ve had problems with network drivers in the past.

So, I went ahead and started testing my new PC with some movies I have stored on my NAS. Everything seemed fine at first, but then a few minutes into my test movie I started getting choppy video. So, I did the usual thing of trying out a few different CODECs, but they all suffered from the same problem to varying degrees.

As a last resort I copied my test file onto the local hard drive of the PC and tried again. Eureka!

I couldn’t believe I was getting the same problem despite having updated my network driver. So, off to the realtek site I went and downloaded the driver for my network chip from there.

Here are the details of the “latest” driver on the asrock site …

Driver Date = 23/06/2010
Driver Version = 7.23.623.2010

Here are the details of the latest driver from the realtek site …

Driver Date = 26/12/2012
Driver Version = 7.67.1226.2012

What I don’t understand is that the motherboard this driver came with is just over 2.5 years out of date and from what I’ve read somewhere (but cannot find again) also predates the release date of the CPU the motherboard is built around, although I may be wrong on that last count. (Update: Wikipedia article stating E350 APU release date of 4th of January 2011)

The motherboard is an Asrock E350M1 which has an AMD Zacate E350 CPU. It has a realtek RTL8111E network chip installed.

The PC has been playing video content solidly for the last 6 hours without any problems. There is still the odd dropped frame, but I can live with that.

The latest incarnation of my TV Server

I recently wrote about how my home network has evolved over the years. Well, it happened again!

About 4 months ago a bought a HP Micro Server. It only cost about £120 after the £100 mail-in rebate. Admittedly its not got anywhere near the grunt that my old server had, but I didn’t really need that as the CPU sat idle 99.9% of the time. I invested in a black gold 4 tuner PCI Express card at the same time. So I just have that and a bunch of hard drives in there. It sits there all day recording umpteen different shows for my 3 year old boy and the odd programme for us to watch! It uses about 60 watts less power, which is a bonus, it also takes up a lot less space and produces less heat and noise. I actually ended up using the MicroATX case to house my new development PC.

The other simplification I have gone through recently is to dismantle my “home made” 19″ rack and move the switch, patch panel, router and wireless access point into a wall mounted 6U rack cabinet. Not only neater but also gives me back quite a bit of loft space!

My next job is to get rid of the patch panel. My justification for having it, apart from being “geek” cool was that I could change how I used any network port in the house. I haven’t done that once in over 5 years. So I’ve bought a label printer and am just going to put RJ45 connectors on the end of all the cat5e cables and label them all up.  I’ll still be able to change how use the network points but it will be that bit simpler.

After that I’ll have a few things to put on eBay!