Thursday, 15 November 2012

Software Bucket List–Nov 2012

After reading Rob Maher’s blog post about the concept of software bucket list it got me thinking.

Let’s take a step back for a minute; what’s a bucket list? A bucket list is a list of all the things you want to do before you pass away. So a software bucket list for a developer is a list of software you’d ideally like to write before you retire. As Rob says it can be anything, not learn this or learn that etc. but what would you like to do?

So this brings me back to me, his blog post got me thinking. The whole idea of the list is that it will evolve over time but as of November 2012 this is my list:

  • Integrated disc golf membership system with result submission with associated automated renewals etc.
  • Work for and write software for a Formula 1 team
  • Multi player strategy re-write (modernise) of an old game we use to play in the early 00’s – Europa
  • Build <insert description here> to enable working from home for my own company – idea still hasn’t been thought of yet.

The last one doesn’t quite fit but it’s more a target to keep me inspired about moving forward.

Anyway, this is just a start and now it’s a seed that’s planted I’m sure I’ll come up with more but for now what’s yours?

Thursday, 27 September 2012

Debugging WCF messages before serialization

Over the past couple of weeks I’ve been doing a lot of work with WCF to do with the messages being sent between client and server and securely signing them. Signing the message isn’t the subject of this post however developing the following technique to see the message before it’s sent did lead me onto the solution for debugging messages being sent between client and server.

This post is to show how you can intercept the message, update it once its been serialized into xml (or just look at the xml) but before it’s been sent to the server. The basis of this all down the the IClientMessageInspector and adding this to your client calling code.

Let’s take a look at the message inspector and then I’ll talk through the additional classes which go with the inspector and then finally I’ll show you how to use the message inspector with a WCF client proxy generated class; in both code and through configuration.


public class DebugMessageInspector : IClientMessageInspector
    public object BeforeSendRequest(ref Message request, IClientChannel channel)

    public void AfterReceiveReply(ref Message reply, object correlationState)

Above is the generated method signatures of which the IClientMessageInspector expects to be implemented. The naming of the methods describes exactly the point in which they are called; BeforeSendRequest is as the request is sent to the server, AfterReceiveReply is as the response is returned. On the way out this is executed after the message has been created from the strongly typed objects and on the way in it executes before any serialization is performed if using strongly typed proxy and class definitions generated from a WSDL.

Inside each of the methods you can call the following code to allow inspection of the message.

private Message Intercept(Message message)
    // read the message into an XmlDocument as then you can work with the contents
    // Message is a forward reading class only so once read that's it.
    MemoryStream ms = new MemoryStream();
    XmlWriter writer = XmlWriter.Create(ms);
    ms.Position = 0;
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.PreserveWhitespace = true;

    // read the contents of the message here and update as required; eg sign the message

    // as the message is forward reading then we need to recreate it before moving on
    ms = new MemoryStream();
    ms.Position = 0;
    XmlReader reader = XmlReader.Create(ms);
    Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);
    message = newMessage;
    return message;

The above is a very simple way of reading the message into a raw xml format and then converting it back into a Message for further processing from the framework.

So how do you hook the message inspector to the client proxy call?

You need an IEndPointBehavior.

IEndpointBehavior definition

The new end point behavior allows you to add, amongst other things, message inspectors to the current ClientRuntime of the client definition using the behavior.

Implementing the interface gives you the following structure:

public class DebugMessageBehavior : IEndpointBehavior
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        // add the inspector to the client runtime
        clientRuntime.MessageInspectors.Add(new DebugMessageInspector());

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)

    public void Validate(ServiceEndpoint endpoint)

As you can see a number of extension hook points are available, but for this post we’ll concentrate on the “ApplyClientBehavior” method. In this method it gives you access to the MessageInspectors collection on the ClientRuntime which is a SynchronizedCollection on which any IClientMessageInspector implemented class instances can be added to.

This is it for the behavior definition. Lets see how we use it with a WCF client proxy class.

How do we use the IClientMessageInspector?

There are two ways in which the inspector can be used with a client proxy class. It can either be added in via code or through configuration. There are pros and cons for both routes. If done through code it will always be added, however a con is it will always be added. If however it is done through configuration it can be enabled/disabled without recompiling the code. This can be especially  handy if the functionality is only for debugging and you don’t want it to be used during Production or it’s used to turn on/off certain functionality which is only applicable under certain circumstances.

Let’s take a look at using the message inspector first with code and then through configuration.

Using the IClientMessageInspector in code

Through code (example code can be found on GitHub) you add it to the Endpoint Behavior collection directly. This can be done either straight after the proxy definition or at any point before any method is actually executed.

