Force Https Redirection for NodeJs Apps hosted in Azure

There seems to be many posts and stackoverflow questions around forcing HTTPS in NodeJs/Express applications.  I’ve found a few specific ones dealing with Azure web app hosting to be missing some key points.

A note on Azure NodeJs hosting

Microsoft extended IIS to include a NodeJs module.  This essentially means, your node app is still running on IIS.  It is leveraging IIS for the rest of the benefits it provides being an application server (not just a web server).  The “web server” piece is being swapped out for whatever you’re including in your node app… Express for example.

Do you even middleware, bro?

Let’s start by saying: ‘like all things in development, there are many ways to do the same thing’.  That doesn’t mean that they are all the right way for the right problem.  There are numerous example of adding Express middleware to process the incoming request for either a secure check or a header check (azure adds the x-arr-ssl header to SSL requests)

These implementations will work.  But why add code at the application level when the application server has runtime modules baked in to support them?  The lower level the implementation can be processed at, the faster it will execute.  Despite your feelings for Microsoft or IIS, IIS is still extremely proficient and efficient.  Now, adding the fact that Azure orchestrates IIS (and balanced instances with scaling) for you only strengthens the approach to configure application server features on the application server and not the application being served.

How to configure IIS for a Node app in Azure

I will assume you can deploy your node web app to Azure already.  There are official MSDN instructions and easily searchable blogs with enough instructions to generate your and git push or CI it from Azure and VCS-of-your-choice.

The key is, after you deploy the first time and get your awesome “Hello, world” loaded from * something happens during the  It generated a web.config.  This is familiar to any .Net developer that’s been awake in the last decade.

When you examine this web.config, it has barebones IIS features since it is not hosting a .Net app, it’s hosting a Node app.  In particular, it loads up the ‘iisnode’ module.  Once this is done, you need to get your favorite FTP client ready.

Azure allows an FTP user/pwd to be defined PER subscription (yes subscription – not per app/azure resource provisioned).  You can find it from most any resource’s Settings (in the new preview portal Settings->Deployment Credentials).  Once this is set up, grab the FTP address (in the new preview portal Settings->Properties).

You’ll find the web.config in /site/wwwroot.  Download it and add it to your root source directory.  Include it in your git repo as well.  From this point on, when your site deploys Azure will use the existing web.config instead of creating a vanilla one.

Add the ReWrite rule

Now that you have your web.config in your development source, you can add the rewrite rule for IIS to manage before it ever touches your node application.

Add an xml child element under <rules> to redirect to HTTPS:

  <!-- Redirect all traffic to SSL -->
  <rule name="Force HTTPS" enabled="true">
    <match url="(.*)" ignoreCase="false" />
      <add input="{HTTPS}" pattern="off" />
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />

  .. omitted ..

This will instruct IIS to force HTTPS on all requests.  There are more things that can be done in the web.config for node apps too to make life easier and keep the warm fuzzy “I know it will work with Azure because I’m using their IaaS deployment configuration strategy”.

This gist has the details:


Hassle Free Level Boundaries in Unity3D

Creating constrained areas and general level boundaries can become tedious when dealing with more complicated design and structure.  In the programming world, we call this giant waste of time boiler code.  I suppose in the level design world, we can call it boiler design.

You can spend an hour or so adding in custom colliders to shape the bounds of your areas or levels.  But, what happens if the scale was off and you need to tweak a few things… you have to go through and adjust everything (especially for height).  This is a lot of wasted time and effort where it could be applied to what will count: your game/simulation/product.

Fortunately, there is a new tool available on the asset store.  The Boundary Tool allows rapid creation of collision areas and each can be grouped and color coded for reference.  They also can overlay to your scene view and they do not get in the way when dragging prefabs/models into the scene to place it on an actual mesh or terrain.  It also supports tweaking the collision areas during editor playback so you can truly test the positioning of the “invisible walls” and your characters without the risk of publishing a level that has map exploits.

There is absolutely no integration code to be done.  It is an editor extension designed for artists and level designers or a programmer who doesn’t have time for tooling when they could focus on gameplay and mechanics.

Here are some videos of it in action:

Disclaimer: I worked on this tool.  However, it still addresses a large time sink in the level design workflow.

