Using Azure to host the node.js backend of your Xamarin-based iOS app

TL;DR: This is how to tell Azure to host your node.js web service even though your repository contains .NET solution files and/or projects: Create an app setting called Project and set its value to the directory where your node app resides, e.g. src\Server – this is the argument that will make Azure decide to host your node.js stuff and not the .NET stuff.

This is not new – it’s how you pick a .NET project to host as well when your repository contains multiple hostable .NET projects, but when it’s .NET you point to a project file instead of a directory.

Do NOT be fooled by GitHub issues mentioning setting the SCM_SCRIPT_GENERATOR_ARGS app setting to --node – doing that will not work together with the Project setting!

I wrote this blog post because it took me quite a while to figure this seemingly obvious thing out, mostly because I got fooled by various red herrings around the net referring to the aforementioned Kudu setting.

Long version 🙂

Lately, I’ve been tinkering a bit with Xamarin Studio, trying to get a little bit into building a simple iPhone app.

My app needs a backend, which will be function as a mediator between the iPhone app and another backend, allowing me to

  • tailor the service to my iPhone app, trimming the API for my needs, and
  • not worry too much about having to update the iPhone app everytime something changes on the real backend (the “backend-backend”…)

This is a sound way of putting these things together IMHO, and since the backend for my iPhone app will mostly function as a mediator/proxy it was kind of an obvious opportunity to get to play a little bit with node.js as well 😉 (because JavaScript is fun, and because of its asynchronous nature)

But – alas – when I Git-deployed my Azure web site, I got the following message in the Azure portal:

Skærmbillede 2014-04-22 kl. 20.35.36

and clicking the log revealed that Azure was kind of confused by the fact that my repository did not contain an obvious single candidate for something to build & deploy – it had multiple (the Xamarin solution Client.sln and my initial Web API-based dummy server solution Server.sln):

Skærmbillede 2014-04-22 kl. 20.35.46

When a Git-deployed Azure web site has multiple things that can potentially be built & deployed, you’ll usually create a Project app setting and point it to the web project that you want to host in that particular web site, e.g. setting it to src\Something.Web\Something.Web.csproj if that is a web site.

That’s also what we need to do here! – just by pointing to the directory where your node app’s package.json resides – in this case it’s src\Server2 (which was the most awesomest name I could come up with for my server no. 2….) It’s that simple 😉

Getting my Mongo on

This is the sixth post in a small series on Node.js. In this post, I will take a look at how to use my MongoDB from a Node app.

First, let’s install a driver for MongoDB: node-mongodb-native:

NPM really make it easy to get going!

Now, in order to connect to MongoDB, do this:

This should be done only once when the application starts up.

Then, to access a collection, do this:

Inside the function above, coll gives you access to do all the usual stuff to a MongoDB collection. To name a few, there’s insert, find, findOne, ensureIndex, count, etc.

As the node-mongodb-native documentation is pretty sparse, I’ve found it useful to open up a Node.js shell and connect with the driver, allowing me to inspect the various objects’ properties and methods, e.g. by inspecting db.__proto__ like so:

and coll.__proto__ like so:

Of course this way of barfing functions all over the place is not pretty, but it makes it possible to get a glimpse of what kinds of operations that can be performed on the various objects.

Getting Express to show flash messages

Now, this one might be obvious if you’re experienced with Node.js and Express, but it took me a while to figure out… therefore, so I know where to look the next time I forget it, and as a service to people Googleing in frustration; without further ado:

How to make Express render flash messages

First: Realize that flash messages are messages that are stored on the server for the duration between two requests from the same client, and thus are only available in the next request :D. Don’t try to req.flash(...) stuff and expect it to be available when render ing the view immediately after… (yeah, I did that for some time – pretty stupid, I know)… the locals object is how you do that.

Next: You need to make sure that the cookie decoder and session middleware are active:

Then: To store messages to be shown in the next request:

Note how nifty the PRG pattern can be implemented with Express. Note also that flash supports formatters, where the default supports %s and _, e.g.

resulting in something like this (with jQuery UI for formatting):

Last: When handling the next request, the flash messages are available in an object that can be retrieved only once by calling flash with no arguments on the request:

Now, having passed the flash object to my view, I can do this in my HAML view:

where the preliminary :if typeof flash != 'undefined' ensures that we don’t get errors if we haven’t transferred the flash object to the locals object.

The only annoying thing is that we need to remember to transfer the flash object in each request handler. I set out to write a piece of Node.js middleware that handled this, and I thought it was going pretty well until I realized that the middleware was executed in the wrong place. I haven’t found out if there’s an appropriate hook that can do this, so if anyone knows, please tell me :).

What is that module thing again?

This is the fourth post in a small series on Node.js. In this post, I will take a look at how the Node.js module mechanism works.

In my previous posts on Node.js, I nonchalantly went ahead and require(...)d something called http – but what was that? And what happened when I did that?

Well, require is one of the few globals when running a Node program, and it is used to import a module. The parameter is a string, which Node uses to look for a file to load.

The simplest usage refers directly to a file relative to the path of the currently running program. E.g., if I have a module residing in a file called importantBizLogic.js in the lib folder beneath my program’s directory, I can include its exports (which I’ll get back to in a moment :)) like so:

If I omit the ./, Node will go look for importantBizLogic in each directory in the require.paths array, which is a list of default paths to search for modules.

