Code Katas

The term code kata was coined by Dave Thomas in his book the Pragmatic Programmer and I have always thought it’s a good idea. I trained in Taekwondo for several years and we also had a form of ‘Kata’ called Poomsaes.

Some people used to misinterpret Katas as a waste of time as the moves and sequences are just predetermined and there is no point training like that, as the same scenarios would never play out in a ‘real’ fight or tournament. But anyone who has trained in a traditional martial art like Karate or Taekwondo will know that Katas or Poomses are there so you can practise each individual move to perfection and this serves to form a muscle memory of the individual moves and sequences so that they come naturally in a more real world scenario.

I latched on to the idea of code katas as it seemed like a great way to practise programming without embarking on a full blown hobby project. It’s hard for an enterprise developer to justify writing code that is just thrown away and that you won’t get paid for ‘just for the sake of it’ but finding time to get back to the basics definitely pays off and keeps you sharp. The good thing about code katas are that it keeps your basic skills grounded and forces you to remember how to do the basic stuff that you would probably never use in your main job (until one day you do).

I wish I did more code katas as like anything practising something makes you better, you can’t get around that fact. The only problem is finding the time or motivation when you have a deadline or are juggling other commitments.

I myself keep a Visual Studio solution containing lots of different projects that I use to practice different concepts or algorithms, the code in the projects isn’t great it won’t conform to best practices or be very elegant but I treat it like my interactive notepad of code.

I have uploaded the project to Github so anyone can take a look.

https://github.com/leedale1981/CodeKata

An example one of the projects is a simple string reversal in C#, this allows me to test out how different techniques perform next to each other, for example I tested string reversal in C# using the LINQ Reverse() method and a basic char array reversal using a for loop. I found that the basic for loop array method was orders of magnitude faster than LINQ. This was expected but it’s nice to prove to yourself so you know in future which is more the performant technique.


class ReverseString
{
    public static void Main(string[] args)
    {
        string input = "reverse me";
        Stopwatch timer = new Stopwatch();

        timer.Start();
        string outputLinq = UsingLinq(input);
        timer.Stop();
        Console.WriteLine("Using LINQ: " + outputLinq + " - time taken: " + timer.Elapsed.ToString());
        timer.Reset();

        timer.Start();
        string outputArrayOnly = UsingArrayOnly(input);
        timer.Stop();
        Console.WriteLine("Using array only: " + outputArrayOnly + " - time taken: " + timer.Elapsed.ToString());
        timer.Reset();

        Console.ReadLine();
    }

    private static string UsingLinq(string input)
    {
        char[] output = input.Reverse().ToArray();
        return string.Join(string.Empty, output);
    }

    private static string UsingArrayOnly(string input)
    {
        char[] inputArray = input.ToCharArray();
        string output = string.Empty;

        for (int index = inputArray.Length -1; index >= 0 ; index--)
        {
            output += inputArray[index];
        }

        return output;
    }
}

CORS Support in WebAPI and XDomainRequest with IE.

The WebAPI framework in the latest release of .Net 4.5 is a great way to easily create HTTP based web services from scratch, it gives you a lot of great features out of the box which allows you to return JSON or XML data back to a client application using Javascript or the server side HttpClient class.

If you would like to know more about WebAPI the head over to the official site to get up to speed with how it works. http://www.asp.net/web-api

One thing that isn’t included with the 4.5 release is the ability to do cross domain calls into your WebAPI services, there is no support for CORS out of the box with the current release. However CORS support is coming with the next release of ASP.Net and can be seen if you browse the ASP.Net source over at codeplex http://aspnetwebstack.codeplex.com/.

If you are reading this and wondering what CORS stands for its Cross-Origin Resource Sharing and it’s a new specification from W3C that aims to standardise the mechanism for cross domain requests by using standard HTTP headers in the request and reponse. You can read more about the specification at the W3C site http://www.w3.org/TR/cors/.

You can also read about CORS support for ASP.Net and WebAPI at this site http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API.

