I’ve been working recently on a new project, Jello, which I intend to be an easy to use expression/rule evaluator, and has just hit a useable-though-lacking-in-features state.

Why use?

I wanted Jello to be really simple to use, and think I achieved that. Before I began writing Jello I tried a number of different approaches, including using embeddable languages such as Boo or IronPython, parser generators such as Irony, and expression evaluators such as NCalc. I found that for my needs, to evaluate simple expressions, the embeddable languages were just overkill; parser generators worked well, but I had to write a lot of boilerplate each time to specify the core of the language; and the expression evaluators didn’t offer the flexibility I wanted; and so decided to roll my own. The result is a compact, simple and easy to use and (will be) highly configurable.

Typical use cases could be:

  • Decision/underwriting rules (I’ve used this in a document generator to allow users to specify criteria to determine if a part of a document is included or not. I’ve also implemented similar behaviour in the past (before writing Jello) for scripting rules to determine whether a buyer accepts a particular lead or not)
  • Evaluating simple expressions, such as calculating the max value for a field based on some criteria
  • Essentially, any time that you need your users to be able to have a high degree of flexibility when specifying rules/calculations, Jello is your friend


Currently it has a very simple syntax consisting of basic equality/logical operators (&&, || and ==) and arithmetic (+, -, * and /), and supports basic data types: booleans, strings, dates and numbers (only decimal types to keep it simple – after all, Jello is intended for the users of your system). Date formats are not fixed allowing you to specify the format that best suits your needs – the default is to use the StandardDateParser which ships with Jello and uses the .net DateTime.TryParse(dateString, out date) method internally, but you can create a class which inherits from the IDateParser interface and parse dates however you’d like. Using the StandardDateParser you can also specify an IFormatProvider and DateTimeStyles if you’d like.

You can also use variables which take their values from a data source that is passed into the parse result when executing. Data sources are classes that inherit from a simple interface, IDataSource, which specifies only a single method: bool TryGet(string key, out object value). The only datasource currently shipped with Jello is a CompositeDataSource, which simply allows you to aggregate multiple data sources, though I intend to add a basic dictionary datasource shortly so that you won’t always have to create your own classes.


As I said before, the syntax is currently fixed, but my hope for Jello is that it will become flexible enough that it can be fit to most uses. The date parser is the first example of this to be added, since there are so many nuances with dates that I didn’t want to force users to use one specific date format, but I plan to add configurable operator overloading, functions and macros so that Jello can be bent to any will.


  • Add operator overloading / functions
  • Support user-defined datatypes
  • Add macros to allow substituting operators (ie. using ‘and’ instead of ‘&&’)
  • Extend grammar to make it more than just expression evaluation; allowing for specifying/amending variables, if/else statements, loops and return statements.

I just read an article by Sergi Mansilla, Extending JavaScript with inline unit tests, where he implements a pretty neat inline testing syntax using sweet.js, which allows writing code like this:

