23 March, 2012

Remote debug your iisnode hosted node.js app

I recently came across iisnode’s built in support for the excellent node-inspector package. My iisnode host of choice being AppHarbor, I proceeded to set up a repo and make sure it all works there.

The good news is… It does!

Even better is that this is built straight into iisnode, you don’t need to touch your app code to get it working, you don’t even need to install the node-inspector package. It is all bundled in with iisnode.

You simply need to make a single change to your web.config rewrite rules so that the urls to launch the debugger are not treated as regular requests and sent through to you app.

So the way you get to the debug console is to hit up /app.js/debug where app.js is the entry point for your app. The rewrite rules here simply allow that url through as it is, everything else gets handed off to the app as normal.

So push up the modified web.config, hit the URL and this nice console pops up.

Debugger

Clicking into Scripts presents you with a list of all the running JavaScript files on the server. Including those built into node itself. You can pick the file you want to debug, and set a break point by clicking on the line numbers.

SetBreakpoints

With the breakpoint set, now you need to fire a hit off to the website that will run over the breakpoint.

Reload Page

This hit will sit there waiting for the server to respond, switch back to your debugger page and the breakpoint has been reached and is waiting for you to take some action.

BreakpointReached

As you can see you have full variable inspection, the options to step through line by line or continue running, variable watch and all the sorts of things you would expect. You even have mouse hover variable inspection like in Visual Studio.

MouseOver

When you are done debugging, you should call the /app.js/debug/?kill url which will shut down the debugger process.

KillProcess

Now I wouldn’t go doing this on production, and you certainly do not want to leave that route in place, I would set the debuggingEnabled property to false as well in production but for development or staging servers where you need to follow something through, this is simply awesome.

13 March, 2012

Custom Domain Testing

I finally got around to purchasing a domain for this blog today (csainty.com) and so this is just a quick test post so I can make sure feeds and the like have all been repointed.

Nothing to see here.

10 March, 2012

WinJS - Classes

In my last two posts on JavaScript for Windows 8 I looked at scope and namespaces. I pointed out that namespaces could be used to create “static” classes. I hasten to add they can be used for more, don’t make a hard link in your brain between namespaces and static classes.

So what about regular classes. There are a couple of ways to define a class in JavaScript, a simple way is to return a hash from a factory method.

We can shift name into a private scope by declaring a new variable inside our constructor which is captured by the resulting object.

However, for complex classes you intend to create a lot of, this method is generally not the suggested. Each instance is redefining the functions rather than simply pointing to an existing implementation in memory. This is where prototype inheritance comes in.

With this setup you start with your constructor, you then extend it’s prototype. Finally instead of calling the constructor directly, you call it with the new keyword, which creates you a new instance.

Note the capital P in Person, this is a convention to say this function is a class definition, so call it with new.

But, we have lost the private scoping on the name property. To get it back, we need to define the property inside the constructor like we did above, but then expose it with a getter method so that the methods on the prototypes can get at it.

It’s starting to get ugly isn’t it. Getting our reference to Person back out is quite awkward. The getter isn't much fun either.

So what does WinJS bring to the table?

There is a WinJS.Class namespace that contains a define method. It can be used to wrap up a big ugly class definition like that above into a simple method call that returns a class definition you can new up. It supports passing in your constructor, your instance methods/properties and your static methods/properties.

Much cleaner. Our class definition is sitting in the MyApp namespace ready to be created via new MyApp.Person('') and for good measure there is a static factory method MyApp.Person.createPerson('').

But what about private variables? You can use the same technique as my example above with the getter. If you had a lot of them you might wrap them all onto a single private hash that only needed a single getter. What you might see a lot of people do is simply prefix them with an underscore and hope others follow the convention that properties starting with an underscore are not to be touched.

Private scope aside, by combining WinJS.Namespace and WinJS.Class you have a really nice set of helpers to wrap up the task of correctly managing global scope and efficient class definitions. Neither is performing any magic, their source code is there for you to explore, they just get rid of some of the confusing boilerplate.

09 March, 2012

Node.js Background Workers on AppHarbor

Today AppHarbor announced beta support for Background Workers, I have been eagerly awaiting this announcement as it is something I need all the time when hosting sites.

Background Workers are simply .exe files that the server now knows to look for and run if you have a worker assigned to background tasks in your subscription. It should be noted that if you are using the free single worker plan, then you can not run both a web and background worker. You do have the option to run a web OR a background worker though. So you can still try these out on your free account.
It should also be noted that trying to run two free accounts (one for web, one for background) that are servicing the same site is against the terms of service.

As people who follow my blog probably know, I am right into Node at the moment. So straight away I set about getting a background worker up that can run node for me instead of C#.

It was rather easy in the end, a simple wrapper that launches a node.exe process. You can grab the code from https://github.com/csainty/NodeWorker.
You don’t even need Visual Studio installed or Windows, you push the source code to AppHarbor and they build it for you!