var client = new ServiceReference1.Service1Client();            client.Endpoint.Behaviors.Add(new DebugMessageBehavior());

As you can see from the above it is instantiated calling a default constructor. At this point you can pass in constructor parameters however this will cause you issues if you want to move it to be bound in configuration later.

And that’s it. Straight forward; simple.

Using the IClientMessageInspector through configuration

Adding the behavior through configuration takes a bit more work but as stated earlier being able to attach the functionality purely through configuration without changing code is worth the extra effort. To attach through configuration we need to define a new BehaviorExtensionElement which describes our new behavior.

public class DebugMessageBehaviourElement : BehaviorExtensionElement
    protected override object CreateBehavior()
        return new DebugMessageBehavior();

    public override Type BehaviorType
            return typeof(DebugMessageBehavior);

Once this has been created and the solution built the binding configuration needs to updated as below:

      <behavior name="debugInspectorBehavior">
    <endpoint address="
http://localhost:60428/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" behaviorConfiguration="debugInspectorBehavior" />
      <add name="debugInspector" type="Client.DebugMessageBehaviourElement, Client"/>


This is all in the system.serviceModel node in your web/app config file. The important parts are highlighted in bold.

First off you have to define a behavior extension pointing at your newly created behavior element class. This is a reflection string so the fully qualified type name needs to be followed by the name of the assembly that contains it.

Secondly you create an endpoint behavior which now uses the newly created extension. At this point the intellisense in Visual Studio will complain however it’s fine.

Third and finally you specify the newly created endpoint behavior as the behaviorConfiguration for your client end point.


Either way, on the way out you can see the whole message is:

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="">
        <Action s:mustUnderstand="1" xmlns=""></Action>
        <GetData xmlns="">

And on the way back:

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="">
        <GetDataResponse xmlns="">
            <GetDataResult>You entered: 7</GetDataResult>


Message inspectors are a very powerful tool when working with WCF and integration services. They can be used for debugging purposes as shown or for performing other actions on the message before it gets sent or on its return such as securely signing the message with a certificate.

The demo code I’ve used for this post can be found on Github; but remember it comes with a “Works on my machine” seal so use at own risk.

Sunday, 23 September 2012

Opening Pluralsight Single Page Application course code in VS2010

John Papa published a very good course on Pluralsight the other day about how to create a Single Page Application (SPA) and due to the popularity of the course Pluralsight opened it up for a short time only for free (thanks!). This allowed me to see exactly the type of quality I would receive when my training budget at work comes through soon (fingers crossed for October).

After watching some of the videos it was really interesting but I wasn’t quite getting how it all fitted together in the solution so was very pleased to find that the free sign up included being able to download the course material including the final solution. After downloading the zip file, expanding the contents and locating the .sln file I double clicked it and waited for Visual Studio 2010 to fire it up.


On Visual Studio 2010 opening the solution I was presented with a very sad looking solution explorer.


This is due to the fact that the course was written in Visual Studio 2012 and hence .net 4.5 was used for the projects. This got me thinking that it shouldn’t cause a problem as all the technologies which were being used are also available for .net 4 so I got about trying to get it to work.

Step 1; getting the projects to load

This in itself wasn’t that tricky. Firing up the .csproj files in notepad and locating the TargetFrameworkVersion I changed it to “v4.0”, saved and repeated it for all of the projects in the solution.




Once all the projects had been updated I reopened the solution in Visual Studio 2010 and got a prompt about configuring IISExpress. CodeCamper is configured to use IISExpress however if you don’t have it installed you will need to install it or configure the solution to work on a local IIS instance.


On clicking “Yes” Visual Studio attempted to load up the projects and Resharper did it’s usual solution scan and I was presented with a much happier looking solution explorer.


Step2; Lets try and build

On building the solution I got the following warnings however it did build.

warning CS1684: Reference to type 'System.Data.Spatial.DbGeometry' claims it is defined in 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.Entity.dll', but it could not be found
warning CS1684: Reference to type 'System.Data.Spatial.DbGeography' claims it is defined in 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.Entity.dll', but it could not be found

After a “successful” build I fired up the IISExpress site and went to start browsing the site to start seeing how it fitted together. However this was not the case and I got the following error.


Step3; changing 4.5 to 4

The changing of required framework version had not finished at the csproj level so I went through the web.config of the mvc project and changed the targetFramework attribute to “4.0”.

I also removed targetframework=4.5 from the httpruntime element below. Removed the machine key below that and hit refresh.


