JSON, .NET and NSDate

If you’re trying to access a JSON web service created using .NET from an iOS device, you’ve probably discovered that dates are produced in a less than useful format:


The rationale for the date format can be found here, but it’s basically a call to the JavaScript Date object constructor. The numeric value represents the number of milliseconds since 1970-01-01.

Below I’ve added a handy Objective-C function that will extract the value and return an NSDate object. Note that we’re losing accuracy by magnitudes as we translate from .NET DateTime objects (which measure time in ticks) to JavaScript Date objects (which measure time in milliseconds) and finally to iOS NSDate objects (which measure time in seconds).

 * Converts a .NET JSON date in the format "/Date(x)/" to an NSDate object.
 * @param string The NSString to convert.
 * @return the NSDate object.
(NSDate*)jsonStringToNSDate(NSString* string) {

    // Extract the numeric part of the date.  Dates should be in the format
    // "/Date(x)/", where x is a number.  This format is supplied automatically
    // by JSON serialisers in .NET.
    NSRange range = NSMakeRange(6, [string length] - 8);
    NSString* substring = [string substringWithRange:range];

    // Have to use a number formatter to extract the value from the string into
    // a long long as the longLongValue method of the string doesn't seem to
    // return anything useful - it is always grossly incorrect.
    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    NSNumber* milliseconds = [formatter numberFromString:substring];

    [formatter release];

    // NSTimeInterval is specified in seconds.  The value we get back from the
    // web service is specified in milliseconds.  Both values are since 1st Jan
    // 1970 (epoch).
    NSTimeInterval seconds = [milliseconds longLongValue] / 1000;

    return [NSDate dateWithTimeIntervalSince1970:seconds];


CanvasLayers - A Layer Library for the HTML5 Canvas Tag

Wouldn’t it be neat if the canvas tag supported layers? Now it does!

This uses the layering engine from CanvasUI, modified to support transparency and transparent sections (if required). Unlike other layer libraries for javascript, this uses a single canvas rather than a stack of several. Something this library gives you that a stack of canvases can’t is nested layers.

I changed the CanvasUI library so that it uses the latest Woopsi layout technique (damaged rects) instead of the old method (BSP trees). It doesn’t appear to have had any impact on performance, but it does make the code simpler. The new CanvasLayers library uses the latest version of the CanvasUI as its basis. I’m hoping to strip the duplicate functionality out of CanvasUI and use the CanvasLayers library as the canvas engine.

The CanvasLayers library sourcecode can be downloaded from BitBucket:


Side Projects

I’ve been working on a few side projects lately that I’ve neglected to mention here, so I’ve decided to rectify that.

Working Week JS

This is the latest project. It’s a port of the C# WorkingWeek library that I mentioned a while ago to JavaScript. It’s functionally identical, except that it includes a TimeSpan class (JavaScript doesn’t have one) and it doesn’t include the custom iterators. JavaScript 1.7 apparently includes these, but as only FireFox supports this version (and even FireFox wouldn’t recognise the “yield” keyword) I replaced them with a more traditional approach.


This is a little C# framework for creating console applications with a UI like Mercurial. Mercurial lets you perform all manner of shortcuts to get at the commands you want:

hg sta
hg help sta

These are automatically translated back to:

hg status
hg help status

MurkyCommando lets you achieve the same thing. It includes the help functionality and will pre-parse command line arguments into argument/value combinations.


BugBare is a distributed bug tracker that uses MurkyCommando to present a very Mercurial-like command line UI. It’s written in C#, and works in both .NET and Mono.

There are quite a few distributed bug trackers out there. For example:

They all have problems, though:

  • Bugs Everywhere doesn’t work in Windows
  • DITrack only works with Subversion
  • Distract has vanished from the net
  • pitz doesn’t have a UI and requires you to use the Python interpreter and its object model to create bug reports
  • ditz was abandoned 2 years ago and doesn’t work with the latest version of Ruby
  • Fossil logically separates bugs from code, so bugs cannot be branch-specific

I haven’t used Artemis yet, so I can’t comment on that one.

BugBare is designed to allow Windows developers (or anyone else who doesn’t mind installing Mono) to get in on the distributed fun.

Distributed bug tracking sounds terribly complicated, but it’s not at all. All but Fossil in the list above work the same way. They create a sub directory within the source repository and add bugs as human-readable text files. This makes merging bugs trivial for most source control systems. Fossil is only different because it’s backed by a SQLite3 database.

One of the main aims I had for BugBare was to make logging bugs as easy, or easier, than just updating a text file. A few years ago I went to the FogBugz World Tour in Cambridge to hear former uber-blogger Joel Spolsky speak. The one thing that really struck me about FogBugz was just how easy and fast it was to enter a bug into the database. Spolsky noted that most developers use a text file to log bugs because it’s quick. I do the same - if I spot a bug whilst I’m in the middle of coding something, I really don’t want to spend 5 minutes filling in dozens of tiny boxes in trac and lose my concentration in the process. I just want to note the bug down somewhere and forget about it until later. Developers don’t want a high-friction bug tracker.

Logging a bug in BugBare (which is entirely command line based, like all of the other trackers mentioned, barring Fossil (again)) takes just one command:

bg add "Something went wrong."

Assuming you’re using a command line DVCS, it is extremely easy to work BugBare into your work flow. For example:

hg pull
hg update
hg commit -m "Made some changes."
bg add "Found a bug somewhere."
hg add
hg commit -m "Made some more changes, added a bug."
hg push

It’s as quick as using a text file, but you get extra benefits:

  • You can add comments to bugs
  • Bugs store the date they were logged/modified
  • Bugs store the user who logged them, which defaults to the logged-in user
  • Bugs can be open/closed/rejected
  • Bugs can have several different priorities (low, normal, high, critical)
  • You can search the database for bugs based on various criteria

Sounds great! However, I’m not entirely convinced that distributed bug trackers are the way to go. Imagine you’ve downloaded a new version of your favourite open-source program; FireFox, for example. You spot a bug and want to report it. However, FireFox has switched to using git and Bugs Everywhere. To log the bug, you have to:

  • Install git
  • Learn the basics of how it works
  • Clone the FireFox source repository
  • Install Bugs Everywhere and its dependencies
  • Learn how to use Bugs Everywhere
  • Log the bug
  • Commit it to the repository
  • Send a patch to the FireFox team that contains the bug (you won’t be able to push to their repo)

From an end-user’s perspective, distributed bug trackers are awful. For most open-source projects, which rely on the “many eyeballs” way of identifying bugs, they just won’t work. It gets worse when you consider that each branch of each different repository clone can have its own separate bug database. Even if someone wrote a web front end to a distributed bug tracker, to allow it to be used by non-developers, it would quickly become confusing if it had to provide access to all bugs in all branches of the repository.

This is probably why most of the trackers listed in this post see very little activity these days. They’re a great idea, and fantastic for individual developers and small teams, but they’re extremely counter productive for open source projects.

So where does that leave BugBare? I’m announcing a new program and at the same time saying that using it probably isn’t a great idea. Perhaps I should get a job in marketing? Personally, I don’t think I’ll use it much. BitBucket’s bug tracker is fairly quick. More importantly, anyone can see it and add bug reports with little effort.


Loose Ends

I have released a few other projects to the tinterwebs recently, but haven’t as yet announced them.


First up is version 3.0 of ALite, a simple data-access and data validation framework for .NET4:


This version simplifies much of the framework. I went off on a wild tangent before moving the repository from SourceForge to BitBucket and started implementing features such as pseudo-transaction support. I even tried real transaction support using the classes from the System.Transactions namespace, but ran into so many nasty problems that it quickly became obvious that it wasn’t going to work.

Instead, ALite now works much more like Igmongonious. It uses a document (key/value store) to store the values of properties, which simplifies and speeds up the undo system. Swathes of code have been refactored to make the framework easier to use.

The “changelog” document seems to be inaccurate so I can’t give a complete breakdown of everything that has changed. Fortunately, no-one but me is crazy enough to use this library.

I moved the repository from SourceForge to BitBucket for a number of reasons. SourceForge has done some neat things with their UI and added a host of exciting new features, but:

  • BitBucket is a better fit for small projects like this. SourceForge’s insistence on manually vetting all projects doesn’t seem to have alleviated the amount of junk projects in its database, but it does increase the amount of work necessary to get what should be a minor project up and running.

  • Mercurial is magnitudes faster than SubVersion, particularly when SubVersion is lumbered with SourceForge’s horribly slow SVN servers.

  • BitBucket projects come equipped with a Creole-based wiki. Though SourceForge has recently added a per-project MediaWiki installation to their suite of features, Creole is notably terser than MediaWiki markup. The wiki is much simpler, which again is perfect for smaller projects. The entire wiki can be pulled down as a Mercurial repo allowing local editing and change tracking.


Next up is Chroma-X, my ill-fated, unfinished and unfortunately-named shoot-em-up for the GP2X:


Nothing new in here, but the sourcecode is browsable and easily accessible. Incidentally, I managed to get the game running on a GP2X Wiz. I was disappointed to discover that it was slower on the Wiz than it was on the GP2X F-200, which put a damper on my Wiz coding plans.

Canvas UI

Lastly, my canvas UI project is also now on BitBucket:


Since the last version I’ve fixed a few bugs and added plenty of new features, including:

  • Window close and depth buttons;
  • Scrolling lists;
  • Shadows on label text for disabled buttons;
  • Separation of GUI definition from library code.


Canvas Tag Clipping 3, AKA a Javascript Window Manager

Building on yesterday’s code, here’s the latest version:

At this point, the similarities to Woopsi should be apparent. This is a basic but workable window manager for the canvas tag. New things since yesterday include window and button gadgets, a top-level container gadget, event handling (click, release, release outside, focus and blur), focus and blur functionality, and probably some other stuff that I’m forgetting.

In various places I’ve just ported code straight from C++/Woopsi to Javascript, whilst in others I’ve taken advantage of lessons I learned whilst writing Woopsi to come up with better approaches. For example, the list of gadget event handlers is a separate class. I’ll probably update Woopsi to follow the same pattern.

As for why I’m doing this - I haven’t the faintest idea. Seemed like a good idea at the time.


Canvas Tag Clipping 2

Continuing on from the last post, I’ve made some improvements to the Javascript UI skeleton:

Try clicking on and dragging the rectangles around and see what happens. Unless you’re using IE, of course, in which case I suggest you go and download a web browser first.

I read up on the canvas API and it transpired that the canvas element already includes clipping functionality. I ripped out my own clipping routines and used the rectangles calculated by the BSP routine to define the clipping regions for the built-in drawing functions. (As an aside, I’m seriously considering pulling the Graphics class out of Woopsi and using the GraphicsPort everywhere, so that clipping is available when drawing to bitmaps. This would require a few changes to the way the clipping region is specified, but I think it would be a change for the better.)

I’ve also improved the way gadgets recalculate their clipping regions when they are moved. Instead of recalculating the entire BSP tree, the system just recalculates the tree nodes within the space defined by the moved gadget’s parent. Since those nodes are the only nodes that can possibly have changed, there’s no reason to recalculate everything.

Gadgets are limited to the confines of their parents. This makes it impossible for them to overlap their parents’ borders. In Woopsi this border protection was aided by the alternative display partitioning scheme; the BSP system used here does not make it quite so easy.

Finally, gadgets jump to the front of the stack when clicked. However, this has been disabled so that it’s possible to move a gadget behind another and actually prove that there’s a reason not to just opt for the painter algorithm instead of this BSP stuff.