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.

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();

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

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


    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.

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

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

You can also read about CORS support for ASP.Net and WebAPI at this site

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 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 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 of the relevant assemblies or even grab the 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 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 =

                     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);
                 return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                     HttpResponseMessage response = t.Result;
                     response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                     return response;
             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();"get", this.url);
    xdr.onload = function () {
        bindData(JSON.parse(xdr.responseText), bindingNodeName);

} else {

        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.

SharePoint site I’ve been working on for the last few months is now live.

Thomson Reuters has been a client of mine for around 18 months now and In that time I’ve worked on lots of stuff from WCF web services to encapsulate some of their data feeds for consumption in websites and graphics creation packages to content managed websites and graphics hosting and creation SharePoint sites.

The latest project I worked on was a public facing SharePoint (MOSS 2007) web content management system. The goal of the site was to provide a content management platform for editorial to use, which would allow them to quickly create multimedia driven websites focused on a particular subject such as frontier markets in the first instance.

Thomson Reuters released a new website called Reuters Insider which the Special Report site we built is designed to complement but more focused on a particular subject. The site employs some standard functionality seen on most websites nowadays like tagging/tag clouds, comments, search, RSS feeds etc.

Take a look and would welcome any feedback:

Localizing a SharePoint UI using ASP.Net Resource Files

I have a requirement for a project I’m working on to make all strings in the UI of a SharePoint 2007 site localized. The problem was that the rest of the site collection needed to stay in English, this meant all the system and admin pages needed to stay in English while all the user interface needed to be localized. The requirement also stated that an admin of the site collection could change this is the admin pages.

I immediately turned to ASP.Net resource files as this would achieve exactly what I wanted, I wanted to use the Regional Settings -> Locale setting in the site collection to determine the locale to show. The problem with this was that changing the sites Regional Settings Locale had no effect on the CurrentUICulture that the current ASP.Net thread was running under, this meant that ASP.Net would load the resource file for the user’s browser not the resource file for the locale of the site collection.

I used the following blog post from Mikhail Dikov which is a good example of how to use ASP.Net resource files in a SharePoint site. The blog post fails to mention however that for the culture to change within a SharePoint site you need the language packs installed and this would affect the whole site collection, admin pages and all.

So the following is an outline of how I achieved my goal:

  • First I created a default resource file which contained all the English strings and then resource files for each locale I wanted to support.
  • Next I deployed these resource files into my SharePoint web applications App_GlobalResources folder (see Mikhail’s blog post on how to deploy your resource files using a SharePoint feature).
  • I then added the following code to my page layout which changed the current ASP.Net threads UI culture to the same culture of the SharePoint site collection:

<script runat=”server”>
override void InitializeCulture()


System.Threading.Thread.CurrentThread.CurrentUICulture = Microsoft.SharePoint.SPContext.Current.Web.Locale;



This made sure that each time the page loads the ASP.Net culture was set to the correct site collection culture.

  • Now that the correct ASP.Net culture is selected in the page we can go ahead and localize our strings in the page layout like this:

    <asp:Literal runat=”server” Text=”<%$Resources:MyResourceFile,MyLocalizedStringKey %> />

    Note that we can also just use <%$Resources:MyResourceFile,MyLocalizedStringKey%>in any ASP.Net web controls property if you don’t want to use a Literal control.

And that’s all there is to it, I think it’s a clean and simple way to localize the SharePoint UI without using language packs and localizing the whole site collection including admin and system pages.

Enumerating MOSS site collections using the object model

For an application I’m working on I needed to be able to get all site collections for a given server URL.

So for example if I had a web application at http://localhost how can I enumerate through all the site collections on that web application?

Here’s how:

First we need to create a new System.Url object and pass that to the static method Lookup on the SPWebApplication class.

Uri serverUri = new

SPWebApplication webApplication = SPWebApplication.Lookup(serverUri);

Now we have an instance of SPWebApplication we can enumerate it’s Sites collection like so:

foreach (SPSite siteCollection in webApplication.Sites)




And that’s it! Simple as it is, no SharePoint development book or google search gave me what I was looking for, I would have thought this was a very common task for most SharePoint devs.

Setting a Site’s locale in SharePoint using SPLocale class.

A requirement I came across recently was to write a tool to set a site’s locale from US to UK using the object model.  Because I potentially needed to do this for hundreds of sites I opted to write a small command line tool that can be scripted to help with the task.

Below is an overview of how to use the SPLocale class to set the Locale of a site.  I have also provided download links for the compiled command line tool and its source code for you to take a look at.

First thing we need to do is grab an instance of the site:

SPSite site = new SPSite(“localhost”);


Next thing we do is get a collection of all the web sites under your site:


SPWebCollection webCollection = site.AllWebs;


We can now interate over this collection and set the Locale property to your new locale which will be an instance of the CultureInfo class. We create a new instance of the CultureInfo class by passing the new Locale’s LCID value to it’s constructor.


foreach (SPWeb web in webCollection)


      web.Locale = new System.Globalization.CultureInfo(2057);




Thats basically all there is to it.




Excecutable –


Source Code –


Example of command line:  SPSiteLocale.exe set http://localhost 2057