A Roslyn Web Script experiment

Out of frustration with the slow compile->deploy->result I look at other solutions from time to time. Recently I was hacking away with some server side javascript, which is cool. But I’m in a .Net world, coding C#. And I like to use the framework, libraries and language I’m used to.

Because many web sites are not rocket science and we like to have a very smooth code -> result loop.

This solution is probably best suited for client side heavy apps (SPA’s and such), where the server is mostly used for serving resources, data storage and security – in a very typical manner.

We like to be able to easily add a server hosted data resource, write some transformation code and check data and secturity. Without breaking any existing functionality. There’s no reason we should be forced to take down our application just to add or edit one small feature in it.

Also – there’s no reason to use scripts for the whole application. For advanced business logic, the well tested, structured and compiled way is without question better suited.

Razor (WebPages) can do much in that respect. It’s easy to write some Api (or Html) functionality with Razor scripts. “A simple Razor Api”, “A require module pattern in Razor”.

And it works really nice. Almost. But it’s rather slow, and breaking the AppPool is easy, and it is not supported. If we need a global helper function (“module”) add a file to App_Code we will need a full recompile and AppPool will restart. And even if we’re not adding files in App_Code, after a few “dynamic recompiles” (edit .cshtml) we will also get a full recompile.

But with Roslyn “compiler as a service”, we can actually execute our C# code as scripts. And we will not need to recompile anything. I found that to be a very interesting ground to build a web solution upon, and I hacked together a small Roslyn Web Script experiment. In the first version I was targeting an Umbraco site and I actually have a first version running already.

In the first version it mimics Razor (WebPages) simple behaviour with a “route per file” + automatically converting the “rest of the url” to UrlData[] parts.

I don’t cache things yet, I’m meaning to do so.

Sample script (“orders.csx”)
“poco” and “db” are modules.

// load "poco", "db"

// url : mysite.com/orders/{customer}

object run() {
        switch (Request.HttpMethod) {

        case "GET":

            var customerNumber = UrlData[0];
            return db.Fetch<Order>("SELECT * FROM orders WHERE CustomerNumber=@0", customerNumber)

        case "POST":
            return "post to database";
        default:
            return "illegal";
    }
}
// the last line of code returns some data to the response, as json:
run()

The github repo
RoslynWebScript can be found here.

Roslyn sept 2012 CTP
I found Roslyn to be very fast. The current CTP manages most C# syntax. Dynamic is still missing though.

One thought on “A Roslyn Web Script experiment