By now I was pretty sure that dependencies and reference errors are likely to be due to the framework version. With this I did a little Google and found that the version number had been bumped up to 4 for System.Net.Http in .net 4.5 however for .net 4.0 this needs to continue to reference version 2. With this in mine I updated the web.config from:

  <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
  <bindingRedirect oldVersion="" newVersion="" />


  <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
  <bindingRedirect oldVersion="" newVersion="" />

and hit refresh.


At this point I decided I would ignore the AntiXss encoder reference for now and come back to it later. I’m not going to publish the site anywhere so not worried about cross site scripting. However if you are going to put a site up into the wild then you will need to stop this kind of attack. Discussion for this is out of scope for this post.

I hit refresh and was presented with the Code Camper blue screen as below.


However no data.

step 4; getting data

At this point I thought I’m pretty close and pretty sure this will have something to do with the connection string. So after checking the connection strings configured in the web.config and noticing which one was currently active I checked to make sure the CodeCamper.sdf was present and ran.


Nothing; so changed the CodeCamperDatabaseInitializer below to always drop and recreate the DB to make sure the DB was fresh with the seeded data (remember to remove this and put it back to one of the other options otherwise it will delete everything all the time).

public class CodeCamperDatabaseInitializer :
    //CreateDatabaseIfNotExists<CodeCamperDbContext> // when model is stable
    //DropCreateDatabaseIfModelChanges<CodeCamperDbContext> // when iterating

Nothing. At this point I decided to remove the sdf file and update the connection string to use to be the SQLExpress one. I knew I had that installed and running so would be perfectly fine for study purposes.

Time to try running it again to see which error would occur next. The next error was inside the NInject Dependency Scope implementation, in the NinjectDependencyScope.GetService(Type serviceType) method …


… with the wonderfully descriptive error message of

“Method not found: ‘System.Delegate System.Reflection.MethodInfo.CreateDelegate(System.Type)”.

This was due to a version miss match of Ninject; uninstalling the Ninject nuget package and reinstalling it to get the correct version down seemed to resolve this.

Another rebuild and run. This time the EntityFramework was not happy with the current build. After the last issue with Ninject I thought I’d try the same routine so I uninstalled the EntityFramework nuget package and reinstalled it. It seemed to be originally wanting .net 4.5 but it’s happy with 4. This needed to be done in both the CodeCamper.Data and CodeCamper.Web projects.

At this point I hit f5 and crossed my fingers. I was greeted with a screen full of green friendly messages about getting data from the web api and a smiling photo of the mighty ScottGu; finally I’d got it working!



There is one out standing issue which was not resolved and that is around the AntiXss functionality but the rest seems to work as expected.

Thanks again to John Papa and Pluralsight for creating and publishing this course and I can’t wait to get my full subscription to start enjoying the other courses.

Friday, 17 August 2012

Personal Quarterly Objectives

Well the second quarter has not gone well. Actually since the beginning of May life has been a bit tough, pretty rubbish and very sad. There have been a couple of highlights (4 yr wedding anniversary, F1 British GP at Silverstone, Olympics football, new kitchen) but the rest of the time has been quite sad. I won’t go into details but I hope the rest of the year is better.

Anyway, will crack on, try and keep positive and keep up with trying to get things done.

End of message.

Wednesday, 20 June 2012

Testable client side view model with knockout without any server side dependencies

After reading the blog post series looking at creating a testable application with a JavaScript by Peter Vogel which looked at setting up the server side and the client side view model using Knockout I couldn’t help but think JavaScript needs a way of doing a kind of dependency injection so it can be unit testable without the reliance on the server side.

I understand that it will have a reliance on the server side to output the tests, however this is down to the implementation of the project not a requirement of unit testing.

View model creation

The view model is setup in a very similar way to how Peter had it in his example with a couple of tweaks to allow for the “DI” to function.