The problem is that if you want CORS support right now then you have two choices:

  1. Download the full ASP.Net web stack dev branch, compile it and use the 5.0.0.0 assemblies in your application.
  2. Write you own HTTP handler to add support.

The problem with option one is that most people don’t want to build their application on an unstable dev release of the framework. CORS support comes in the form of two new assemblies System.Web.Cors.dll and System.Web.Http.Cors.dll. The later is the assembly that you would use for WebAPI and the former is what you would use for ASP.Net. The problem is that these assemblies are both complied with version 5.0.0.0 of System.Web.dll and System.Web.Http.dll so you can’t just download the code for these assemblies and compile them against version 4.0.0.0 of the relevant assemblies or even grab the 5.0.0.0 version of the dependencies and compile against them. You will get either a compile time or a runtime security exception stating that there is a version mismatch between dependencies.

So bottom line is that unless you are willing to build your application on a dev release you are stuck with creating your own HTTP handler to deal with this. The approach below was taken from this blog post by Carlos Figueira http://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d and shows how you would implement a handler to deal with CORS support.

Creating a HTTP Handler for CORS Support

 public class CorsDelegatingHandler : DelegatingHandler
 {
     protected override Task<HttpResponseMessage> SendAsync(
         HttpRequestMessage request,
         CancellationToken cancellationToken)
     {
         string allowedDomains = WebConfigurationManager.AppSettings["CORSAllowCaller"];
         const string Origin = "Origin";
         const string AccessControlRequestMethod = "Access-Control-Request-Method";
         const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
         const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
         const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
         const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

         if (string.IsNullOrEmpty(allowedDomains))
         {
             return base.SendAsync(request, cancellationToken);
         }

         bool isCorsRequest = request.Headers.Contains(Origin);
         bool isPreflightRequest = request.Method == HttpMethod.Options;

         if (isCorsRequest)
         {
             if (isPreflightRequest)
             {
                 return Task.Factory.StartNew(() =>
                 {
                     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                     response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                     string accessControlRequestMethod =
                     request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();

                     if (accessControlRequestMethod != null)
                     {
                         response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                     }

                     string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));

                     if (!string.IsNullOrEmpty(requestedHeaders))
                     {
                         response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                     }

                     return response;

                 }, cancellationToken);
             }
             else
             {
                 return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                 {
                     HttpResponseMessage response = t.Result;
                     response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                     return response;
                 });
             }
         }
         else
         {
             return base.SendAsync(request, cancellationToken);
         }
     }
 }

The code above essentially looks for an Origin header in the request which indicates that the caller is coming from another domain. The requesting browser will add this header if the originating domain is different to the requested domain. It then adds the relevant CORS headers to the response which tells the browser that this call is allowed by the server. Most browsers support the Origin header using XHTTPRequest object so JQuery AJAX requests work fine, however IE does not add this header when using XHTTPRequest object so you need to use the XDomainRequest object instead which I will show in the next section.

Calling WebAPI from Javascript.

As I said above you will have to use XDomainRequest instead of XHTTPRequest object when making a cross domain request using CORS, otherwise the Origin header does not get added to the request.

You can see below how to achieve this:


if ($.browser.msie && window.XDomainRequest) {

    // Use Microsoft XDR
    var xdr = new XDomainRequest();
    xdr.open("get", this.url);
    xdr.onload = function () {
        bindData(JSON.parse(xdr.responseText), bindingNodeName);
    };
    xdr.send();

} else {

    $.ajax({
        type: "GET",
        url: this.url,
        dataType: "json",
        success: function (data) {
            bindData(data, bindingNodeName);
        }
    });
}

We essentially just need to check whether the browser is IE and supports the XDomainRequest object and if it does go ahead and use that object instead. The only thing to note here is that you will be getting back a string of data instead of the raw data when using XDomainRequest object and you will need to get your data out of the string before you use it. In the case of JSON it’s as easy at using the JSON.Parse helper method to get at your raw JSON object.