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):

Image

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

Image

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;
        installer.Start();
        //string output = installer.StandardOutput.ReadToEnd();
        installer.WaitForExit();
    }
}

private void ConfigureSite()
{
    try
    {
        InstallWCFNonHTTPActivation();

        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");
        }

        manager.CommitChanges();
    }
    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