NancyFx & Castle Windsor

I’ve just managed to fix a very odd problem with Castle Windsor and NancyFx. The error I was getting wasn’t much help at all really!

Can’t create component ‘Nancy.Routing.DefaultRouteCacheProvider’ as it has dependencies to be satisfied.
‘Nancy.Routing.DefaultRouteCacheProvider’ is waiting for the following dependencies:
– Service ‘System.Func`1[[Nancy.Routing.IRouteCache, Nancy, Version=0.22.2.0, Culture=neutral, PublicKeyToken=null]]‘ which was not registered.

I’ve created a bootstrapper which among other this allows me to use a pre-existing container.

    public class NancyBootstrapper : WindsorNancyBootstrapper
    {
        private readonly IWindsorContainer _container;

        public NancyBootstrapper(IWindsorContainer container)
        {
            _container = container;
        }

        protected override IWindsorContainer GetApplicationContainer()
        {
            if (ApplicationContainer != null)
            {
                return ApplicationContainer;
            }

            _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
            _container.Register(Component.For<NancyRequestScopeInterceptor>());
            _container.Kernel.ProxyFactory.AddInterceptorSelector(new NancyRequestScopeInterceptorSelector());
            return _container;
        }

        protected override void RegisterBootstrapperTypes(IWindsorContainer applicationContainer)
        {
            // Note: Do NOT do the line below, this will cause the container to be registered twice and Windsor will throw an exception
            // applicationContainer.Register(Component.For<INancyModuleCatalog>().Instance(this));
        }
    }

Thanks to Ricardo Campos for getting me started! But whenever I tried starting nancy in self-host mode I immediately got the “missing IRouteCache” problem.

            var bootstrapper = _container.Resolve<INancyBootstrapper>();

            var uri = WebServerUri;
            _nancyHost = new NancyHost(uri, bootstrapper);

After much googling, head scratching, silent cursing and putting the world to rights a few times, I stumbled across a Stack Overflow answer. After reading through the link provided in the answer (https://github.com/NancyFx/Nancy.Bootstrappers.Windsor/pull/8). I tried adding the suggested fix.

        protected override void ConfigureApplicationContainer(IWindsorContainer existingContainer)
        {
            existingContainer.AddFacility<TypedFactoryFacility>();

            // some other cool stuff!
        }

Hey presto, it was all working and all is well with the world once more, until I hit the next bug that defies logic!

Shrewbury Regatta 2014

The last time I competed at Shrewsbury Regatta was when I lost my novices way back in 2009.

Image

On the Saturday the course is 1000m and had a single event to compete in, Masters C 2x. I’d not been in a boat for 2 weeks, or a double for about 6 months and had never rowed in a double with my partner. These facts did not bode well. It didn’t go well either. We were lucky to not capsize if I’m honest. Steering was a problem as we just couldn’t get our stroke side blades out of the water because we were constantly being pushed over by the high wind. Our opposition were sheltered from it on the other side of the river, but I’m sure they were feeling the effects of the weather. We felt it more because we weren’t balanced to start with. We eventually paddled over the finish some time after our opposition. It was probably the worst I’ve ever sculled and I was very embarrassed by my performance.


Image

Sunday sees the course reduced to 600m, again I had a single event to compete in. This time Masters C/D/E 4x-. It was a straight final against a Masters E crew. Masters rules meant that they were given a 9 second head start, which over a 600m course seems like an eternity. After a false start and us receiving an official warning, our opposition were set off and the long countdown began. We stuck to the start we used at Leicester regatta as it seems to work well for us. The boat speed picked up quickly and we soon got in to a good rhythm. I sat at the 3 position just behind the stroke man, constantly making calls out to help him get to a good rhythm and keep it.

I’ve always seen the 3 seat as a crucial seat. When I’m sat there I make it my job to stroke the boat along with the stroke man, I can reign him in when things get rushed and stop the other guys rushing him in. So, that’s what I did. It’s also my job to calm the stroke man down when things get a bit sloppy, which they tend to do in the latter stages of a race!

Anyway, we had a good rhythm, the boat was moving well and we were balanced, for the most part. I glanced over my left shoulder and saw a boat, we’d only taken around 20 or so strokes, so I looked again and it was our opposition. We’d eaten up their head start in no time at all and were rowing through them. We got maybe half a length up and they picked it up, trying to pull us back. But we were really into a good groove at this point. I kept making calls to the stroke man to keep the length and rhythm we had. No one else could hear me! Not that it matters as they’ll follow the rhythm stroke is setting. We pulled ahead and stretched out a lead of 2-3 lengths by the time we crossed the finish line. Job done.

I was quite surprised by how heavy I was breathing as it didn’t feel that hard during the race. That’s a sign of a good row. It feels good, even easy right up until you stop rowing, then it hits you like a brick wall!

I was still buzzing from the adrenaline 20 minutes after we’d got the boat off the water!

Image

 


 

For anyone wondering what the numbers mean …

  • 2x = double scull
  • 4x- = quad coxless scull

 

Leicester Regatta 2014

On Sunday 27th April 2014 I competed at Leicester Regatta, which was surprisingly easy to get to. Parking was fairly close by, being only a 5 minute walk away.

I had 2 events, the first being a Masters Quad. We never quite got the boat sat right on the paddle up to the start, and that continued during the race. We were, however, at a disadvantage from the word go. In master rowing there is a rather bizarre rule where the older crews are given a head start. I can understand the reasoning behind it, just not the execution of it. Masters crews are categorised by the average age of the crew, so with us being slightly younger we had to start 5 seconds after our opposition. The problem I have with it being done at the start is that we are immediately in our opponents wash, which makes everything that much more difficult.

Anyway, we pulled a little bit of the deficit back, but not enough. We lost by 2 lengths.

The next event was an IM3 quad. We fared much better in that, as we were both starting at the same time. We’ve been training as a coxless/coxed 4 for the last couple of weeks, so this was the first time in a while that we’d rowed together in a quad. The paddle up to the start was much better, although to me it still didn’t feel quite right. We agreed on our start strategy, and it worked great. Our start was really smooth, and we got the boat up to speed within 5 or 6 strokes. We were level with our opposition for the start and when we lengthened out, pulled away from them with every stroke. Towards the latter third of the course we started to get a bit messy, so I made a few calls to the stroke man (I was at 3) and we crossed the finish line 3 lengths ahead. Job done, on to the final, which I’d forgot about and was privately celebrating getting another point!!

In the final we weren’t quite as clean or as powerful and were down from a couple of strokes in. We were up against a much stronger crew and ended up losing “easily”.

Despite losing there are a lot of positive to take away from that. The main one is that we were racing against students in the IM3 event, literally half our age. And we got into the final, so I’m really very pleased with how we did. Also, it’s the start of the season and we can only get better.

So, I’m looking forward to a good season of sculling and sweep oar rowing.

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!