Calling WebAPI service from Windows Phone 8 using HttpClient

I had to solve what I figure must be a typical problem for a windows phone developer today, invoking a WebAPI service from the Mobile side. I found documentation on this process rather scarce, so here’s how you do it.

NuGet is your friend in this regard.

Step 1.

PM>  Install-Package Microsoft.AspNet.WebApi.Client -Pre

Step 2.
Confirm references


Step 3.

Now you can use  the HttpClient Async API to invoke your WebAPI service and return data. Here’s an example.


Which can then be used like this


To download the source click here.

Can’t start the Windows Phone Emulator – The Windows Phone Emulator couldn’t start because the hypervisor isn’t running.

So I figured I’d document my first experiences with the Windows Phone 8 SDK.

First issue I ran into was an error “The Windows Phone Emulator couldn’t start because the hypervisor isn’t running.”


While the information shown in the “more information” link helps its a bit verbose.

Basically enable “Execute disable bit” and “Intel Virtualization Technology” in the equivalent BIOS settings of your motherboard.


and ensure you have the “Hyper-V” features turned on


That’s it. Should be working now!

Magic Url Fetcher (Website Thumbnailer)

I recently tried to find a service to create website thumbnails for a product I am currently working on. Unfortunately I was unable to find a company that provides a service that returns the metadata I needed. Hence I created an Azure Service I call Magic Url Fetcher which allows you to take a thumbnail of any site and use it in your application.

If you’d like more information please visit:

Implementing WCF Net.Tcp binding/activation in Azure Web Role

I’ve been spending a significant amount of time recently working with the Azure platform and all I can say is WOW! Congratulations to Microsoft for creating an awesome cloud computing platform. The power, scalability, robustness and small learning curve of Azure is a godsend.

Niceties aside, working out how to get WCF Net.Tcp bindings working in an Azure web role has been far from a trivial process so I figure its time to share the magic.

Step 1 (Configure the internal endpoint):


Step 2 (Configure the WebRole to run in elevated execution context in the ServiceDefinition.csdef file):


Step 3 (In the WebRole OnStart() method add code that installs NonHttp Activation and configures the site bindings to support net.tcp):

Note that this code requires a reference to Microsoft.Web.Administration which is located in C:\Windows\System32\inetsrv\

private void InstallWCFNonHTTPActivation()
    using (Process installer = new Process())

        installer.StartInfo.UseShellExecute = false;
        installer.StartInfo.RedirectStandardOutput = true;
        installer.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "dism.exe");
        installer.StartInfo.Arguments = " /online /enable-feature /featurename:WCF-NonHTTP-Activation";
        installer.StartInfo.CreateNoWindow = true;
        //string output = installer.StandardOutput.ReadToEnd();

private void ConfigureSite()

        ServerManager manager = new ServerManager();
        Site CurrentSite = manager.Sites.FirstOrDefault();

        if (CurrentSite != null)
            Application app = CurrentSite.Applications.FirstOrDefault();

            if (app != null)
                app.EnabledProtocols = "http, net.tcp";

            CurrentSite.Bindings.Add("123:" + CurrentSite.Bindings.First().EndPoint.Address, "net.tcp");

    catch (Exception ex)
        System.IO.File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "ConfigureSiteException.txt"), ex.Message);


And there you have it, your Azure Web Role will now Install Non-Http Activation, configure bindings and automatically start without any intervention. Simple as that, only took me 3 days to work out! :-p

Simple Cross Domain HttpHandler proxy

I recently ran into the problem where I needed to forward cookies to a WCF service running on a different port to the originating request. This caused all sorts of cross domain issues between browsers.

In the end I settled on using a IHttpHandler to forward the requests and figure this might be useful to others.