Let’s see what it contains… Go to a terminal and enter the Node shell:

Great – so that’ s where my global modules reside. Now, what was that export thing again?

Well, that’s related to how importantBizLogic.js is structured… in order to control how the import works, a module must explicitly export stuff – and that can be done like so:

– allowing this module to be imported and used like so:

Nifty!

Apparently – and I am almost embarrassed that I did not know that – there is a thing called CommonJS, which is an initiative that strives to create a JavaScript standards library – and the require stuff I’ve described here is actually just Node implementating the CommonJS Modules specification. Pretty sweet, actually!

Up and running with Express

This is the third post in a small series on Node.js. In this post, I will take a look at how to get up and running with Express.

Let’s get Express installed – first, let’s install NPM – a package manager for Node:

That was easy. Now, Express can installed like this:

Too easy!

Now, let’s create a simple app like we did the last time:

Punch in the following few lines:

and run the app from the terminal like so:

and navigate to http://localhost:3000 – on my machine it looked like this:
Hello Express

That was easy. See how the API pretty much resembles Node’s builtin HTTP server, except it adds routes into the mix!

Now, in order to build a web site we need some kind of view engine to help generate some HTML for us. I have used Haml a couple of years ago, and I really liked it… and luckily, some nice people have made Haml available to Node apps, so let’s try installing that:

Now we configure Express by punching in the following stuff in the app:

As you can see, I tell Express to use Haml as the default view engine. Moreover, I configure Express to serve static content from the /public folder in my app dir, and then I install the bodyDecoder middleware which will parse incoming posts and make posted values available in req.body.

Now, let’s alter our action to render a view:

and now create two files, layout.haml and index.haml in the /views folder. Mine look like this – /views/layout.haml:

and /views/index.haml:

Now, let’s go to the terminal and node app.js and navigate to http://localhost:3000 – on my computer it looks like this:
Hello Express + Haml

As you can see, view models can be handed to the view via the locals object.

This was some basic web app stuff – only thing missing is some way to persist data, so next time I will take a look at how to get my Mongo on…

Getting started with Node.js

This is the second post in a small series on Node.js. In this post, I will take a look at how to get started and run the ubiquitous “Hello world” sample.

First, create a directory somewhere and Git clone Node… I did it like this:

Then, build and install Node like this:

If you get permission errors during the last step, you might need to do a

to grant yourself ownership of everything beneath /usr/local. Note however, that this should probably only be done if the machine is your own personal machine.

Now, try typing node -v in the terminal… I got this:

Now, let’s finish this post by creating a Node app like so (using TextMate or whatever you prefer):

Punch in the following few lines:

and go the terminal again and type

which yields

Now, when I navigate to http://localhost:8124 I get this:

Node.js HTTP Hello World

Nifty, huh?

In the next post, I will see if I can get up and running with Express – a simple but powerful Sinatra-like web framework for Node.

I want to learn Node.js

Preface

More than three years ago, I watched a couple of videos with Douglas Crockford that changed my view on JavaScript completely!

I must admit that I too used to consider JavaScript a toy language, somehow inferior to “real programming languages” like Java and C#.

This view was of course induced by the sheer amount of JavaScript crap code available to copy/paste from the web, almost always operating on an equally crappy non-standards compliant DOM implementation in some crappy browser – but after watching those videos I actually began to understand that JavaScript was a pretty cool and powerful language.

Some time after, Crockford released JavaScript: The Good Parts which I immediately read, and at that time I remember saying to one of my colleagues: “I think it would be cool to build large systems in JavaScript”.

At that time, stuff like Rhino was around, but I had never heard of anyone actually using it, and executing JavaScript on the JVM by compiling JavaScript into Java into bytecode didn’t sound sexy at all to me.

Today

Recently, however, I have somehow come across Node.js at different occasions, and I have really been meaning to check it out. If you don’t know what Node is about, I can quote the homepage: Node is “Evented I/O for V8 JavaScript.”

That’s right! Let’s break that down:

  • Evented: There’s only one thread executing in a Node process, high throughput is achieved by doing asyncronous I/O, queueing callbacks to be executed upon completion.
  • I/O: Not usually what JavaScript is used for, but this covers the fact that Node has APIs that treat the file system and TCP and HTTP as first class citizens.
  • V8: The JavaScript is executed by the V8 JavaScript Engine that Google in Aarhus built for Chrome.

As an example, there’s the ubiquitous code sample that you’ll see everywhere – opening a HTTP server in Node:

As you can see, Node has a nice and thin API for working with HTTP, and as I envy Rubyists of having Rack and Sinatra, and as I am interested in how web frameworks work in general, this code sample has continued to spark my interest.

Therefore, in order to push myself through learning more about it, I have decided to see if I can write a couple of blog posts on Node.js. I will try to cover the necessary topics to develop a simple web app, and I expect to come across more or less of the following:

  • Acquiring Node.js and running a “Hello world” script. Can’t do anything without having done this.
  • Basic Node stuff, like how to structure code into files/modules/whatever and whatnot.
  • Bringing in external, possibly native libraries.
  • Building a web app, possibly with Express – a simple web framework for Node.
  • Persisting some data, probably using node-mongodb – a MongoDB driver for Node.
  • Unit testing my app – probably with the built-in assert API.
  • Hosting my app – probably with Nginx as a router and load balancer.

Wow! – that was a lot of words and almost no code… I promise that my next posts on Node will have more code in them.