Scott Hanselman

What is Serverless Computing? Exploring Azure Functions

August 27, '16 Comments [46] Posted in Azure | nodejs
Sponsored By

There's a lot of confusing terms in the Cloud space. And that's not counting the term "Cloud." ;)

  • IaaS (Infrastructure as a Services) - Virtual Machines and stuff on demand.
  • PaaS (Platform as a Service) - You deploy your apps but try not to think about the Virtual Machines underneath. They exist, but we pretend they don't until forced.
  • SaaS (Software as a Service) - Stuff like Office 365 and Gmail. You pay a subscription and you get email/whatever as a service. It Just Works.

"Serverless Computing" doesn't really mean there's no server. Serverless means there's no server you need to worry about. That might sound like PaaS, but it's higher level that than.

Serverless Computing is like this - Your code, a slider bar, and your credit card. You just have your function out there and it will scale as long as you can pay for it. It's as close to "cloudy" as The Cloud can get.

Serverless Computing is like this. Your code, a slider bar, and your credit card.

With Platform as a Service, you might make a Node or C# app, check it into Git, deploy it to a Web Site/Application, and then you've got an endpoint. You might scale it up (get more CPU/Memory/Disk) or out (have 1, 2, n instances of the Web App) but it's not seamless. It's totally cool, to be clear, but you're always aware of the servers.

New cloud systems like Amazon Lambda and Azure Functions have you upload some code and it's running seconds later. You can have continuous jobs, functions that run on a triggered event, or make Web APIs or Webhooks that are just a function with a URL.

I'm going to see how quickly I can make a Web API with Serverless Computing.

I'll go to and make a new function. If you don't have an account you can sign up free.

Getting started with Azure Functions

You can make a function in JavaScript or C#.

Getting started with Azure Functions - Create This Function

Once you're into the Azure Function Editor, click "New Function" and you've got dozens of templates and code examples for things like:

  • Find a face in an image and store the rectangle of where the face is.
  • Run a function and comment on a GitHub issue when a GitHub webhook is triggered
  • Update a storage blob when an HTTP Request comes in
  • Load entities from a database or storage table

I figured I'd change the first example. It is a trigger that sees an image in storage, calls a cognitive services API to get the location of the face, then stores the data. I wanted to change it to:

  • Take an image as input from an HTTP Post
  • Draw a rectangle around the face
  • Return the new image

You can do this work from Git/GitHub but for easy stuff I'm literally doing it all in the browser. Here's what it looks like.

Azure Functions can be done in the browser

I code and iterate and save and fail fast, fail often. Here's the starter code I based it on. Remember, that this is a starter function that runs on a triggered event, so note its Run()...I'm going to change this.

#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Table;
using System.IO; 

public static async Task Run(Stream image, string name, IAsyncCollector<FaceRectangle> outTable, TraceWriter log)
    var image = await req.Content.ReadAsStreamAsync();
    string result = await CallVisionAPI(image); //STREAM

    if (String.IsNullOrEmpty(result))
        return req.CreateResponse(HttpStatusCode.BadRequest);

    ImageData imageData = JsonConvert.DeserializeObject<ImageData>(result);
    foreach (Face face in imageData.Faces)
        var faceRectangle = face.FaceRectangle;
        faceRectangle.RowKey = Guid.NewGuid().ToString();
        faceRectangle.PartitionKey = "Functions";
        faceRectangle.ImageFile = name + ".jpg";
        await outTable.AddAsync(faceRectangle); 
    return req.CreateResponse(HttpStatusCode.OK, "Nice Job");  

