Race conditions in Javascript

Given all hype about javascript recently, it can come as a shock to realise that modern browsers still execute javascript on a single thread. For developers used to multi-threaded runtimes such as .NET and the JVM this can lead to unfamiliar results.

For this example we will consider the HTML 5 Websockets API.

Note first of all that there is no connect() method with websockets, the constructor itself initiates the connection.

Let us consider the following code. By adding a big loop we’ve essentially added a time delay between creating the websocket and wiring up the onopen event handler. Now the million dollar question: does the event handler always get triggered when a connection is made, or does the delay mean that the onopen handler is sometimes not wired up by the time the websocket has connected?

var wsUri, testWebSocket;
wsUri = "ws://localhost:8080/mywebsocket";
testWebSocket = function(){
  var connection, i$, i;
  connection = new WebSocket(wsUri);
  for (i$ = 0; i$ <= 1000000000; ++i$) {
    i = i$;
    /* simulate a delay */
  }
  console.log("wiring up event handler");
  connection.onopen = function(){
    console.log("opened");
  };
};
testWebSocket();

In the JVM/.NET world we would expect this to cause a race condition. If the websocket connects before our event handler has been wired up the handler would never get triggered. In fact though, this works fine in javascript and there is no race condition. Since the execution model is single-threaded the websocket doesn’t actually attempt to connect until nothing else is executing. Very much like a Dispatcher in WPF/Silverlight.

Of course you do still have to be very careful when using timers… this for example does indeed cause a race condition:

var wsUri, testWebSocket;
wsUri = "ws://localhost:8080/mywebsocket";
testWebSocket = function(){
  var connection, wireUp;
  connection = new WebSocket(wsUri);
  wireUp = function(){
    console.log("wiring up event handler");
    connection.onopen = function(){
      console.log("opened");
    };
  };
  window.setTimeout(wireUp, 5000);
};
testWebSocket();

Remember folks: Concurrency and asynchrony are not the same thing!

Personally I think this API design is a bit short-sighted… it’s going to make it very difficult to add real concurrency to javascript runtimes and browsers in the future without revamping the APIs and breaking existing apps.

See also:
http://ejohn.org/blog/how-javascript-timers-work/

Hosting Websharper/ASP.NET apps on Linux with Mono + nginx

F# + cheaper hosting = winning

One of the arguments often levelled against .NET web frameworks is that Windows hosting options are expensive compared to their Linux counterparts. Pricing aside, many people, myself included, also prefer the simplicity and flexibility of being able to quickly SSH into a box for administration rather than faffing around with remote desktop.

In the past Mono had something of a reputation for poor performance due to the primitive garbage collector. Mono 3.0 however ships with a new garbage collector called sgen which is much better. The Xamarin guys are doing a great job and it now seems ready for primetime.

Having recently been experimenting with Websharper, and being a big proponent of F#, I was keen to see if I could have the best of both worlds. Would it be possible, I wondered, to use Mono to host a Websharper app on Linux?

My initial attempts at installing Mono and F# proved somewhat fruitless because the mainstream Debian packages are hopelessly out of date. Fortunately some bright spark has uploaded some more recent ones onto launchpad which makes the process fairly straightforward.

Once that was done the rest was easy enough. I just copied a compiled Websharper site across from my Windows machine, fired up fastcgi-mono4, configured nginx to proxy the requests and hey presto, the page popped up! The same process should also work just fine for ASP.NET sites.

One small caveat: I did run into a websharper bug that was causing links to render incorrectly but that wasn’t too difficult to resolve.

Being a fan of automation (i.e incredibly lazy) I also created some vagrant provisioning scripts. This means you can be up and running with Ubuntu 13.04 64-bit Server hosting a Websharper site in minutes!

image

What the scripts do

  1. Download and install Mono 3.0.10 and F# 3.0
  2. Adds init.d script for fastcgi-mono4 (/etc/init.d/monoserve) – this also configures mono to use the new sgen garbage collector.
  3. Sets up nginx to point to fastcgi4-mono.
  4. Hosts the sample Websharper app in which is housed in /vagrant/www (this folder is shared between the guest VM and the host machine).

How to get started

  1. Install Virtualbox.
  2. Install Vagrant.
  3. Clone the provisioning scripts from my bitbucket account:
    git clone https://perfectshuffle@bitbucket.org/perfectshuffle/vagrant_raring_mono.git mono
  4. Launch the vagrant box:
    cd mono
    vagrant up
    
  5. Once everything has finished configuring it dumps out the boxes IP addresses to the console. Just point your browser to the eth1 IP address and you should see the site running!
  6. Replace the sample files in the
    /vagrant/www

    folder with your own website.

  7. Profit!

I’ve also tried running the scripts on some cloud hosting rather than inside vagrant and they work great.

Installing Monodevelop 3 with F# support on Ubuntu

After much experimentation and digging around on google groups (special thanks to Ibrahim Hadad) I have finally managed to get Monodevelop 3 and F# working together nicely on Ubuntu. These were the steps I took. Your mileage may vary. :)

(Update: Knocte has suggested a couple of modifications to simplify the process. These are now reflected below.)

1) sudo apt-get install mono-complete libgdiplus git autoconf libtool

2) Install monodevelop using the script from John Ruiz’ blog:
http://blog.johnruiz.com/2012/05/installing-monodevelop-3-on-ubuntu.html

3) Get F# source and compile:
git clone git://github.com/fsharp/fsharp
cd fsharp/
./autogen.sh --prefix=/usr
make
sudo make install