Consuming a WCF Service from Unity3D

Unity3D is running MONO.Net and WCF implementation was for some time being worked on under “Moonlight 3.5” for MONO.  It has been merged into the main distribution of MONO for a while now; and yes, Unity3D supports it.  I will assume if you are reading this, you know how to create and host WCF services so I will not touch that at all.

Assumption: You have a WCF service running on your local IIS server at: http://localhost:8080/MyService.svc

There are a few infrastructural steps involved on the Unity3D side:

  • Setting API compatibility
  • Add plugins to project tree
  • Generate and add client proxy
  • Add gateway specific to the Unity3D application

Setting API compatibility

By default, Unity3D uses a stripped down version of the MONO framework.  You can consider this similar to .Net 4.0’s Client Profile versus Full version.  This setting can be changed through the menu bar: Edit -> Project Settings -> Player.  It needs to be set to 2.0 and not 2.0 Subset.

Add plugins to project tree

Unity3D’s runtime will enumerate a specific folder for assemblies and make those references available to the scripting engine “globally”.  At the root level, simply create “Plugins”.  Any assembly you package and use as a business layer should be deployed here.

In the new container folder, you need to add the MONO assembly compilations for the standard WCF assemblies you’d normally use in a Microsoft .Net Framework runtime.  Navigate to your Unity3D installation directory and start diving into the mono 2.0 location (for a point of reference, mine is: C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\2.0).

You will need to copy three assemblies into the Plugins container:

  • System.Runtime.Serialization
  • System.Security
  • System.ServiceModel

Generate and add client proxy

Add another container named “ClientProxies”.  This can technically be nested under “Scripts” or whatever folder convention / structure you may have or desire (Plugins is the only engine specific folder).  Now run the Visual Studio Command Prompt and navigate to the ClientProxies folder (this will have the generated proxy code placed here automatically, you can alternatively generate it anywhere on your filesystem and move/copy it into this container).  Generate the proxy class using SVCUTIL

svcutil -out:MyServiceClient.cs http://localhost:8080/MyService.svc?wsdl

This will generate the same files that get created when adding a Web Service reference through Visual Studio.

Add gateway specific to the Unity3D application

Now all that remains is writing a gateway script that will use the newly created client proxy as an object and execute methods off the service.  You do this the same as any ofther WCF in-code call.  You will access to the MyServiceClient object type now, and can pass in the endpoint and binding information through the constructor.

Thats all!

Microsoft Unity, Workflow 4 and You!

I encountered an interesting challenge a few weeks ago that I didn’t get around to documenting.

At work, Workflow was never an evaluated technology and past that, best practices are hard to come by given the company’s latency in adopting new things.  Unity as an inversion of control for example, is still very rare.  I deal in WCF services mostly, and only a small group of us in my department get involved.  Unity was easy for us to “sneak” into adoption.

Now the challenge…  Workflow 4 was completely foreign to me and everyone on my team.  So we have services with mocked implementations down to the method level and we need to consume them from inside the workflow; sounds easy!

It wasn’t at first.

Not until some research revealed workflow extensions that can be added into the pipeline when executing the workflow via code.  Essentially we can create the unity container as normal, and then add the container as an extension into the workflow.  Then code activities can retreive the unity extension and use the service locator to get injected implementations.

The workflow creation and execution looked like:

        public void Execute()
            IUnityContainer container = new UnityContainer();
            ProcessorUnityServiceLocator serviceLocator = new ProcessorUnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);

            ActualWorkFlowXaml flow = new ActualWorkFlowXaml();
            WorkflowApplication app = new WorkflowApplication(flow);

            // add the service locator to the WF version of a service locator
           app.Extensions.Add<IServiceLocator>(() => serviceLocator);


Which is nice and clean…   all the Unity bindings are already done before this clearly.

And in a new base code activity inheriting CodeActivity you pull it out:

        protected BaseUnityServiceLocator ServiceLocator { getset; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
       protected override void Execute(CodeActivityContext context)
            ServiceLocator = (BaseUnityServiceLocator)context.GetExtension<IServiceLocator>();

Enjoy, if I missed anything, post back, I’ll try to answer any questions.