static async Task<string> CallVisionAPI(Stream image)
    using (var client = new HttpClient())
        var content = new StreamContent(image);
        var url = "";
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Environment.GetEnvironmentVariable("Vision_API_Subscription_Key"));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        var httpResponse = await client.PostAsync(url, content);

        if (httpResponse.StatusCode == HttpStatusCode.OK){
            return await httpResponse.Content.ReadAsStringAsync();
    return null;

public class ImageData {
    public List<Face> Faces { get; set; }

public class Face {
    public int Age { get; set; }
    public string Gender { get; set; }
    public FaceRectangle FaceRectangle { get; set; }

public class FaceRectangle : TableEntity {
    public string ImageFile { get; set; }
    public int Left { get; set; }
    public int Top { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

GOAL: I'll change this Run() and make this listen for an HTTP request that contains an image, read the image that's POSTed in (ya, I know, no validation), draw rectangle around detected faces, then return a new image.

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) {
var image = await req.Content.ReadAsStreamAsync();

As for the body of this function, I'm 20% sure I'm using too many MemoryStreams but they are getting disposed so take this code as a initial proof of concept. However, I DO need at least the two I have. Regardless, happy to chat with those who know more, but it's more subtle than even I thought. That said, basically call out to the API, get back some face data that looks like this:

2016-08-26T23:59:26.741 {"requestId":"8be222ff-98cc-4019-8038-c22eeffa63ed","metadata":{"width":2808,"height":1872,"format":"Jpeg"},"faces":[{"age":41,"gender":"Male","faceRectangle":{"left":1059,"top":671,"width":466,"height":466}},{"age":41,"gender":"Male","faceRectangle":{"left":1916,"top":702,"width":448,"height":448}}]}

Then take that data and DRAW a Rectangle over the faces detected.

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
    var image = await req.Content.ReadAsStreamAsync();

    MemoryStream mem = new MemoryStream();
    image.CopyTo(mem); //make a copy since one gets destroy in the other API. Lame, I know.
    image.Position = 0;
    mem.Position = 0;
    string result = await CallVisionAPI(image); 

    if (String.IsNullOrEmpty(result)) {
        return req.CreateResponse(HttpStatusCode.BadRequest);
    ImageData imageData = JsonConvert.DeserializeObject<ImageData>(result);

    MemoryStream outputStream = new MemoryStream();
    using(Image maybeFace = Image.FromStream(mem, true))
        using (Graphics g = Graphics.FromImage(maybeFace))
            Pen yellowPen = new Pen(Color.Yellow, 4);
            foreach (Face face in imageData.Faces)
                var faceRectangle = face.FaceRectangle;
                    faceRectangle.Left, faceRectangle.Top, 
                    faceRectangle.Width, faceRectangle.Height);
        maybeFace.Save(outputStream, ImageFormat.Jpeg);
    var response = new HttpResponseMessage()
        Content = new ByteArrayContent(outputStream.ToArray()),
        StatusCode = HttpStatusCode.OK,
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    return response;

I also added a reference to System. Drawing using this syntax at the top of the file and added a few namespaces with usings like System.Drawing and System.Drawing.Imaging. I also changed the input in the Integrate tab to "HTTP" as my input.

#r "System.Drawing

Now I go into Postman and POST an image to my new Azure Function endpoint. Here I uploaded a flattering picture of me and unflattering picture of The Oatmeal. He's pretty in real life just NOT HERE. ;)

Image Recognition with Azure Functions

So in just about 15 min with no idea and armed with just my browser, Postman (also my browser), Google/StackOverflow, and Azure Functions I've got a backend proof of concept.

Azure Functions supports Node.js, C#, F#, Python, PHP *and* Batch, Bash, and PowerShell, which really opens it up to basically anyone. You can use them for anything when you just want a function (or more) out there on the web. Send stuff to Slack, automate your house, update GitHub issues, act as a Webhook, etc. There's some great 3d party Azure Functions sample code in this GitHub repo as well. Inputs can be from basically anywhere and outputs can be basically anywhere. If those anywheres are also cloud services like Tables or Storage, you've got a "serverless backed" that is easy to scale.

I'm still learning, but I can see when I'd want a VM (total control) vs a Web App (near total control) vs a "Serverless" Azure Function (less control but I didn't need it anyway, just wanted a function in the cloud.)

Sponsor: Aspose makes programming APIs for working with files, like: DOC, XLS, PPT, PDF and countless more.  Developers can use their products to create, convert, modify, or manage files in almost any way.  Aspose is a good company and they offer solid products.  Check them out, and download a free evaluation.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Visual Studio 2015 - Fixing "Dependencies npm not installed" from fsevents with node on Windows

August 14, '16 Comments [35] Posted in ASP.NET | nodejs
Sponsored By

Maria and I were doing some work together on Thursday and I did a clone of one of her ASP.NET Core repositories and opened it in Visual Studio 2015 Community Edition on my local machine. Some of the JavaScript tool libraries didn't load so I went back into Solution Explorer to see if there was a problem and I saw this weird error that said (or at least, I read it as) "npm not installed."


That's weird, since I have npm installed. I dropped out to the command line and ran:

C:\Users\scott>npm --version

I also ran "where" to see where (and how many) npm was installed. Side note: WHERE is super useful and not used as often as it should be by y'all.

C:\Users\scott>where npm
C:\Program Files\nodejs\npm
C:\Program Files\nodejs\npm.cmd

This looks OK as two of those npms are shell scripts and not run on Windows. Just to make sure you have the version of npm you want, Felix made a VERY useful npm-windows-upgrade utility that you run like this, ironically with npm.

npm install --global --production npm-windows-upgrade

I've used this tool many times with success. It also lets you choose the exact version you want and it's very smart.

However, then I realized that Visual Studio wasn't saying that npm wasn't installed, it was saying a dependency in the npm tree below wasn't installed. That hyphen - is intended to mean something. For the record, I think this is not intuitive and is a poor UX. Perhaps it should say "package(s) not installed" but you get the idea now.

I started manually opening the tree up one item at a time looking for the bad package - while quietly swearing to myself - until I realized that the Solution Explorer tree nodes are searchable.


This is UX issue number two, for me. I think the "broken" library should also include the BANG (!) or warning icon over it. Regardless, now I know I can quickly do a string search.

So what's up with the fsevents library?

I can check the Visual Studio Output Window and I see this:

npm WARN install Couldn't install optional dependency: Unsupported
npm WARN EPACKAGEJSON No description

I dropped out to the command prompt into to the project's folder and run "npm ls" to see an ASCII tree that effectively is the same tree you see in Visual Studio. Note the screenshot with the ASCII tree below.

The output of "npm ls" is a nice ASCII tree

What's that "UNMET OPTIONAL DEPENDENCY?" for fsevents?

Looks like fsevents is a package that is only used on OSX, so it's an optional dependency that in the case of Windows is "unmet." It's a WARNING, of sorts. Perhaps it's more an "INFO" or perhaps, one could argue, it doesn't need to be shown at all on Windows.

A quick google shows that, well, the entire world is asking the same thing. So much so that it got pretty heated in this GitHub Issue asking a similar question.

Regardless, it seems to me that something inside Visual Studio really doesn't appreciate that warning/info/notOKness and says, "hey it's not installed." The part that is missing is that, well, it doesn't need to be installed, so Visual Studio should relax.

A Fix

Here's where it gets super interesting. Visual Studio (consider it from their point of view) needs to keep things consistent so it tests with, and ships with, a version of npm.

I can check that like this:

C:\>"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\npm.cmd" --version

Again, this makes sense. That way when working in a large group we can all be sure we're on the same version of stuff. When you get a new version of the Web Tools for Visual Studio, presumably this version of npm gets updated. This also means that unless you tell Visual Studio otherwise, the npm and node you get when running a build in VS is gonna be different than if you do it outside - if you stick with the default settings.

Fear not. It's easily updated. I went over to Tools | Option in Visual Studio:

Tools | Options | External Web Tools has its own list of node copies, and it doesn't include mine

See the Web\External there? I added my node installation like this and made sure it was at the top.

Tools | Options | External Web Tools has its own list of node copies, and I have ADDED my path now.

Then I right click on npm and Restore Packages and all is right with the world as now I'm using npm 3.10.5 rather than 3.3.4.

There are no npm errors anymore

The Output Window for 3.10.5 shows this different output, which apparently stresses Visual Studio out less than npm 3.3.4. (Actually I think VS is calling an npm library, rather than shelling out and parsing the "npm ls --json" payload, but you get the idea.)

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14

Adding my global npm/node folder fixes this issue for me and I can move on.

The Weird

BUT. In my fix I'm using npm globally - it's in my %PATH%. The change I made affects all Visual Studio projects on my machine, forever.

Maybe I need to be smarter? Maybe Visual Studio is already being smart. Note the second option there in the list? It's pointing to .\node_modules\bin. That's a LOCAL node-modules folder, right? Ah, I can just add specific version of npm to packages.json there if need be on a project by project basis without affecting my entire system OR changing my Visual Studio settings, right?

However, when I run my build, it's ignoring my project's locally installed npm!

PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\git
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\npm.CMD" install
npm WARN install Couldn't install optional dependency: Unsupported
npm WARN EPACKAGEJSON No description
npm WARN EPACKAGEJSON No repository field.
npm WARN EPACKAGEJSON No license field.

How can I be sure it's ignoring that relative path? I can temporarily hardcode my local node_modules, like this. Note the PATH *and* the newer output. And it works.

PATH=D:\github\sample-NerdDinner\NerdDinner.Web\node_modules\.bin;node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\git
"D:\github\sample-NerdDinner\NerdDinner.Web\node_modules\.bin\npm.CMD" install
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14
npm WARN No description
npm WARN No repository field.
npm WARN No license field.

In this screenshot below I have npm 3.10.6 installed in my project, locally, but it's not being used by Visual Studio if the path remains relative.

I am 99% sure that the relative path ".\node_modules\.bin" that's prepended to the PATH above either isn't being used OR is interfering in some way.

Am I misunderstanding how it should work? Perhaps I don't understand npm enough?


I'm going to continue to dig into this and I'll update this post when I have an answer. For now, I have a fix given my globally installed npm.

I've also passed my feedback/bug report onto the Visual Studio team in the form of an email with a link to this blog post. I hope this helps someone!

Sponsor: Big thanks to Redgate for sponsoring the feed this week. Could you deploy 1,000 databases?Imagine working in a 70-strong IT team, with 91 applications and 1,000+ databases. Now imagine deployment time. It’s not fiction, it’s fact. Read FlexiGroup's story.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

UPDATED for 2015: How to install the nodejs Ghost blog software on Azure Web Apps (and the Deploy to Azure Button)

April 20, '15 Comments [9] Posted in Blogging | nodejs | Open Source
Sponsored By

What? Didn't I blog about this before? Yes, in fact, in 2013 I did an article showing how to get Ghost - a lovely nodejs-based blogging app - running on Azure.  The instructions involved making some changes to Ghost itself to make it friendlier to Azure and doing a git deploy. Since this post both Ghost AND Azure have become friendlier. ;)

Fast forward two years and the instructions have changed! In fact, they've gotten WAY easier. You can still theoretically follow most of my old instructions, but these new ones are WAY better, so just do it this way.


There's a "Deploy to Azure" button up at that you can get an put in YOUR GitHub project's so folks can easily and quickly deploy your app as well!

Here's what you do. Head over to the GitHub repository for Ghost Azure. Click Deploy to Azure. That will automatically install Ghost for you in Azure.

The Deploy to Azure Button

The website will look at the repository from the HTTP Referer header. You'll end up with a nice form like this.

DO make sure to double check your settings, the Site Location is alphabetical right now, and you may not want your blog in Brazil. ;)


Hit Next, then check the summary that will warn you what's getting created, then hit Deploy. Boom. Azure will actually run through the template and setup Ghost (or whatever app you wanted) automatically.

  • Note it's setting it up from Source Control as well, although you can certainly change this. For example, you might want to Fork it yourself, and then Deploy.
  • However, as this is set up today, you won't get updates until you go to Deployments within the Azure Portal and click Sync. You decide if you want the app to update when new code is committed.

After it's created, you can manage your site in the Azure Portal. I made a little free one for this example, as can you if you like.

Ghost in the Azure Portal

And it works just great!

Ghost running on Azure

It's not super obvious what to do next. You'll need click the little chevron there, or visit something like /admin, and you'll get redirected to the Ghost setup process online.


Now you can start your first post!

My first post in Ghost

What's going on here?

Felix Rieseberg added a few files to Ghost and has the fork up here on GitHub. The most interesting one is the AzureDeploy.json. This is an Azure Resource Manager template. Here's another simple example from Elliot Hamai for an ASP.NET MVP app. This file tells Azure (and the Deploy to Azure button) what kinds of things it needs to create and actually gives the system enough information to build a whole form for you!

Maybe this is the perfect time for you to start your own blog! Perhaps you've been putting it off. Go check out my FREE two-hour documentary movie with Rob Conery called Get Involved in Tech! We will get you ready to jump into the world of Social Software Development.

Here's a video of Elliot and I talking about the Deploy to Azure button on Azure Friday. Here's Elliot's blog announcing Deploy to Azure and explaining more.

Remember that Ghost is open source and you can learn more at!

DON'T WANT TO SIGN UP FOR AZURE? You can try Azure out for an hour without signing up for anything. Check out You can make a PHP, Java, nodejs, Python, ASP.NET web app, or even setup Ghost itself. You can also try out Visual Studio online, which is basically a complete IDE in your browser written entirely in JavaScript.

Sponsor: Big thanks to our friends at Raygun for sponsoring the feed this week. I use Raygun myself and I encourage you to explore their stuff, it's really something special. Get full stack error reporting with Raygun! Detect and diagnose problems across your entire application. Raygun supports every major programming language and platform - Try Raygun FREE!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Enabling Websockets for Node apps on Microsoft Azure

November 3, '14 Comments [13] Posted in Azure | Diabetes | nodejs | Open Source
Sponsored By

Whoa my Blood Sugar is a CGM in the Cloud!NOTE: This is a technical post, I'll blog more about Nightscout later this week. Subscribe and watch for my take, or visit

I'm running an application called Nightscout that is a node app with a MongoDB backend that presents a JSON endpoint for a diabetic's blood sugar data. I use my Dexcom G4 CGM (Continuous Glucose Meter) connected with a micro-USB OTG cable to an Android phone. An Android app bridges the device and POSTs up to the website.

Azure is well suited to run an app like this for a few reasons. Node works great on Azure, MongoLabs is setup in the Azure Store and has a free sandbox, Azure supports WebSockets, and * has a wildcard SSL cert, so I could force SSL.

Enabling Websockets and Forcing SSL

So my goal here is to do two things, make sure Websockets/ is enabled in my app because it's been using polling, and force my app to use SSL.

Setting up a node.js site on Azure is very easy. You can see a 3 minute video on how to do a Git Deploy of a node app here. Azure will see that there's a app.js or server.js and do the right thing.

However, because IIS and node are working together to host the site (IIS hands off to node using a thing called, wait for it, iisnode) you should be aware of the interactions.

There's a default web.config that will be created with any node app, but if you want to custom stuff like rewrites, or websockets, you should make a custom web.config. First, you'll need to start from the web.config that Azure creates.

Related Link:  Using a custom web.config for Node apps

Let's explore this web.config so we understand what's it's doing so we can enable Websockets in my app. Also, note that even though our project has this web.config in our source repository, the app still works on node locally or hosts like Heroku because it's ignored outside Azure/IIS.

  • Note that we say "webSocket enabled=false" in this web.config. This is confusing, but makes sense when you realize we're saying "disable Websockets in IIS and let node (or whomever) downstream handle it"
  • Note in the iisnode line you'll put path="server.js" or app.js or whatever. Server.js appears again under Dynamic Content to ensure node does the work.
  • I added NodeInspector so I can do live node.js debugging from Chrome to Azure.
  • Optionally (at the bottom) you can tell IIS/Azure to watch *.js files and restart the website if they change.
  • We also change the special handling of the bin folder. It's not special in the node world as it is in ASP.NET/IIS.
<?xml version="1.0" encoding="utf-8"?>
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:

<!-- Visit for more information on WebSocket support -->
<webSocket enabled="false" />
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^server.js\/debug[\/]?" />

<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>

<!-- All other URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
<action type="Rewrite" url="server.js"/>

<!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
<remove segment="bin"/>

<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />

You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled

See for a full list of options
<!--<iisnode watchedFiles="web.config;*.js"/>-->

Next, turn on Websockets support for your Azure Website from the configure tab within the Azure Portal:

Turn on Websockets in the Azure Portal

Now I need to make sure the node app that is using is actually asking for Websockets. I did this work on my fork of the app.

io.configure(function () {
- io.set('transports', ['xhr-polling']);
+ io.set('transports', ['websocket','xhr-polling']);

It turns out the original author only put in one option for to try. I personally prefer to give it the whole list for maximum compatibility, but in this case, we clearly need Websockets first. When will Websockets fall back if it's unavailable? What Azure website pricing plans support WebSockets?

  • Free Azure Websites plans support just 5 concurrent websockets connections. They're free. The 6th connection will get a 503 and subsequent connections will fallback to long polling. If you're doing anything serious, do it in Shared or above, it's not expensive.
  • Shared Plans support 35 concurrent websockets connections, Basic is 350, and Standard is unlimited.

You'll usually want to use SSL when using Websockets if you can, especially if you are behind a proxy as some aggressive proxies will strip out headers they don't know, like the Upgrade header as you switch from HTTP to Websockets.

However, even free Azure websites support SSL under the * domain, so doing development or running a small site like this one gets free SSL.

I can force it by adding this rule to my web.config, under <system.webServer>/<rewrite>/<rules/>:

<rule name="Force redirect to https">
<match url="(.*)"/>
<add input="{HTTP_HOST}" pattern=".+\.azurewebsites\.net$" />
<add input="{HTTPS}" pattern="Off"/>
<add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>

Note the pattern in this case is specific to, and will take any Azure website on the default domain and force SSL. You can change this for your domain if you ike, of course, assuming you have an SSL cert. It's a nice feature though, and a helpful improvement for our diabetes app.

I can confirm using F12 tools that we switched to WebSockets and SSL nicely.


The whole operation took about 15 minutes and was a nice compatible change. I hope this helps you out if you're putting node.js apps on Azure like I am!

Sponsor: Big thanks to Aspose for sponsoring the feed this week! Working with Files? Aspose.Total for .NET has all the APIs you need to create, manipulate and convert Microsoft Office documents and many other formats in your applications. Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

"It's just a software issue"- Edge.js brings Node and .NET together on three platforms

April 30, '14 Comments [44] Posted in Learning .NET | nodejs | Open Source
Sponsored By
.NET and node together on three platforms

There was an engineer I used to work with who always said "That's just a software issue." No matter how complex the issue, no matter how daunting, they were confident it could be solved with software.

.NET and C# and NuGet and the community have been making some amazing stuff in the last few years like ScriptCS, Chocolately, Boxstarter. Azure Websites now supports ASP.NET, sure, but also PHP, Python, Java (Tomcat or Jetty or your own container), and node.js. Getting these things to work together has been an interesting software issue. Apps can run side-by-side, but they can't really talk to each other in-process. (Mostly one just moves data between universes over JSON and HTTP when need-be.)

However, Tomasz Janczuk has been working on Edge.js (on Github) for a while now. I showed his work at jQuery Portland last year, but this week he's taking it to the next level. He is creating a wormhole between software universes.

Edge.js now lets you run node.js and .NET code in-process on Windows, Mac, and Linux.

The name is great. An edge connects two nodes, and Edge.js is that edge.

node and .NET connected by edge.js

Here's a node app hello world node app calling .NET. Don't sweat that the .NET code is tunneled inside a comment, this is the Hello World proof of concept.

var edge = require('edge');

var helloWorld = edge.func(function () {/*
async (input) => {
return ".NET Welcomes " + input.ToString();

helloWorld('JavaScript', function (error, result) {
if (error) throw error;

Perhaps you have a bunch of CPU intensive work or algorithms in C#, but you've also got a node.js app that needs the result of that work. Edge can help with that.

You can bring in a CS or CSX file into node like this:

var myCSharpCode = edge.func(require('path').join(__dirname, 'myCSharpCode.csx'));

You can bring code from a .NET DLL into a node.js compiled as well.

var clrMethod = edge.func({
assemblyFile: 'My.Edge.Samples.dll',
typeName: 'Samples.FooBar.MyType',
methodName: 'MyMethod'

It's not a hack, it's a clear way to marshal between CLR threads and the V8 (the node Javascript engine) thread. It's also interesting from a comp-sci perspective as the CLR can have many threads and V8 has the one.


Here's Tomasz's own words:

Edge.js provides an asynchronous, in-process mechanism for interoperability between Node.js and .NET.

You can use this mechanism to:

  • access MS SQL from Node.js using ADO.NET more...
  • use CLR multi-threading from Node.js for CPU intensive work more...
  • write native extensions to Node.js in C# instead of C/C++
  • intergate existing .NET components into Node.js applications

Read more about the background and motivations of the project here.

Now, you might ask yourself, what problem does Edge.js solve? The answer is in the Edge.js FAQ.

Go explore what you can do. Edge goes much further than just C# and Node. It works on Windows, OSX, and Ubuntu but you should just "npm install edge" as there's a node package available.

Have fun! You have a lot more power and flexibility than you think. It's just a software problem.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Page 1 of 2 in the nodejs category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.