Node.js and Express – Strange Http Status Codes

In a Nutshell

Sending a response in Express with a call like res.send(status, body) will send body as the status code if it is numeric – ignoring status. This is due to a fudge for backwards compatibility.

The Details

As part of a project I’m working on, I’m writing a service using node.js and Express. This service exposes some entities in a MongoDB database through a REST API. Typically I hit this API through client-side Javascript, but in some places I want to hit the same API from some C# code – and I don’t want to have to create classes for everything. I’ve got a funky library for this which I’ll be publishing soon, but it helped me find a problem.

Testing the C# code showed me something that was a bit odd – GETs and POSTSs were working fine, but PUTs and DELETEs were showing an HTTP Status code of ’1′ (which isn’t a valid code). Here’s the what I was seeing:


Checking the node server showed the same thing – DELETEs were returning status 1.


The server code is very lightweight so it’s quick to see what’s going on:

exports.deleteUser = function(request, response) {

	//	Get the id.
    var id = request.params.id;

    //	Log the user id.
    console.log('Deleting user: ' + id);

    //	Get the users collection, delete the object.
    db.collection(collectionName, function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error deleting user: ' + err);
                response.send(400, {'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) deleted');

The function is called successfully, so we hit ‘response.send’. This looks like the problem – the result object is simply the number one, checking the Express Api Documentation for send shows some examples like this:

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('some html');
res.send(404, 'Sorry, we cannot find that!');
res.send(500, { error: 'something blew up' });

So just like the final example, we’re sending the code 1, which is not valid. What surprised me was what happened when I changed the send call to the below:

response.send(200, result)

I was still getting the code 1 returned. It turns out that this is a kind of undocumented oddity of Express – if you pass a numeric code and the second argument is also numeric it sends the second argument as the status.

In response.js of Express we find:

res.send = function(body){
  var req = this.req;
  var head = 'HEAD' == req.method;
  var len;

  // allow status / body
  if (2 == arguments.length) {
    // res.send(body, status) backwards compat
    if ('number' != typeof body && 'number' == typeof arguments[1]) {
      this.statusCode = arguments[1];
    } else {
      this.statusCode = body;
      body = arguments[1];

So it seems the Express used to support a call like res.send({body}, 200) – and checks for a numeric second argument for backwards compatibility.

The workaround – don’t send numbers as any part of the response, unless it’s most definitely the status code – if you want to return the number of documents deleted, format it as json first, otherwise Express will get confused and mess with your status codes.


Recursive read lock acquisitions not allowed in this mode

If you are using the following combination of tools:

  • Visual Studio 2012
  • Visual Studio Tools for Git
  • Nuget

Then you may encounter some weird problems when trying to update Nuget packages. For me, updates regularly fail with:

Recursive read lock acquisitions not allowed in this mode.

I’m lost on the root cause of this, but it does seem that the project I’m working on has files set to read-only by something regularly, perhaps Visual Studio is trying to make Git more TFS-y by locking things all over the place. Whatever the cause, I’ve found that the following usually helps:

  1. Don’t use Update-Package – use Install-Package instead.
  2. Make sure the solution has all of its files read+write, not read only.
  3. Open the team explorer and go to ‘Commits’ – making sure that the Git tools have loaded various components.

This combination of tricks seems to solve the problem. If anyone has any other ideas or suggestions, just comment.


Context Menu for Trello

I’m on holiday at the moment, back in sunny England. Holiday may not be the right term really, I’m mostly working through charity stuff (for my charity Namaste – Children’s Homes Nepal) and company administration. I’m also starting working on a big new project, which is pretty exciting.

Anyway, I got a nice message from a fellow coder George Hahn who has put together a pretty cool project that lets you send files directly to Trello as an attachment to a card, or even as a new card. Here’s a screenshot of it in action:


It’s a nice project, you can check it out on GitHub:

What’s also cool about this project is that it’s the first project that someone’s told me about that uses SharpShell. Many people have got in touch with me about SharpShell (in fact, the SharpShell Context Menus article on the CodeProject is very popular), but so far this is the first real-world project where the writer got in touch after the project is completed.

Thanks George, I look forward to seeing what else you’re working on!


Visual Studio Deployment Projects – an Update

I received the following message in my inbox the other day:

‘[Uservoice declined - Bring back the basic setup and deployment project type Visual Studio Installer.’

Some readers may recall my post on the frustrating removal of the simple deployment project from Visual Studio. Unfortunately, with this message, they have closed the Uservoice request to bring back the basic setup projects (the request is at http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3041773-bring-back-the-basic-setup-and-deployment-project-).

It’s rare for me to blog or comment on products like visual studio, to complain or evangelise about features and so on, but in this case as the previous post had received some interest I thought I’d write an update.

It’s extremely frustrating for developers to have features like this removed from our toolkit. Is it fair to call it our toolkit? Perhaps not, but this is an extremely expensive product, we pay a lot of money for it and it’s a product that evolves in a sense based on what we do. As we start developing more and more web based applications, the product evolves in that area. As we develop less in other areas, features are no longer invested in. This is all fair enough.

However, it is difficult to keep your customers happy when a simple and extremely useful feature is removed, and replaced with essentially a cross sell link to another product. In fact, let’s look at this and really state what the problem is.

We’ve paid a hell of a lot of money for a feature rich toolkit, that can cope with diverse development requirements. An element we’ve used for years has been removed without explanation and replaced with an advert for an expensive alternative.

I doubt very much the deployment project was a difficult or expensive one to maintain. In fact, its simplicity is one of the reasons it was popular. So most of us are thinking that a working, heavily used feature has been deliberately removed. Why? To sell another product. This sort of mercenary behaviour is not appealing to us as customers.

I would end this post by saying that us computer nerds are fickle and highly strung about things like this. If we feel we’re getting screwed over, we’re likely to move to alternative products.

This indifference to customer opinion is rather worrying. (This was the second highest voted item in Visual Studio Uservoice). It also seems to not be isolated. Many customers seem deeply disenchanted with decisions taken in Windows 8, these concerns have been raised and roundly ignored.

I’m not going to go on any more about this, the comments and posts have been made, the requests ignored.

But I will say that if you have a online system to collect user feedback and requests for features for a product as expensive as Visual Studio, a request in the top three is for you to bring back something you’ve removed to get a kickback from Flexera, and you ignore the request, then don’t bother asking for feedback, because it feels like a middle finger to your customers.


Web Deploy – Could not connect to the remote computer

Using Web Deploy is a nice and easy way to publish websites and web applications with Visual Studio. However, I found one thing that can be a bit of a blocker, that didn’t seem to be explained anywhere very well.

Let’s imagine I administer a webserver that hosts the site www.something.com. I’ve installed the Remote Management tools for IIS and the Web Deploy stuff, and have also configured the site to allow Web Deploy. I now try and deploy using Visual Studio, with the settings below:


Validating the connection fails with the message:

‘Could not connect to the remote computer “somesite.com”. On the remote computer, make sure that Web Deploy is installed and that the required process (“Web Management Process”) is started. [more stuff] ERROR_DESTINATION_NOT_REACHABLE.

So what do we try first?

  • Check the Web Deploy feature is installed on the server, it is.
  • Check the Web Management Process is running, it is.
  • Check port 8172 is open, it is.
  • Read up on similar issues, they say the same as the above.

I spent quite some time pulling my hair out over this – is it because I’m on a different domain? Is there some other port that needs to be open too?

Now the error says ‘could not connect to the remote computer “somesite.com”‘ – so maybe the issue is here. I try the IP address, www.somesite.com and the IP address with the port 8172 specified – no joy.

It turns out, that even though it says ‘Server’ in the first box (leading us to think it would be the address of a server we need), it’s actually the server with http specified. Change the Server from somesite.com to http://www.somesite.com and it works a charm.

Not the most exciting post ever, but hopefully this’ll save someone else wasting the same amount of time that I did.


Build Buttons for Facebook, Twitter, LinkedIn, GitHub and More!

Recently I’ve been working on a small project called Build Buttons. Build Buttons is a website that let’s you quickly create buttons for sharing and promoting content. You can use Build Buttons to create Facebook ‘Like’ or ‘Follow’ buttons, LinkedIn ‘Share’ buttons, Google +1 buttons, GitHub Star, Fork and Follow buttons and more. Here’s how it works.

First, go to www.buildbuttons.com:

Build Buttons

Now choose the kind of buttons you want, in this example we’ll select ‘Social Media’ from the top menu:

Social Media Buttons

On each category page, there’s a list of the different types of buttons that can be built. Social Media includes the ‘Share’ button set. Click ‘Build It!’:

Social Media Button Settings

Now just fill in the details to customise your buttons, enter a URL and select the sort of buttons you want to include. When you’re ready to see how your buttons look, choose ‘Build it!’:

Build Buttons Results

You get a working preview of how your buttons look, and a text box that includes the HTML you need to drop into your webpage or blog, easy!

Build Buttons has quite a few different types of buttons you can create. You can:

  • Create a set of social media buttons
  • Create Facebook Like and Follow buttons
  • Create Google +1 buttons
  • Create LinkedIn Share buttons
  • Create GitHub Star, Follow and Fork buttons

WPF and Visual Studio Addins

If at all possible nowadays, I write all my Windows UI code in WPF, it’s just quicker and easier than WinForms. Recently however, I came across a situation that you should just avoid.

If you’re developing addins for multiple versions of Visual Studio – don’t use WPF for the Tools > Options windows. It’s just noit going to place nice out of the box. This is because there’s a lot of property page Win32 stuff going on in the host window that makes it hard to route messages properly – keyboard entry won’t work correctly, tab order will be messed up and more, it’s just not worth the pain.

If you’re developing addins for later versions of Visual Studio, you can actually use the VSPackage functionality to build options pages with WPF with ease, just check UIElementDialogPage. In fact, read the article here:

Creating Options Pages by using MPF 

Final thoughts on this – if you want the functionality above in VS2010, you can get it (as long as you use MPF) by checking this page:

Unable to access WPF User Control in Options Dialog

You’ll see that about halfway down, Ryan Moulden has posted some code from Microsoft for the UIElementDialogPage, you can use that you get the functionality in VS2010.

Any other versions, or for a addin installed by an MSI, it’s probably best to stick with WinForms.



Introducing Sil

For the last few weeks I’ve been trying to tie up a project I’ve been working on for a while called Sil. With lots of other things on my plate at the moment I haven’t had much of a chance to work on it, but finally tonight I’m able to release the first version.

Sil is short for ‘See IL’, or ‘See Intermediate Language’. It’s primarily an addin for Visual Studio (2010 and 2012) that lets you right click on some code and disassemble it.

I think it can be very useful sometimes to see what’s going on in the code your writing, and searching for ildasm (which Sil actually uses itself) slows me down – I want to disassembly right from Visual Studio, and I want the results side-by-side with my original code.

Here’s a screenshot of how the code editor looks after I’ve just right clicked on a method and chosen ‘Disassemble’:


It’s not too shabby – syntax highlighting and a few options to see more detail. As I’ve disassembled a method, from the bottom of the window I can also expand the scope to the parent class or the whole assembly.

Under the hood, Sil uses ildasm to disassemble the entire assembly, then parses it into a set of ‘DisassembledEntity’ objects (which can be DisassembedClass, DisassembedEnumeration and so on). A little bit of WPF for the UI and the great AvalonEdit control and that’s all there is too it. As you might expect, the bulk of the complexity is in the code to parse the disassembly into logical entities.

You can get the Sil installer from the Sil page on this site. You can also head to the CodeProject and take a look at the article I’ve just written ‘See the Intermediate Language for C# Code’.

I think with this project, rather than using CodePlex (as I’ve done for Apex, SharpGL and some others) I’m going to go for GitHub to mix things up a bit. Watch this space for news on the source code going online – if you’re keen for a look, it’s also in the CodeProject article.


Creating Addins – ‘An error occurred, and the wizard could not generate the project.’

When doing a little bit of work on a solution that contains a Visual Studio Addin the other day, I noticed that there’s a little bit of an issue with Visual Studio. If you create an addin project and you get the message:

An error occurred, and the wizard could not generate the project. Verify that the programming language is properly installed.

Then double check where you are creating your addin. If it is in a child folder of the solution, then this error can occur. The solution – add the addin project to the solution root. Then if you need to, you can move it afterwards.

This issue occurs in Visual Studio 2012, but a bit of googling suggests that it may also be an issue in 2010.


Getting Paths for Files in NUnit Tests

When using NUnit, sometimes you will want to access files in the test project. These might be xml files with data, assembly references or whatever. Now typically, NUnit will actually copy the files it thinks it needs into a temporary location. This causes the problem that you can then do things like use a relative path to get files in the project. You can use manifest resource streams but sometimes this just isn’t suitable.

To get the path of the root of your test project, you can use the snippet below. Make sure you call it in a unit test fixture that’s actually in your test project, not from a class referenced in another project!

This class, ‘TestHelper’ can be included in a Unit Test project to let you quickly get the path to the test project.

public static class TestHelper
    public static string GetTestsPath()
        return Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace(@"file:\", string.Empty);