public class MagicProxy : IHttpHandler
    private const int WCFServicePort = 8081;
    private const string WCFServiceDomain = "localhost";
    /// <summary>
    /// Method calls when client request the server
    /// </summary>
    /// <param name="context">HTTP context for client</param>
    public void ProcessRequest(HttpContext context)

        Tuple<bool, string> requestURL = BuildRequestURI(context); //all site accepted

        if (requestURL.Item1)
            //create the web request to get the remote stream
            HttpWebRequest forwardRequest = (HttpWebRequest)WebRequest.Create(requestURL.Item2);

            HttpWebResponse response;

                forwardRequest.Method = context.Request.HttpMethod;

                foreach (string item in context.Request.Cookies)
                    HttpCookie OriginalCookie = context.Request.Cookies[item];
                    forwardRequest.CookieContainer = new CookieContainer();
                    forwardRequest.CookieContainer.Add(new Cookie(OriginalCookie.Name, OriginalCookie.Value, OriginalCookie.Path, WCFServiceDomain)); 

                SetHeaders(context.Request.Headers, forwardRequest);

                if (forwardRequest.Method.ToLower() == "post")

                response = (HttpWebResponse) forwardRequest.GetResponse();
            catch (System.Net.WebException we)
                //remote url not found, send 404 to client 
                context.Response.StatusCode = 404;
                context.Response.StatusDescription = "Not Found";
                context.Response.Write("<h2>Page not found</h2>");


            //close streams


    public void SetHeaders(NameValueCollection originalRequest, HttpWebRequest forwardRequest)
        string connection = originalRequest["Connection"];
        int contentLength = string.IsNullOrEmpty(originalRequest["Content-Length"]) ? 0 : int.Parse(originalRequest["Content-Length"]);
        string contentType = originalRequest["Content-Type"];
        string accept = originalRequest["Accept"];
        string host = originalRequest["Host"];
        string referer = originalRequest["Referer"];
        string useragent = originalRequest["User-Agent"];

        forwardRequest.KeepAlive = connection.ToLower() == "keep-alive";
        forwardRequest.ContentLength = contentLength;
        forwardRequest.ContentType = contentType;
        forwardRequest.Accept = accept;
        forwardRequest.Host = host;
        forwardRequest.Referer = referer;
        forwardRequest.UserAgent = useragent;

        string pragma = originalRequest["Pragma"];
        string acceptEncoding = originalRequest["Accept-Encoding"];
        string xRequestedWith = originalRequest["X-Requested-With"];
        string dnt = originalRequest["DNT"];

        if (!string.IsNullOrEmpty(pragma))
            forwardRequest.Headers.Add("Pragma", pragma);

        if (!string.IsNullOrEmpty(acceptEncoding))
            forwardRequest.Headers.Add("Accept-Encoding", acceptEncoding);

        if (!string.IsNullOrEmpty(xRequestedWith))
            forwardRequest.Headers.Add("X-Requested-With", xRequestedWith);

        if (!string.IsNullOrEmpty(dnt))
            forwardRequest.Headers.Add("DNT", dnt);


    public Tuple<bool, string> BuildRequestURI(HttpContext context)
        string serviceName = context.Request.QueryString["ServiceName"];
        string serviceMethod = context.Request.QueryString["ServiceMethod"];

        if (!string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(serviceMethod))
            return new Tuple<bool, string>(true, string.Format("http://{0}:{1}/{2}/{3}", WCFServiceDomain, WCFServicePort, serviceName, serviceMethod));
            return new Tuple<bool, string>(false, null);

    public bool IsReusable
            return false;

Concatenating values with commas in arbitrary collection

On numerous occasions I have needed to concatenate a property of an entity in a collection with a comma and have typically resulted in code that requires a loop for each entity along with a removal of the extra comma once the loop is completed.

This has always been a pain and plain ugly

Today I stumbled across a new overload for String.Join (String.Join Method (String, IEnumerable<String>)) which is only available after .NET 4.0 .

This allowed me to come up with the following extension.

public static string ConcateWith(this IEnumerable<T> values, 
                                      Func<T, string> property, 
                                      string separator) 
    return string.Join(separator, values.Select(o => property(o)));

Nice eh?

Building a generic security framework

Its a mind blowing fact that despite the countless libraries and frameworks available for the ASP.NET platform there still doesn’t appear to be any options regarding a plug and play security framework.

This is now the second time I have had to build a security framework for my applications and each and every time it seems to prove just as frustrating as the last. For every generic implementation I am able to concoct and two steps forward that I take, I am subsequently pulled 3 steps back when I confront a requirement that simply doesn’t fit anywhere within my implementation.