The demo app I used for testing is also available, it simply logs entries off to logentries (a free, one click install, addon from AppHarbor) so I can see if it is working. That code is at https://github.com/csainty/NodeWorkerDemo.

So how does it work?

First you need to clone down the project from GitHub.

Then you need to add your node.js code into the app folder. The assumed entry point is app/index.js, but you can quickly point it elsewhere and add extra parameters to the node process if needed.
See https://github.com/csainty/NodeWorkerDemo/blob/master/NodeWorkerRunner/Program.cs#L19

Finally make sure your node_modules folder is in the commit (AppHarbor does not run npm for you yet) and that all the files are being copied into the build folder and you are done.
If you are unsure, check the build output on AppHarbor for lines like the following

Now push the whole project up to AppHarbor where it will be built and start running straight away.

The lifetime of a background worker is controlled by the exit code from your application. The wrapper will pass the exit code from your node process back out to AppHarbor, putting node in control. There are currently two supported values

  • Exit Code: 0 – Stop running the worker until the next deploy is performed
  • Anything else – Start the worker again immediately

If you take a look here you will see I chose to return 0 if there was a problem launching the node process. Meaning it will stop attempting to run your process. If this is not what you want, then you should change this value to be non-zero.

Finally similar to iisnode, all your <appSettings /> are added as environment variables when launching the node process which makes them available on process.env. Just like if you are hosting a node site on AppHarbor.

08 March, 2012

WinJS - Namespaces

In my last post I explained a little about scope in JavaScript and why you should (and the default templates do) wrap each of your files in a self executing function.

One note about my code snippets. For simplicity I will be concatenating what would in a real application be multiple .js files into a single code snippet. I’ll use comments to show you where the files break.

So let’s imagine you are creating a helper function to do something really useful, like add two numbers together.

We have defined this function in the global scope, let’s do the right thing and wrap a function scope around each file.

Now the two scopes can’t see each other or interact with each other. So how can we make our add function available to the rest of our application without just throwing it in the global scope.

I present to you Namespaces.

Namespaces are not a part of JavaScript, they are a helper library that Microsoft has provided in WinJS to better handle the problem of scope in JavaScript. In fact if you dig into the references on your project, you can actually find all the code for Namespaces in the base.js.

Basically a namespace is an object that sits in the global scope. They can be nested and since you should be naming them much more uniquely than you would a regular variable the chances of conflicting with another library are slim.

So let’s expose our add function through a namespace.

The WinJS.Namespace object is itself a namespace, defined in the base.js I mentioned above, which is why we are able to just call off to it. Once we define our own namespace we can then call it in any later code in the same way.

Another interesting feature of Namespaces is that they are composed, so if you define the same Namespace twice instead of overwriting it you add to it.

Suppose we now want to add a subtract method, but we want it to be in a separate file from our add method. A better example, which we are using at Code52, suppose you have two implementations for your data access layer. You want them in the same namespace but in separate physical files.

This is super useful and kudos to Microsoft for making it work that way.

One last note on namespaces. Remember that the context in which you are defining your Namespace is local to itself. JavaScript captures that scope when you define a function though. So you can define functions and variables that are only visible to the functions you are exposing on your namespace.

To demonstrate this I will keep a running total of all the sum operations, and add a new function to return that total.

The runningTotal variable and the adjustTotal method are both local to the helpers.js file and inaccessible outside of it. However, the add and total functions that we are exposing through the namespace have captured and retained the scope in which they were define and therefore still have access.

So that is a quick introduction to namespaces. I have only shown exposing functions, but variables can be exposed as well. What I have shown here is most similar to a static class in C#.

Next time I will look at WinJS.Class and how you can use it to create class definitions.

Windows 8, WinRT and WinJS - Scope

This week at Code52 we are taking on our first Windows 8 app. Just to make it interesting we are doing it using the HTML / JS stack instead of C# / XAML.

Before getting too far into WinJS (which is the general term I am going to use for referring to WinRT apps written in JS until someone tells me otherwise) it is a good idea to get a basic understanding of JavaScript as a language. It is a lot more in-depth than jQuery and the DOM would lead you to believe.

The first thing you are going to confronted with upon creating a new project and opening on of the .js files is this structure.

This is a self or immediately executing function. It defines a function, then execute it. Nonsense! I hear you scream.

The reason for this structure is scope. JavaScript’s scope boundary is at the function level. It is not at the file level, or at the block level (like in C#). For example this code works.

But if we define our variable in a self executing function. Then it does not.

Functions scopes are stacked, and the outer most layer of that stack is called the global scope. So consider a large application with hundreds of js files. If each of these files did not use the self executing function trick to get a local scope, then they would all share the global scope. Now consider how likely it is that two files would share a variable name and cause difficult to track down bugs.

It is interesting to note that Node actually wraps your modules in a function scope for you, so you get this safety out of the box.

I’ll try keep these posts short and to a single topic, so that will do it for this one. Next I am going to take a look at the WinJS.Namespace helper and show you how to use it to safely get objects back out of your function scope and into accessible globally.