Running ActiveMQ as non-root

Running ActiveMQ as non-root with a handy script and a small tweak in conf/log4j.properties: replace log4j.appender.logfile.file=${activemq.base}/data/activemq.log with log4j.appender.logfile.file=${activemq.data}/activemq.log to prevent ActiveMQ from putting the log in the installation folder.

Though I suppose you could also create a new broker instance.

What is Node.js?

It took me some time to get my head around the peculiarities of Node.js so here’s my take on explaining it.

What is Node?

Node(.js) is a program that allows you to run programs written in JavaScript.

But I heard it is a Web Server?

Well a Web Server is a program; you can write one in JavaScript with Node.

Why is it so popular?

Well web developers like to create tools in JavaScript because they are using that language already for programming the browser. For that reason it is also a compelling web server. Some frameworks even allow you to run the same code on the server and the browser. But Node has another advantage.

How come Node beats established web servers?

Node uses a novel approach at dealing with concurrency, that is all the requests and responses a web server needs to process.

So how does Node deal with concurrency?

Well it’s like comparing a large crossing to a roundabout. If a crossing is complicated and busy it needs traffic lights to start and stop the flows that would otherwise collide. With a roundabout however, all flows merge into a large loop and traffic ramps off at the various exits.

Another analogy is a restaurant serving several customers. To deal with all the cooking involved you could:

  • Have multiple kitchens. This is like multiple processes.
  • Have several cooks working in the same kitchen. This is like multithreading.
  • Split the work into small steps that complete quickly. When there is waiting involved (for the oven to finish or water to boil) move on to the next task and continue when the waiting is over.

Traditional web servers use multiple processes and multithreading. The third option is obvious for cooking but not for web servers.

The main downside of each method is:

  • Multiple processes requires a lot of memory and switching and communication between processes requires considerable CPU time.
  • Multithreading is hard when resources are shared. Also each thread requires memory and switching requires CPU time.
  • Splitting programs into small steps requires a language to split code into small parts while still being able to see the flow of tasks.

To be fair Node is not the first web server doing things this way, but it sure made it popular.

Why JavaScript?

Well, besides being able to use the same language in the browser JavaScript has two advantages:

  • It has lambdas, useful for splitting programs into small parts.
  • It has nothing else for handling concurrency, so there’s less confusion.

“Insufficient Storage” on Samsung Galaxy S II (I-9100)

My wife’s phone (Samsung Galaxy S2 I-9100, upgraded to Android 4.1.2) recently refused to update any installed apps with the error ‘Insufficient Storage’, even though the phone clearly had enough internal storage left to install at least some apps.

After surfing the web I found 2 solutions that worked:

  1. In the dialer type *#9900#. You get some techie menu, then choose the second menu option Delete dumpstate/logcat.
  2. Shut down the phone then start it up by holding the Volumne Up, Power and Home buttons. You boot into the recovery menu. Then choose the second last option Wipe the cache partition. Then restart the phone normally.

This solved the problem, now all apps update without any problems.

Navigation Bar issues between iOS 6 and iOS 7

A major difference between iOS 6 and 7 is that in iOS 7 the navigation bar is translucent by default and stuff appears underneath it instead of being shifted down.

Normally this is fixed by making the navigation bar opaque, but this doesn’t always work. An additional solution is described here, and translated to Xamarin it is:

using MonoTouch.ObjCRuntime;

...

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    if (RespondsToSelector(new Selector("edgesForExtendedLayout")))
    {
        EdgesForExtendedLayout = UIRectEdge.None;
    }
...
}

Using XmlReader.Read() with ReadElementContentAs*()

Most samples of using an XmlReader use a Read in a while loop like this:

var value1 = 0;
var value2 = 0;
var value3 = 0;
while (reader.Read())
{
    if(reader.IsStartElement())
    {
        switch(reader.Name)
        {
            case "Element1":
                value1 = reader.ReadElementContentAsInt();
                break;
            case "Element2":
                value2 = reader.ReadElementContentAsInt();
                break;
             case "Element3":
                value3++;
                break;
         }
    }
}

However, this pattern may fail if elements are not separated by whitespace. The culprits are the ReadElementContentAs* methods. Without separating whitespace they leave the reader at the start of the next element. The Read at the top of the loop moves it past this next start element and it will be skipped completely.

This is particularly nasty because it works well with nicely formatted XML, which you’ll probably use while testing, because it has whitespace between elements. However, dense XML generated by a feeding system will trip it up.

Instead you can use something like this:

var value1 = 0;
var value2 = 0;
var value3 = 0;
while (!reader.EOF)
{
    if(reader.IsStartElement())
    {
        switch(reader.Name)
        {
            case "Element1":
                value1 = reader.ReadElementContentAsInt();
                continue;
            case "Element2":
                value2 = reader.ReadElementContentAsInt();
                continue;
            case "Element3":
                value3++;
                break;
        }
    }
    reader.Read();
}

The Read at the top of the loop is replaced by an EOF check and moved to the bottom. This allows skipping it with the continue keyword after using a ReadElementContentAs* method or anything else that leaves the reader at the start of the next element. Anything else is followed by a break to move the reader forward.

Please note the use of continue instead of break is rather subtle so a comment is probably in order.

BTW, if you want to test XML documents without having to edit terse XML files load pretty formatted XML in an XDocument and then open an XmlReader from it. Apparently this reads the XML without the whitespace nodes.

Booting an SD Card

I’m running out of USB sticks with all the Windows and Linux images I like to try out. However, I still have a bunch of SD cards left. Both my laptops have an SD card slot but unfortunately they cannot boot from it.

Recently I bought a USB connected multi-card reader and after some experimentation I succeeded in booting from an SD card inserted in the reader. Sweet!

Unfortunately the Windows 7 Download Tool created an invalid image, resulting in a boot error. It is however possible to make the SD card bootable manually. After copying all files from a Windows 7/8 ISO you can boot from it.

Linux images created with pendrivelinux worked perfectly.

I have only tried it with this USB multi-card reader, so your mileage may vary.

So now I finally have some use for those old SD cards!

Secure RESTful WCF Service with SHA-256 hashing

This is an old draft I found, perhaps it is useful if you’re trying to do SHA-256. If not, let me know, I might be able to help you out.

Azure Storage supports secure access of resources without logon. It involves hashing the query part of the URL and then signing that hash. I’ve implemented this at my workplace in the following steps:

  • Create a web project for a WCF service.
  • Update the .svc file by adding (this makes everything work without configuration, found this here):

Factory=”System.ServiceModel.Activation.WebServiceHostFactory”

  • Add the following attribute to your interface method:

[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "?p0={parameter0}&p1={parameter1}&sig={signature}")]

  • Create a method like (please note that parameter names match those specified in the WebInvoke attribute and that they are all string type):

Stream MyMethod(string parameter0, string parameter1, string signature);

  • In the implementation of MyMethod verify the signature with the following function:

bool ValidSignature(string customerID, string signature, paramsstring[] toSignArguments)
{
    var certificate = FindCertificate(customerID);
    if (certificate == null)
{
        return false;
}
    const string TERMINATOR = “\n”;
    var toSign = string.Join(TERMINATOR, toSignArguments) + TERMINATOR;
    var oldProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
    using (var newProvider = new RSACryptoServiceProvider())
{
newProvider.ImportCspBlob(oldProvider.ExportCspBlob(
false));
        return newProvider.VerifyData(Encoding.UTF8.GetBytes(toSign), “SHA256″, Convert.FromBase64String(signature));
}
}

The trick is to create a new provider instead of the default one you get when loading the key. The default is connected to the wrong library that doesn’t support SHA-256.