Despite my issues I do however have some tips.

Use a generic approach

  1. It may initially seem an like overwhelmingly complicated problem to solve generically but it isn’t, just like most things in our field it needs to be solved using a staggered approach.
  2. Start by implementing only the most basic functionality (Edit and View for example) and slowly move to more complicated requirements (If this value is x this control is enabled, if this value is y this control is hidden). Slowly as you solve these problems generically, you will build an overall solution.
  3. Testing a non generic approach is nearly impossible and will cost you much more in the long run.

Use bitwise operations (flag enumerations)

  1. I have tried both an approach with and without flags and I can confidently say that the code in the latter is cleaner and more understandable (even if it does make DBAs go mad)

Create a separation of permissions in the following way

  • Groups
  • Page Level Permissions
  • Control Level Permissions
  1. Groups are your standard security groups as with any other application.
  2. Page level permissions are the permissions that are tied to a single page or a group of pages and will typically only require View, Create, Edit, Delete functionality.
  3. Control level permissions are usually where things get tricky, these can require any number of ‘truths’ to either enable or show the control and the logic to express this can become very convoluted. I approach this part of the problem with the idea of invoking defined methods (that are linked by control names) that perform the required validation returning either true or false.

The above separation will cover just about any scenario you can envisage and if implemented with even the smallest of foresight should be enough for the basis of any generic security framework. Having said that, if anyone wants to become another Telerik, go get started on this project immediately…

Persisting Telerik RadGrid grouping UI after postback

I have recently run into a problem where after utilizing the grouping functionality along with the RadAjaxManager my RadGrid grouping UI state was disappearing after rebinding data.

This is undesirable for a number of reasons but mainly because it is unclear to the end user if an edit performed to an entry in the grid has been successfully achieved. Not to mention frustrating to have to open the group again to verify.

After much searching to see if the RadGrid supported such functionality or not I was extremely confused with some forums and posts saying this functionality was built into the grid and others suggesting it was impossible to do.

Anyway, in the end I was unable to find a built in way to perform this and resorted to the hack demonstrated here.

Pity Telerik doesn’t appear to have built this functionality straight in.

Lines of code, per developer, per day

I have recently embarked on my largest ever development project. I am roughly 45,000 lines of code into the project (Only counting C#) and am expecting it to hit at least 50,000 by the time its completed.

At the beginning of each Monday I have logged and plotted the amount of lines of C# code completed in the prior week. I have only plotted C# lines because the tool I was using unfortunately only supported this. I have since upgraded to a program called Microsoft Line Of Code Counter and this provides a much more comprehensive report (and its free).

Although the project isn’t finished (And I will update once it is) a couple of interesting results have already surfaced.

  1. It appears that an individual programmers peak output on a completely blank canvas is still limited to roughly 400 lines of code per day.
  2. There appear to be clear peaks and troughs where there are productivity bursts and lulls.
  3. Its unlikely that many programmers could output significantly more than 100,000 lines of code per year.
  4. There gets a point where you’re no longer contributing significant amounts of code in a project but rather fixing what is already there.

However obviously all of this assumes that my work is representative of most programmers, that the type of work is similar (in this case developing a very straightforward business web app – I’m sure you wouldn’t get the same results in one of Microsoft’s or Google’s labs) and as I said above doesn’t take into account the fact that this only counts pure C# lines and none of the other files that were a significant part of this project (aspx, js, asax, css and others).

Here is current chart for anyone interested



(Note that roughly the first 3-4 weeks of this project were only on a part time basis)

Phone number parsing is a bitch

Having spent the last couple of weeks looking for a decent implementation of a generic phone number parser that works with international numbers I’ve continually come up short.

I finally started writing my own custom one when lo and behold I happen to stumble across an awesome C# port of the library that Google uses in its Android platform to parse phone numbers.

Not only will this library support a format like +61 03 9123 1234 but can also understand extensions like this +61 03 9123 1234 ext 1234

Here is the original Java code:

And the C# port:

While I definitely don’t think its perfect and structurally ugly (in my opinion as a result of being a Java clone), its damn near close and building anything nearly as good would be a significant effort.