var Customer = function () {
    this.CustId = ko.observable();
    this.CompanyName = ko.observable();
    this.City = ko.observable();

    var self = this;

    this.getCustomer = function (custId) {

        MyApp.Customer.getCustomer(custId, this.updateData);


    this.updateData = function (data) {

We start by setting up the properties of the view model with the Knockout observables, set a reference to it’s self to be able to reference them later (good practice with Knockout from what I can gather), a callback binding function and the first “action” function on the model; getCustomer.

The getCustomer method calls into the data service passing in the parameters it requires for the action to execute and a callback function to call on the result. This could easily be expanded so that error handling can be caught and handled by another callback function but for this we’ll keep it simple.

With the view model set, the data service contract defined and being called in the function the view model is clean and not cluttered. At this point we can take a look at the data service “interface”.

Client side data service

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) { };

The data service is built up with JavaScript object notation. The first two lines is to make sure that firstly there is a “MyApp” defined and it has a “Customer” property. Then the getCustomer function is defined with the set parameters required for execution and the delegate for the callback. Doing it this way you also add it into your own applications namespace and avoid cluttering up the global name space.

Lets look at the implementations for unit testing and for the actual application implementation.

The Unit Test

The test we are trying to pass is relatively simple and still based on Peter’s from the original series.

test("Get Customer",
    function () {
        cust = new Customer();
        setTimeout(function () {
            equals(cust.CustId(), "ALFKI", "ID not correct");
            equals(cust.CompanyName(), "My Company", "Company not correct");
            equals(cust.City(), "Reading", "City not correct");

All it is trying to do is call getCustomer and make sure the data returned is bound to the correct properties.

Data service in testing

For testing purposes the view model test requires a populated JSON object to be returned from the data service. To enable the test to pass and remove the reliance on the server side test controller I create a mock client side data service before the qunit tests are added to the page.

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) {
callback({ CustomerID: custId, CompanyName: "My Company", City: "Reading" });

All this is doing is following the contract/interface as defined for the data service, but instead of calling into a server side action it is returning a “mock” object. At this point we have removed the need for any server side calls.

After this has been defined we can now write our unit test (as above) and test that JSON object values which are being returned are bound to the correct properties.

Application implementation

So now we’ve created a mock data service and got our unit tests passing for the view model it’s time to create the actual implementation to allow for server communication and getting actual data.

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) {
    var url = "@Url.Action("CustomerById", "Home")/" + custId;
    $.getJSON(url, null, callback);

As you can see we follow the same pattern as before but the difference is the getCustomer body implementation. We can now call into the server action and using jQuery’s $.getJSON method retrieve some json data from a server. The callback function is passed into the $.getJSON method which will delegate what needs to be done when the data is returned.


So to conclude client side unit tests do not need to have reliance on server side actions to execute even if they require data to be returned from an action. Some people may argue that the unit test isn’t testing the responses back from the server and handling them correctly. To do this you could go down the test controller route and get the server side to through actual errors or you could get the mock call to throw the errors.

If you have any comments about the above please post them below or contact me on Twitter - @WestDiscGolf.

Tuesday, 19 June 2012 MVC 4 WebAPI RC - What on earth is “Antlr3.Runtime”?!

I upgraded to the latest version of MVC 4 at the weekend which is the newly released “RC” so thought I’d have a play and see what’s changed.

On doing File > New on a new MVC 4 / Web API project a newly clean crisp solution loads up in Visual Studio. Just out of interest I make sure it builds – can’t be too careful with these “pre-release” builds. The solution builds fine so it’s time to explorer …

I expand the project references to see what dependencies the project now has and the list is quite large. The usual suspects are there; EntityFramework, System.Web.Mvc, System.Web.Razor etc. but I’m greeted by some un-usuals.

Disclaimer: I’ll point out now I didn’t do this check on the Beta so I’m not sure if some of the following where there before.

The first one is new and expected; Newtonsoft.Json. We’ve been hearing for a while that will be rolled into the final release and here it is. Nice! I’ve been using for other projects for a while and it’s good.

The second two which seem out of place are “Antlr3.Runtime” and “WebGrease”. What on earth are these?

Lets look at WebGrease first …

  • It has an entry in the nuget package file with a version number etc.
  • In object browser it has some of the “Microsoft.Ajax.Utilities” namespace in.
  • The rest seems to do with css, ui etc.
  • Delete it and the app still builds and runs.

Guessing can live with that, but could remove it. What does it do?!

The other remains a mystery; “Antlr3.Runtime”.

  • No entry in the nuget packages
  • Remove it and the default app still builds
  • In object browser from the class names it looks like it does something with Tree structures?!

From doing some searching it relates to parsing grammers etc. to interpret them in your application. Why would that be shipped with mvc 4? Couldn’t find any documentation to support this so maybe it was an oversight and will be removed from the final RTM version. Will have to wait and see …

Saturday, 5 May 2012

29 to 30–Q1 Review (Feb to April)

So the first quarter has drawn to a close so lets review where I got to with the objectives I set myself …

1. Launch personal website

I achieved this quite early on in the quarter. This was a site I’d been playing with, tweaking and re-writing a number of times over the past 6+ months. I finally decided that I’d got it to a point and published it. My problem is I never seem to be completely happy with what I write and want to put it out perfect. This doesn’t work in real life, so now I’ve got my site out there and there is a platform to build on and improve instead of striving for perfection, missing it and never getting anything into the world.

2. Run competitive 10km race

On the 15th April 2012 I took part in the 10km Regency Run in Leamington Spa. I completed the course in 54mins 52 seconds. I’m proud that I did it under my target time of an hour and glad that between my wife (@lau84) and I managed to raise almost £200 for Pancreatic Cancer Action.

3. Play disc golf right handed again

Unfortunately I have missed this. I had a set back with my recovery from surgery mid Jan to March and only now I’m starting to get back into going to the gym for a workout. My running has been going quite well recently and general fitness is pretty good so I don’t think it will be much longer (fingers crossed). I have been playing left handed and competed in the Bristol Open 2012 on the last weekend of April playing lefty.

4. Sand and paint the doors and frames upstairs in house

Missed this too. Due to my shoulder recovery set back I have not been able to do this. It will be on the list for next quarter so at least by the time the kitchen is done the upstairs should be looking a bit better.

5. Blog more

This was a bit of a woolly objective, you’ve got to have one woolly objective! I’m going to say I’ve hit this as along with my objectives posts I have done a couple of posts about other stuff with the highlight being a public refactoring exercise laid down by K. Scott Allen of OdeToCode fame which was reviewed by the man himself and my code can be found on Github. Totally going to count this as achieved!

Tuesday, 10 April 2012

An answer to OdeToCode–A refactoring experiment

I was shown a blog post by @MrKevHunter on earlier today which was partial interview question / partial skills exercise to flex your brain and coding ability.

So at lunch time I forked and pulled the code down and set about the little exercise. My first attempt was exactly that a first attempt. I wasn’t overly happy with it but generally it was ok. So on the way home I decided to continue the refactoring and have come up with a solution which I’m much happier with and have pushed that up to Github.

Let me know what you think …

Kev’s version can be found :

And the original (if you want a go) can be found:

Thanks for the challenge Scott!

Thursday, 22 March 2012

Help the world; help your Granny upgrade

As a web developer having to support multiple browsers can be (very) painful at times. Getting your client to agree on which browsers need to be supported for your project and ruling out older ones is a good way forward, but until we get people to upgrade and stop using older browsers then there will always be people trying to look at your site in IE6 and wondering “why does it look this bad?”

Personally that makes me sad.

Just think … you can make a difference this Easter! When you go and see your relatives (parents, grandparents, uncles, aunts etc.) this Easter weekend coming have thought for your loved ones and the offense they may see online. Remember why we celebrate Easter and while you go to church and/or sit down to eat a lovely roast dinner with your family be a loved one and click windows update and get the latest version of Internet Explorer (or download another latest version browser).

Remember, the sooner we get people not using it the sooner more people get to use websites around world the way they were designed to be used!

Help get this percentage down this Easter (at time of writing globally 7.1% / UK 1.4%) …

Friday, 3 February 2012

29 to 30–Q1 Objectives (Feb to April)

After thinking through what I want to achieve in the next few months taking into account my recover from shoulder surgery I have come up with the following personal objectives for the first quarter of this little experiment.

  1. Launch personal website
  2. Run competitive 10k race
  3. Play disc golf right handed again
  4. Sand and paint the doors and frames upstairs in house.
  5. Blog more.

Lets see how it goes …

Wednesday, 1 February 2012

29 to 30–Business Plan

The past couple of years I’ve found that some things have been stumbled into or nothing has been done for a while and before you know it its the summer, then Christmas and another year has gone. So this year is going to be different!

Companies have business plans and quarterly objectives to help give guidance as to where the board want the company to go, what they want to achieve etc. so I’m going to have a go at applying this to my life this year and see what happens. Remember that quarterly objectives are there to stretch ambition they are not set because they will be easy.

The premise is I’m going to break the year into four quarters; February to April, May to July, August to October and November to January. So by the time I hit 30 I will have a defined set of objectives I wanted to hit and see where I get to. I’m going to try and decide on 5 objectives per quarter and any I don’t hit in that period will be rolled over into the next assuming they are still applicable. The idea isn’t that I end up in Q4 with 20 things to achieve but to make my 30th  year productive and structured and not just be sailing through life. Obviously things will come up and priorities will change but that’s life, this is here purely for me to try and make sure I do something with it.

As companies have objectives they also have bonus incentive schemes and so do I. For each of the objectives I hit I will allow myself to spend £20 on something fun, something which I wouldn’t normally buy unless I’d been saving for (I know this is a kind of saving scheme, but its in an unorthodox fashion) or something impulsive. It’s almost like paying myself to do something for myself.

So why am I posting this online, one single reason; accountability. I could write them up, work through the objectives through the year and at the end go “look what I’ve managed to achieve this year” however it won’t show what I’ve missed, how its progressed through the months and won’t be documented.

Let the experience begin …