4) Run monodevelop. Go to tools, add-in manager, gallery. Install F# language binding.

5) Enjoy!

Monodevelop 3 with F# bindings

Winning!

Debugging Silverlight applications with WinDbg

To use WinDbg to examine a dump…

1)      Make sure that the dump file is 32bit if it was running under a 32bit Silverlight runtime. Process Explorer creates 64 bit dumps on 64bit machines even for 32 bit applications. These will not work in WinDbg. You can use the Sysinternals procdump tool to create a 32 bit dump: procdump –ma sllauncher.exe mydump.dmp

2)      Make sure you are using the 32 bit version of WinDbg (for 32 bit dumps).

3)      Configure symbols in windbg: .sympath SRV*c:\symbolcache*http://msdl.microsoft.com/download/symbols

4)      Load the dump file in WinDbg (File, Open crash dump)

5)      Load SOS and the CoreCLR for Silverlight. The .loadby command seems to be broken so you’ll have to use .load and enter the complete paths:


.load C:\Program Files (x86)\Microsoft Silverlight\5.1.10411.0\sos.dll
.load C:\Program Files (x86)\Microsoft Silverlight\5.1.10411.0\coreclr.dll

If you’re using the 64 bit Silverlight runtime I believe you just need to use the 64bit WinDbg and load the dlls from C:\Program Files\Microsoft Silverlight\5.1.10411.0 instead.

You should be ready to go, for example:

0:000> !clrstack
OS Thread Id: 0x45dc (0)
Child SP IP Call Site
0014f3c0 03aa025f SilverlightApplication2.MainPage..ctor()
0014f3cc 03aa0215 SilverlightApplication2.App.Application_Startup(System.Object, System.Windows.StartupEventArgs)
0014f3e4 7b316fa3 MS.Internal.CoreInvokeHandler.InvokeEventHandler(UInt32, System.Delegate, System.Object, System.Object)
0014f410 7b2f5239 MS.Internal.JoltHelper.FireEvent(IntPtr, IntPtr, Int32, Int32, System.String, UInt32)
0014f460 7b390969 DomainNeutralILStubClass.IL_STUB_ReversePInvoke(Int32, Int32, Int32, Int32, IntPtr, Int32)
0014f510 02e017a7 [ContextTransitionFrame: 0014f510]

Sometimes, for example if your Silverlight application uses managed .NET COM components, WinDbg will try to load the wrong CLR debugging module. The quote from the deep dark depths of the WinDBG help file:

“To debug a managed application, the debugger must load a data access component (DAC) that corresponds to the CLR that the application has loaded. However, in some cases, the application loads more than one CLR. In that case, you can use the I parameter to specify which DAC the debugger should load.”

In this case the following two commands should sort things out:


.cordll -u
.cordll -I coreclr -lp "C:\Program Files (x86)\Microsoft Silverlight\5.1.10411.0"

This article also may also be useful:

http://www.codeproject.com/Articles/331050/Assembly-Helps-Debug-NET-Applications

Derivatives of a polynomial in F#

Just because I was bored…

type Term = {Coefficient: int; Power: int}
type Term = {Coefficient: int; Power: int}
type Polynomial = list<Term>

let derivative polynomial =
    polynomial |> List.map (fun term -> {Coefficient = term.Coefficient * term.Power; Power = term.Power - 1}) |> List.filter (fun x -> x.Power >= 0)

let prettyPrint polynomial =
    let sortedTerms = polynomial |> List.sortBy (fun term -> -term.Power)

    let rec printTerms terms =
        match terms with
        | [] -> ""
        | [term] ->
            match term.Power with
            | 0 -> sprintf "%d" term.Coefficient
            | 1 -> sprintf "%dx" term.Coefficient
            | n -> sprintf "%dx^%d" term.Coefficient term.Power                           
        | h::t -> printTerms [h] + " + " + printTerms t

    printTerms sortedTerms

let sample = [{Coefficient=3; Power=2};{Coefficient=5; Power=1};{Coefficient=4;Power=0}]
let derived = sample |> derivative

printfn "Polynomial:\t%s" <| prettyPrint sample
printfn "Derivative:\t%s" <| prettyPrint derived

 

Town Crier 1.1 now available on NuGet

Town Crier can now be downloaded from NuGet :)

There is now also some built in markdown support (thanks to friism). This provides a convenient way to send HTML emails where possible but with a human readable plaintext alternative whilst only writing one template:

            var factory = new MergedEmailFactory(new TemplateParser());

            var tokenValues = new Dictionary<string, string>
                                  {
                                      {"name", "Joe"},
                                      {"userid", "123"}
                                  };

            MailMessage message = factory
                .WithTokenValues(tokenValues)
                .WithSubject("Test Subject")
                .WithMarkdownBodyFromFile(@"templates\sample-markdown.txt")
                .Create();

To install Town Crier into your project from the Visual Studio Package Console:
install-package towncrier

Temporary file helper class

Occasionally it’s necessary to output data into a temporary file, for example in order to pass data to an external program. I threw together this little helper class to help out in such situations.

public class TemporaryFile : IDisposable
{
    public string FilePath { get; protected set; }

    public TemporaryFile()
    {
        FilePath= Path.GetTempFileName();
    }

    public void Dispose()
    {
        if (File.Exists(FilePath))
            File.Delete(FilePath);
    }
}

Use it like this:

using (var tempInputFile = new TemporaryFile())
{
   // Do stuff with tempInputFile.FilePath here...
}

// Dispose will be called at the end of the using statement and so the file will be deleted.