function square(n) {
    return n * n;
} where {
    square(2) is 4
    square(3) is 5

Obviously this isn’t really valid javascript – sweet.js is a javascript preprocessor which allows you to write macros in your code which are then rewritten as valid javascript. I liked the idea of being able to write inline tests, but wanted to be able to achieve it in pure js only, so I wrote inline, a little snippet of javascript (~20 lines) which implements this functionality. The syntax is a bit different, but I think it’s still pretty readable:

var square = function(n) {
    return n * n;
 .where(3) shouldEqual(5);

The way it works is simple. Inline adds a ‘where’ function to the prototype of Function, which returns an Inline object which records the function and the arguments and also has assertion functions (currently only shouldEqual() but it’s pretty obvious how more could be added).


– To use it with functions written like function fn() { ... } you must wrap the function declaration in brackets to avoid a syntax error: (function fn() { ... }).where(...).shouldEqual(...);
– Make sure not to call where() without following it with an assertion function as it’ll replace the original function! (ie. for the code: var fn = function() { ... }.where(...); fn will be an Inline object and not the specified function
– You can chain multiple where().shouldEqual()s on a function to run multiple tests

Inline.js is only a quick experiment, and I wouldn’t really recommend mixing tests and code, but I do think there’s something interesting about inline testing, and could see it being used for teaching or demonstration purposes. Sergi’s code definitely offers an advantage that as it’s written as a macro you can write the tests inline but strip them out for production.

It’s been a long time since I’ve written anything on this blog, which I really regret. I’ve got a lot going on in my life at the moment: I’ve got a 9 month year old daughter who takes up a lot of time, am in the process of planning to build a new home, and am currently working on a new project (QuickAnalyses) with some guys I met at the Launch 48 event in Exeter (which was a really enjoyable and worthwhile event that I had hoped to blog about but ran out of time!). On top of all of this, I’ve started working for a new company and my workload has really picked up, leaving me very little free time.

However, I don’t want this blog, or my efforts at ‘extra curricular’ projects, to die out. And for this reason, I want to put down in public some ideas that I hope to work on in the coming months. At the very least, I hope these will guilt me into making some extra free time for myself, and perhaps give me something to blog about in the process:

Inspired by this poll on Hacker News, this is the project that I’m really aching to get cracking on. Basically it would be a website that allowed people to pledge money for the completion of issues on open source projects on github that they really want resolving. I think this could be a worthwhile project and allow those who don’t necessarily have the ability to fix an issue themselves to incentivise someone who could to do it.

Update: Looks like I jumped the gun on this one, and a quick google could have saved me some trouble. Looks like someone’s beaten me to it, and to add insult to injury, used the exact same name I came up with! Guess I’m not as creative as I’d though! Looks promising though, check it out at gitbounty.io

This one would be personally useful to me at work, as we’re currently exploring new ways of managing products within the scope of a brand new company, and is basically a client-facing project management/issue tracker tool, allowing for a single place for customers to get quotes for new work, file bugs and communicate directly with developers. A bit of googling turned up Duet which is very close to what I want, but I want this to be completely free and open source, and also run on .net (rather than php which I believe Duet is built on). Also, it claims to be ‘beautiful’ but looks to me kinda 90s (especially with those nasty logos). Though not the most exciting of projects, it would be useful for me on a day-to-day basis, and would also be a chance for me to dig in to some new technologies – namely AngularJS to build a dynamic, SPA frontend, and RavenDB (which I’ve never had the opportunity to use) for the database.
I use dotless on almost all of my projects and love it, but I’m really intrigued to use Stylus – another css preprocessor that looks pretty ace. I’ve not yet used it though as there is no really nice way to use it from within a .net project (yes, there are ways but I don’t particularly like them). I also like the look of axis css, which is part of the roots project and builds upon stylus, but haven’t yet had a chance to use it.

Occasionally when using javascript you’ll find that you want to intercept a function call, usually to run some code before invoking functions belonging to a third-party codebase. Essentially, this is achieved by saving a reference to the original function and then replacing it with a new function which, at the end, calls the original. Something like:

(function () {
    var originalFunction = Object.getPrototypeOf(someObject).someFunction;
    Object.getPrototypeOf(someObject).someFunction = function () {
        // intercept code here

Likewise, interception is possible if a property has a getter or a setter:

(function() {
    var propDesc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(someObject), "someProperty"),
        originalGetter = propDesc.get,
        originalSetter = propDesc.set;

    propDesc.set = function(val) {
        // getter intercept code here
        return originalSetter.call(this, val);

    propDesc.get = function() {
        // setter intercept code here
        return originalGetter.call(this);

    Object.defineProperty(Object.getPrototypeOf(someObject), "someProperty", propDesc);

As you can see this is basically the same; the only real difference is that you need to use Object.getOwnPropertyDescriptor / Object.defineProperty rather than being able to set it directly using regular assignment. This is because var getter = someObject.someProperty will return the result of the getter function, and someObject.someProperty = "something" will invoke the setter function.

In my last post, looking at “typed” function overloading, I mentioned that I was working on a new project aiming to simplify animations in paper.js, and I’m pleased to say that today I was able to get the project to what I would consider a useable form. I’m also pleased to mention that I completely changed the approach that I was taking with the api, with the effect that it is simpler to use, and has also allowed me to do away with all the function overloading stuff! (Don’t worry, I’m not a hypocrite; I said at the beginning of the post that it was something I disagreed with in Javascript!).

Anyway, check it out over on GitHub, I’d love to hear any opinions or feedback.



paper.animate.js has been designed to integrate easily with existing paper.js code. Simply prefix a transform command withanimate(duration, updater, chain) / animate(duration, chain). This returns a proxy object, PaperAnimate.AnimationProxy, with overloads for all the transform methods found on paper.Item. To run the animations, call the update() method of the proxy from the paper.js view onFrame event handler. It’s easiest to use the PaperAnimate.Updater to make this easier and to automatically clear up any finished animations (more info below).

var shape = ...
var updater = new PaperAnimate.Updater();

function onFrame(e) { // paper.js onFrame event

// Translate
shape.translate(new Point(100, 50); // paper.js
shape.animate(1, updater).translate(new Point(100, 50)); // paper.animate.js

// Rotate
shape.rotate(90); // paper.js
shape.animate(4, updater).rotate(90); // paper.animate.js

// Chaining
shape.animate(2, updater, true) // 2 secs, chained = true
     .shear(0.1, 0.3);

// Animate Shape (paper.animate.js only)
shape.animate(2, updater).replaceShape(differentShape);

// Not using PaperAnimate.Updater
var anim = shape.animate(1).rotate(45);
function onFrame(e) {


animate(duration[, updater, chain]) or animate(duration[, chain])

  • duration (Number): Specifies, in seconds, the duration of the animation. If unspecified then defaults to 1 second
  • updater (PaperAnimate.Updater): Makes it simple to work with and update many animations
  • chain (Boolean): Allows chaining commands by returning PaperAnimate.AnimationProxy object rather than originalpaper.Item. Defaults false, in keeping with paper.js api (returning item)

Supported Transformations

paper.animate.js supports all the transformations currently implemented by paper.js:

  • scale(scale[, center])
  • scale(hor, ver[, center])
  • translate(delta)
  • rotate(angle[, center])
  • shear(point[, center])
  • shear(hor, ver[, center])
  • transform(matrix, flags)
  • fitBounds(rectangle[, fill])


The updater is simply an easy way to manage animations. Rather than having to maintain a list of all the animation proxies returned every time animate() is called, simply pass in the reference to the updater and then call update() only on that. Additionally, the updater will remove animations when they have completed

Before I start, I want to go on the record to say that I do not agree with using function overloads in javascript. Javascript doesn’t really support function overloading, and overloaded functions (at least in my experience) seem to lead to unclear code; the better solution is to pass in an object and determine behaviour from that.

That said, the other day I did have to implement function overloading, for a new project I started which aims to simplify basic animations when using paper.js. I wanted my solution to integrate nicely with existing code written for paper, so I decided to use a proxy object which intercepts the tranform function calls on an item and animates it, and for this reason my proxy object needed to implement matching method signatures.

Typically when people use function overloading in javascript, they are dealing with different numbers of arguments, but paper.js complicates things slightly as there can be ambiguities in function calls which can be resolved not by counting the number of arguments but by looking at the “types” of the arguments.

  • scale(Number:scale [, Point:center])
  • scale(Number:hor, Number:ver[, Point:center])

When calling something.scale(a,b), we cannot know which function to use without further inspecting b. I briefly googled function overloading in javascript and came up with a few solutions that dealt with overloads which had different numbers of overloads, but nothing that dealt with ambiguities such as the one above, and so I came up with this method:

function selectOverload(that, args, overloads) {
	var types = {
		Number: function(val) { return !isNaN(parseFloat(val)) && isFinite(val); },
		Point: function(val) { return val.x !== undefined && val.y !== undefined; }
	for (var o = 0; o < overloads.length; o++) {
		var overload = overloads[o],
			matches = true;
		if (args.length > overloads[o].params.length) continue;
		for (var a = 0; a < args.length; a++) {
			if (!types[overload.params[a]](args[a])) {
				matches = false;
		if (matches) { return overload.fn.apply(that, args); }

And it gets used like this:

AnimationProxy.prototype.scale = function() {
		this, arguments,
			params: ["Number","Point"],
			fn: function(scale, center) {
				// code for this overload here
			params: ["Number","Number","Point"],
			fn: function(hor, ver, center) {
				// code for this overload here
	return this;

Although not perfect, I’m pretty pleased with this code. I think the intention is pretty clear, and like that the arguments are correctly named. It doesn’t actually check the type of the argument; the “type definitions” are actually just boolean functions which return true or false if an argument meets their “type criteria”, and so this can easily be used on a whole variety of scenarios.

Also, I made the decision to pass a string value in for the type and have the type defs in the selectOverload function, but that’s just because it suited the situation I was working with, but there’s no reason you can’t adapt the code to use the criteria function itself. In my situation I didn’t feel it would be as readable, but if you have a lot of different types then it may work out more efficient.

Consider that you have two objects, Parent and Child. A child has a parent, and a parent maintains an IEnumerable of children.

class Parent
    public IEnumerable Children { get; set; } 

class Child
    public Parent Parent { get; set; } 

Given a list of child ids, you need to populate the parent with a list of Child instances, and also set the parent of each child.

Method 1: foreach

First option is to use foreach to iterate through each id in the list, get the child, set the parent on it and add it to the parent’s list of children. Since IEnumerable doesn’t support an Add() method, we need to modify Parent to take a List<> or Collection<> instead, and then we can use the code:

foreach (var id in childIds)
    var child = GetChild(id);
    child.Parent = parent;

Now I guess there’s nothing wrong with this; it does get the job done, but when converting a list of something to a list of something else, it seems really wrong not to use linq. Plus, if you were unable to modify the Parent class to use a data type that supported Add(), then this would be out of the questions.

Method 2: linq

parent.Children = childIds.Select(id =>
    var child = GetChild(id);
    child.Parent = parent;
    return child;

As you can see, although this code has been modified to use linq, the lines match almost one-to-one. We can now, however, leave the Parent’s list of children unchanged, as an IEnumerable. I personally would rather use a single line lambda expression rather than a multiline closure like this though, as I feel they read much better, and make it far clearer to see what the intended action is.

Method 3: object extension

There is a useful linq method, ForEach(), which allows the execution of an action on each item of a list. It returns void, but the behaviour is fairly basic so it is easy enough to knock up a quick extension method to do it. I want to be able to reuse this code, as the ability to update an object within a linq query would be a useful one, so rather than extending Parent you can extend object:

public static object SetProperty(this object entity, Action<object> setter)
    return entity;

This allows for the following code:

parent.Children = childIds
                  .Select(id => GetChild(id).SetProperty(c => (c as Child).Parent = parent))
                  .Select(o => o as Child);

Eeesh. The idea worked in principle, but clearly using an object extension is not the way to go! While I like having the ability to chain the method, it’s not nice to have the nested cast to access the parent property. Furthermore, since the extension method returns object, a further Select was required which simply cast the list items back to Child.

Method 4: generic extension

The final solution is, therefore, fairly obvious, and makes for an elegant and easy-to-read solution.

public static T SetProperty<T>(this T entity, Action<T> setter)
    return entity;
parent.Children = childIds
                  .Select(id => GetChild(id).SetProperty(c => c.Parent = parent));

I’ve just read a post by Alex Maccaw, 5 APIs that will transform the Web in 2013, and think that while the APIs described are all pretty cool, my personal favourite has not been mentioned: web intents. The specification is currently in the ‘working draft’ stage and so chances are it still won’t be finalised next year, which probably means browser coverage will be lacking (particularly in the IE camp), but Firefox and Chrome are already picking it up and so at least that’s something!

Web intents is inspired by Android’s Intents framework, and is a framework that allows for web-based inter-app communication and service discovery. The example that is typically bounded about when talking about web intents is photo editing. Say, for example, I build a web application that allows users to upload photos, and I want to enable them to manipulate the photo on my site. I could spend a lot of time trying to develop my own editing system, but the likelihood is that it will be buggy, or lacking in features, because this is simply not my area of expertise. Using the web intents framework, however, I could simply integrate with a third-party photo editing application which is hopefully less buggy and more feature packed than anything I could code myself. Furthermore, since all my application is doing is declaring that it needs a certain type of service, rather than specifying one service specifically, the user is able to select whichever photo editing application suits him best.

This example works well, given the difficulties that can arise for the average developer dealing with advanced image manipulation techniques, but the web intents system specification is open enough that anyone can register a service for any intent that they wish. Take a look at the demos on the webintents.org for some different sample applications, as well as to get an idea of how this system will work. I think it’s really exciting, and will make it easier for us all to develop richer web applications going forward.

I’m a big fan of Twitter’s Bootstrap html/css/javascript framework, and use it on practically all new web projects that I work on. It makes it super easy to quickly knock up a slick-looking web application, and since it’s built on less it’s really easy to customize the look of each site.

That said, the markup is complex enough that when developing sites I typically have the docs open in another tab at all times as a reference point, which lead me to start building little HtmlHelper extensions to create the more complicated elements, such as navbars, forms, etc. These extensions have been bounced around from project to project, and have ended up a little scrappy as they’ve been built as-and-when with no real planning, but they have been hugely useful, so I decided it was finally time to look at rewriting them. Check out the Bootstrap Extensions repo over on GitHub, or have a browse through the documentation (design somewhat inspired by the original bootstrap docs!).

The library is by no means complete, as of writing this I’ve only implemented lists, buttons, button groups + toolbars, navbars and progress bars; but it’s a start, and I intend to cover the majority of the more involved elements. I’ll also look at fine tuning the API to make development as pleasurable as possible.

Update: This project has been included on The Big Badass List of Twitter Bootstrap Resources. Check it out, there’s some brilliant useful stuff on there

If ever you accept user-written HTML code in your web applications, such as may be generated in a rich-text ‘wysiwyg’ text editor, it is vital that before displaying it back anywhere you first sanitize it. Sanitization is the process of removing potentially malicious code, primarily to prevent xss (cross-site scripting) attacks; and is generally achieved by allowing only a subset of tags and attributes in the submitted code and removing or encoding the rest.

I recently needed to do this, and a quick google turned up a project, patapage, which does just that. Although it is a java solution, there is a C# port written by Beyers Cronje; unfortunately it’s some seriously ugly code, being more-or-less a straight rip of the java version, just fixed to be valid c# code.

I realise that some people don’t think that is necessarily a bad thing, but I can’t stand to see eyesores, such as lowercase methods and type names instead of ‘var’, and so had to clean it up. I take no credit for any of the code, all I did was capitalize property/method names; replace some if/elses with ternary operators for terseness (where appropriate); replace type names with ‘var’; and change some arrays to IEnumerables (I hope this should give a bit of a performance gain, but I didn’t bother to check so don’t quote me on that).