Testing CORS with POSTman

I’ve just added CORS support to my Web API and have spend a not inconsiderable amount of time chasing my tail and trying all sorts of different things to try and get it working. Let me explain …

I use the POSTman chrome extension to test my API (outside of unit/integration tests) and whenever I made a request I wasn’t getting back the expected Access-Control-Allow-Origin header in the response. So, I loaded up fiddler after scratching my head for a while and I could see the Origin header wasn’t being sent in the request. Apparently chrome restricts that header, so it was getting stripped out. I could have used the POSTman python proxy (https://github.com/a85/POSTMan-Chrome-Extension/wiki/Postman-Proxy) but since I already have fiddler I simply customised it a little. I started off by adding a new RulesOption and hard-coding the Origin in fiddler, like so …

    class Handlers
    {
        ...
        public static RulesOption("Add Origin Header")
        var m_AddOriginHeader: boolean = false;
        ...
        static function OnBeforeRequest(oSession: Session) {
        ...
            if (m_AddOriginHeader)
            {
                oSession.oRequest["Origin"] = "http://localhost/";
            }
        ...
        }
    ...
    }

But, that didn’t allow me to control the origin. It’s not applicable in this instance, but I figured I might want to add specific origins in other instances, so I came up with this …

    class Handlers
    {
        ...
        static function OnBeforeRequest(oSession: Session) {
        ...
            if (oSession.oRequest.headers.Exists("X-Origin"))
            {
                oSession.oRequest["Origin"] = oSession.oRequest["X-Origin"];
                oSession.oRequest.headers.Remove("X-Origin");
            }
        ...
        }
    ...
    }

So, all I need to do now is add the X-Origin header in place of the Origin header and I’m good to go. Obviously, I will need fiddler to be running and capturing traffic in order it to work. But, if fiddler is not running then the request still works but without the CORS header being returned in the response.

Burton Regatta 2013

This weekend just gone (13th-14th July 2013) I competed at the Burton Regatta.

Team Trent all met at the club at 7am (well most of us did, some didn’t quite get there on time) for a pre-race paddle. As I wasn’t racing until late afternoon I didn’t actually get to go for a paddle with the rest of my crews. So, I helped paddle a quad up to the regatta field, one at bow/stroke and nobody in the middle!

The Burton regatta isn’t held near the club due to lack of space, so it’s 1.4km (approx) up river.

Things did not get off to the best start for me as I slipped on the grass bank at the club while getting the launch out. I was actually quite lucky to not break my leg as I slipped and went under the launch which then fell on my leg just above the knee. I escaped with a shallow cut a couple of inches long. It was a bit sore, but thankfully it didn’t impede my performances.

I had 2 events on the Saturday, both quads.

My first race was at 16:25 in the Masters C Coxless Quad Scull (MasC.4x-) against North Staffs. I wasn’t confident that we’d do well in this one, but I was proven wrong. It took us a while to get lined up at the start on account of the flow of the river pushing the crew on the Stapenhill side around a bit. The Saturday start is from stake boats, so it’s a bit fiddly! My memory of this has faded a little in the 2½ weeks since we raced. I do remember getting soaked through! I was at 3 (sitting behind stroke), both the guy at stroke and 2 are known “splashers” and I got the brunt of it. Still, it was nice and refreshing as the whole weekend was an absolute scorcher, weather wise. We won fairly easily by a length or two. So, my first win in a long time. But, no extra sculling point. The rules for masters are that you can only win a point if you don’t already have any.

My second (and last) race was at 17:15 in the Open Intermediate 2 Coxless Quad Sculls (IM2.4x-). We had a bye into the final, which turned out to be against Bradford. Again, I wasn’t sure how we’d perform. One of our crew had to pull out due to a back injury, so we roped someone else in from another club and we weren’t sure how we’d do as he’d only been in a quad a couple of times. But, about 30 minutes before race time the substitute was changed for a better sculler from Team Trent, things were looking up. The paddle up to the start was promising, we were moving well. Again, it was fiddly at the start getting both crews lined up. Pretty much as soon as we set off, things got aggressive on the steering front! There was a lot of “move over” shouts from both bow-men, we clashed blades about halfway down the course. They took a lead on us, we pulled it back and pulled away, they came back again. Like I said, *VERY* competitive. Coming in to the last 50 metres or so they were up by almost a length and I was shouting “GO” at the top of my lungs for 4 or 5 strokes and we had a massive surge and started to eat up the gap, then it got really interesting! We were clashing blades and riggers! But, I kept on rowing for all I was worth, my legs felt like lumps of lead I was gasping for air but I kept going. That is, until we got so tangled up neither crews could row any more! We crossed the line all tangled up and I was positive we’d won, as was the other crew and everyone else in my crew. We appealed immediately as they’d rowed into our water and (rightly so) we’d held our ground. The verdict came in just as we were landing, Bradford by 3 feet! No-one could quite believe it. With one person left in the boat we could still get a re-row. (The rule is if the whole crew is out we’ve accepted the verdict)

It seems the only people who thought we’d lost were the officials. So, we had a re-row on our hands. The first I’ve ever done, and not the thing I wanted to hear after my legs had just turned to jelly! We paddled straight back up to the start, turned around and we were off again. Unfortunately we didn’t have much left and lost by a couple of lengths.

So, because of slight changes in times of the races, I ended up rowing three 1100m sprints back-to-back. With the benefit of hindsight the IM2 was an awesome race to be a part of, so agonisingly close to a win. But, it felt good to be right up there in the mix rather than lagging behind by a number of lengths.

Sunday is a shorter sprint regatta over a distance of 700m. Again I had 2 events, both quads. I am becoming something of a quad specialist!

My first race was at 13:36 in the semi-final of the Open Intermediate 3 Coxless Quad Sculls (IM3.4x-) against Burton Leander (our neighbouring club). Apparently they were all about the start, going off hard and controlling the race from the front. Armed with that knowledge we practised a few starts beyond the start line (it’s not allowed on the course). We were moving well and agreed on a good stroke pattern for the start. As it’s a shorter distance it’s a free start, so the 2 crews have to get level and then we’re set off. We powered away from the start and I knew we’d won by the time I’d taken the 3rd stroke. We were a couple of lengths up within 50 metres from the start and we kept pulling away to win easily. If I were to guess I’d say we’d got somewhere around 5 lengths on them by the time we crossed the finish line. We were through to a Trent-Trent final!

The other event for Sunday was another Masters C quad, in the same crew as the day before. I remember this race, again for the thorough soaking I got all the way down the course. Which was actually very refreshing as it was even hotter than the previous day. I’d take a guess that it was hitting 30C. We were racing a crew from Ancholme rowing club, and they were having issues lining up at the start. We were eventually set off and I knew we had them from the 2nd stroke! I looked across and they were almost tipping in! Lots of shouting and very messy, they recovered and staged a comeback halfway down the course, but we were always in control. All this despite the boat being a bit wobbly and very very splashy. But we kept our heads, kept the boat upright and crossed the finish line several lengths ahead.

So, on to the final of the IM3.4x-, a Trent-Trent final no less. A fairly relaxed affair ….. on the surface! But I needed to win this one! We were pretty much the last race of the day, so the only people left cheering us on from the river bank were the local clubs! The paddle up the the start was good and we put some firm pressure on the way there to try things out. We were confident of a win.

We powered off the start, even quicker than previous races. We had them off the start again, up by a length within 15 strokes. We kept the pressure on and had a massive pickup with about 100 metres to go. It’s always easier to do that when you can see the other crew! The boat was really flying and we won easily.

So, my haul for the weekend was 3 medals. It should have been 4, but there you go. Perhaps if we’d moved over a touch in our IM2 race on Saturday instead of holding our ground we’d have won as we were destroying them in that final sprint. But, you live and learn.

Overall, an awesome weekend of racing made extra special by being cheered on by my little boy as I won a few races!

(photos to follow)

Using Moq to check the values of an object passed to a method

In order to test individual properties of an object passed to a method using Moq I have been making use of my Assert.IsFieldEqual method. See here for details.

Because I can’t call the Assert.IsFieldEqual inside a lambda, like so …


    _mockBus
        .Verify(x => x.Send(It.Is<MyMessage>(m => Assert.IsFieldEqual(m, propertyName, expectedValue))), Times.Once());

Obviously, since makes no sense as the Assert.IsFieldEqual is a void method. So, I’ve made use of Moq’s callback facility.


    MyMessage sentMessage = null;

    _mockBus
        .Setup(x => x.Send(It.IsAny<MyMessage>()))
        .Callback<object>((m) => sentMessage = (MyMessage) (((object[]) m)[0]));

    Assert.IsFieldEqual(sentMessage, propertyName, expectedValue);

This allows me to have a TestCase for each property in the message, so I have one test method for all the properties.

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);
                    configuration.MessageHandlers.Add(handler);

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"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

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.

    [Hypermedia]
    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 (http://nuget.org/packages/Hyprlinkr/).

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/someone@example.com",
      "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 https://git01.codeplex.com/aspnetwebstack

… I was rummaging around the asp.net web stack code :D

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 – https://www.nuget.org/packages/moq) 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;

        [SetUp]
        public void SetUp()
        {
            const string id = "john.doe@example.com";

            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>()))
                                      .Returns(_mockResourceLinker.Object);

            _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 :D

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>();
    _mockHttpRequestMessageService
        .Setup(x => x.CreateErrorResponse(
            It.IsAny<HttpRequestMessage>(),
            It.IsAny<HttpStatusCode>(),
            It.IsAny<string>(),
            It.IsAny<string>(),
            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.

DSC_0088

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 …

%IMG("MyProgram.Images.logo.png")%

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 regexhero.net) 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");