A Raspberry Pi Build Light for TeamCity in Mono

Some Background…

After I bought my Raspberry Pi I went through a little period of uncertainty that most other owners have, asking myself “how do I make this thing useful?” It didn’t take long before one of my colleagues created a GitHub repository for a little project that had been sitting around for a while – TeamFlash.

TeamFlash is a build light client app for TeamCity. It monitors the build server to find the status of the latest build and flashes a light in a different colour depending on that status. Having a little bit of electronics know-how, I wanted to see if I could make my Raspberry Pi into a standalone build light.

First up, I knew there had to be someone that’s interfaced with the GPIO ports. Within a few seconds of deciding to search I stumbled upon the RPi Low-level peripherals page. This has a sample of driving the GPIO using C# linking to the RaspberryPi.Net GitHub repository. It has one moving part – Mike McCauley’s BCM2835 library. Brilliant! Now to get it working…

Getting Started

The RapsberryPi.Net README has instructions on how to compile the BCM2835 library into a statically linked library named libbcm2835.so. To use GPIO from Mono I simply:

  1. Compiled the BCM2835 library
  2. Compiled the RaspberryPi.Net project
  3. Took the output of both and added them to my Dependencies folder
  4. Added RaspberryPi.Net.dll to my project as a reference
  5. Added libbcm2835.so to my project as a linked file and changed its build action to Copy if newer

Now I can write code like:

var led = new GPIOMem(GPIO.GPIOPins.GPIO01);
led.Write(true);
Thread.Sleep(1000);
led.Write(false);

Running TeamFlash on YOUR Pi

Here’s how you can get TeamFlash working on your Raspberry Pi.

Step 1 – Wiring it up

I’ve got some standard LEDs from an old Arduino kit, so I’ve hooked each of those in serial with a 330 Ohm resistor to ensure the forward current is within the correct range.

Raspberry Pi TeamFlash Fritzing VisualRaspberry Pi TeamFlash Fritzing Schematic

Step 2 – Boot Raspbian

Go to http://www.raspberrypi.org/downloads and get the latest release of Raspbian. Follow the instructions and get it up and running.

Step 3 – Install the Required Components

To get it all going you’ll need to install mono. If you want to build it on the Pi, install git and mono-complete:

sudo apt-get install git
sudo apt-get install mono-complete

Otherwise the mono-runtime will suffice:

sudo apt-get install mono-runtime

Step 4 – Get TeamFlash

Again, if you want to compile the app on the Pi:

git clone https://github.com/ducas/TeamFlash.git
cd TeamFlash
xbuild

Otherwise you can clone the repository and compile it on your desktop/laptop and just move the output (contents of TeamFlash/bin/Debug) around on a USB key.

Step 6 – Configure TeamFlash

Edit the serverUrl, username and password values in TeamFlash.exe.config (in the output directory of the build – TeamFlash/bin/Debug). If you’re looking for an easy way to do this on the Pi, try using nano:

nano TeamFlash.exe.config

When using nano, simply change the appropriate values and hit Ctrl + X to exit – you will be prompted to save.

Step 7 – Run TeamFlash

sudo mono TeamFlash.exe

Step 8 – Profit!

And that’s it! When your build is:

  1. Good – the green light will stay lit
  2. Broken – the red light will flash on and off
  3. Investigating – the red and yellow lights will flash sequentially

Unit Testing and the .NET Micro Framework

Recently I decided to take up a new hobby… writing code for small things. So, being a .NET developer, I decided the easiest way to crack this nut is to use .NET Micro Framework (or NETMF).

Getting started with NETMF is fairly easy for a .NET developer. You go to www.netmf.com, download and install the SDK and you create new projects using the new templates.

One thing that’s missing from NETMF is the ability to unit test your projects. Because the core is not the same as the desktop core there are no unit testing tools. Searching a bit I found a few people using some patchy solutions involving referencing code files in regular unit testing projects. While this may work for some, I don’t believe it’s the most accurate test as the framework implementations are rather different. This drew me to creating my own solution…

Introducing MFUnit!

MFUnit is a simple .NET Micro Framework Unit Testing Library. It uses convention based discovery to find and run your tests.

Open Source

MFUnit is open source – https://github.com/ducas/MFUnit. Check it out! You’ll find a readme page with more detailed information and source code, including a test project that uses MFUnit to test the Assert class.

Installation

1. Create a NETMF Console Project

2. …

Install-Package MFUnit

3. Profit!

Installing this package will create a class named TestProgram. Simply delete Program.cs, write your tests and you’re on your way.

Conventions

  1. Test fixtures/classes must end with Tests
  2. Test methods (or facts) must be public void methods

Asserting

MFUnit comes with an Assert library that supports the following methods:

  • Fail
  • AreEqual
  • IsTrue
  • IsFalse
  • IsNull
  • IsNotNull
  • Throws

Example

The following class will be discovered by the test runner and the methods will be executed.

public class AssertTests
{
    public void AssertIsNull_ShouldPass_WhenActualIsNull()
    {
        Assert.IsNull(null);
    }

    public void AssertIsNull_ShouldFail_WhenActualIsNotNull()
    {
        Assert.IsNull(1);
    }
}

The first method will pass, but the second will fail. The Output Debug window will contain the following text:

PASS AssertTests.AssertIsNull_ShouldFail_WhenActualIsNull
    #### Exception MFUnit.AssertException - 0x00000000 (3) ####
    #### Message: Expected: "null", Actual: "not null".
    #### MFUnit.Assert::Fail [IP: 0005] ####
    #### MFUnit.Assert::IsNull [IP: 000f] ####
    #### MFUnit.Tests.AssertTests::AssertIsNull_ShouldPass_WhenActualIsNull [IP: 0008] ####
    #### System.Reflection.MethodBase::Invoke [IP: 0000] ####
    #### MFUnit.TestRun::Execute [IP: 00b6] ####
A first chance exception of type 'MFUnit.AssertException' occurred in MFUnit.dll
FAIL AssertTests.AssertIsNull_ShouldPass_WhenActualIsNotNull: Expected: "null", Actual: "not null".

GUI

Currently the only GUI is a simple Pass/Fail count.

MFUnit GUI

Depending on whether this picks up and how many people request it, I may put some effort into listing the appropriate tests and making the information navigable.

Also, once VS11 is a bit closer to release, I may add a plugin for the test runner.

Enjoy!

Hopefully this is useful to others out there. If you have any suggestions feel free to leave comments. If you want to contribute I’ll happily accept GOOD pull requests.

Using Web API Validation with jQuery Validate

Building on my last post about validating your model with Web API, if you’re calling a Web API controller from JavaScript you may need to parse the validation result and display it on the screen.

Most people using MVC would be using the jQuery Validate plugin that’s been included with the default template for quite a while now. While most validations are performed using JavaScript adapters, some are only performed server side. As a result, the regular unobtrusive JavaScript adapters will not catch this before the post occurs. This means that you if you are using JavaScript requests with Web API to handle data manipulation you will need to somehow manually handle the validation errors that will be returned.

Plugging into jQuery Validation is actually quite easy… To validate a form, simply select the form using jQuery and call .validate() on it – e.g.

var validator = $('.main-content form').validate();

This will return a validator object will a few handy methods on it. Two of which are valid() and showErrors(). The valid method will return a Boolean value indicating whether the form is valid or not and the showErrors method will show any validation errors on the current form. The showErrors method also accepts an object that defines any additional error messages you wish to display – e.g. to display the message “The title is incorrect” for a property named Title:

validator.showErrors({ Title: 'The title is incorrect.' });

Now, assuming I a view with the following mark-up inside the form, I should see a validation error:

<div class="editor-label">@Html.LabelFor(model => model.Title)</div>
<div class="editor-field">
    @Html.TextBoxFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title)
</div>


But how do we connect this to Web API…? Well, if you’ve read my previous post you’ll recall that calling a Web API controller’s PUT action that’s decorated with the ValidateFilter attribute I created will return a collection of validation errors if the model is not valid. To test this, I’ll modify my TodoApiController from the previous post as follows:

[ValidateFilter]
public void Put(int id, TodoItem value)
{
    if (value.Title == "hi there")
        ModelState.AddModelError("Title", "The title is incorrect.");

    if (!ModelState.IsValid) return;

    db.Entry(value).State = EntityState.Modified;
    db.SaveChanges();
}

I should now receive a validation error whenever I try to update an item with the title “hi there”. Let’s write some jQuery to submit my form:

function updateItem(form, url) {
    var validator = form.validate(),
        serialized = form.serializeArray()
        data = { };

    if (!validator.valid()) { return; }

    // turn the array of form properties into a regular JavaScript object
    for (var i = 0; i < serialized.length; i++) {
        data[serialized[i].name] = serialized[i].value;
    }

    $.ajax({
        type: 'PUT', // Update Action
        url: url, // API Url e.g. http://localhost:9999/api/TodoApi/1
        data: data, // e.g. { TodoItemId: 1, Title: 'hi there', IsDone: false }
        dataType: 'JSON',
        success: function () { alert('success'); },
        error: function (jqXhr) { extractErrors(jqXhr, validator); }
    });

}

Now let’s look at extractErrors:

function extractErrors(jqXhr, validator) {

    var data = JSON.parse(jqXhr.responseText), // parse the response into a JavaScript object
        errors = { };

    for (var i = 0; i < data.length; i++) { // add each error to the errors object
        errors[data[i].key] = data[i].value;
    }

    validator.showErrors(errors); // show the errors using the validator object
}

Lastly, attaching to the form’s submit event will call this whenever the Enter key is hit or the Submit button is clicked:

$('.main-content form').submit(function () {
    updateItem($(this), '/api/TodoApi/' + $('#TodoItemId').val());
});

Validating your model with Web API

One of the great things about ASP.NET 4.5′s Web API is that it’s built on the same (or similar) principles as MVC. This means that you get a lot of cool things out of your API controllers from MVC – like Action Filters.

While building my first Web API controller, I wanted to ensure that a creation or an update of an item was only done if that item was valid. I also wanted to pass any validation errors back to the client. This looks quite difficult at first because the Put and Post functions on an ApiController can’t return a result. Action Filters to the rescue!

With a simple action filter attribute, you can ensure that your models are validated and the errors are returned in a simple format to the client by decorating the appropriate methods.

Note: Code also available on Gist - https://gist.github.com/1920999

public class ValidateFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var modelState = actionExecutedContext.ActionContext.ModelState;
        if (!modelState.IsValid)
        {
            var errors = modelState
                .Where(s => s.Value.Errors.Count > 0)
                .Select(s => new KeyValuePair<string, string>(s.Key, s.Value.Errors.First().ErrorMessage))
                .ToArray();

            actionExecutedContext.Result = new HttpResponseMessage<KeyValuePair<string, string>[]>(
                errors,
                HttpStatusCode.BadRequest
            );
        }
    base.OnActionExecuted(actionExecutedContext);
}

Now, for the controller implementation…

public class TodoApiController : ApiController
{
    private BetterMobileSpaContext db = new BetterMobileSpaContext();

    // GET /api/todoapi
    public IEnumerable<TodoItem> Get()
    {
        return db.TodoItems.ToList();
    }

    // GET /api/todoapi/5
    public TodoItem Get(int id)
    {
        return db.TodoItems.Find(id);
    }

    // POST /api/todoapi
    [ValidateFilter]
    public void Post(TodoItem value)
    {
        if (!ModelState.IsValid) return;

        db.TodoItems.Add(value);
        db.SaveChanges();
    }

    // PUT /api/todoapi/5
    [ValidateFilter]
    public void Put(int id, TodoItem value)
    {
        if (!ModelState.IsValid) return;

        db.Entry(value).State = EntityState.Modified;
        db.SaveChanges();
    }

    // DELETE /api/todoapi/5
    public void Delete(int id)
    {
        TodoItem todoitem = db.TodoItems.Find(id);
        db.TodoItems.Remove(todoitem);
        db.SaveChanges();
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

Now a Create (PUT) and an Update (POST) request will validate the model before invoking the appropriate action. Calling Create from using a JSON request with an invalid model would look something like this:

Request

Method: PUT

Body: { Title: ”, IsDone: false }

Response

Status Code: 400 (Bad Request)

Body: [{ "key": "Title", "value": "The Title field is required" }]

Using a valid model will simply result in a 200 (OK) response with no body.

NOTE: while writing this post I stumbled on these two blog posts that did the same thing and adapted my code:

EDIT 2012-02-27: Updated code to replace ValidationError type with KeyValuePair and changed filter to be after action execution so controller can perform any extra validation.

Project Liike (aka. Microsoft Patterns & Practices do Mobile Web)

Microsoft have started a new Patterns & Practices project name Liike (LEEE-keh) with the aim of delivering guidance for building mobile web solutions.

http://liike.github.com/

How do they plan to do this…?

Well they’ve got a few FTE’s who are creating a mobile version of a previous project as a reference implementation so they can make the mistakes we’ve all made in the past. They’ve also taken on an advisory board consisting of a few members of the community (including myself) for some ideas and extra guidance.

One thing that’s been made clear so far is that reusable code is not a major deliverable. There are many people out there who’ve done a bang-up job of building UI frameworks and plugins for mobile web, so they don’t want to re-invent the wheel – they just want to reduce the squeak in yours by giving you the oil you need to run smoothly.

So, how can you help…?

1. There’s a uservoice site available for you to throw your ideas for what you think are the most important challenges: http://liike.uservoice.com/forums/136038-mobile-web-dev-guidance

2. Start a conversation with myself or anyone else on the advisory board! I’m always available on twitter and am happy to take comments on my blog. If you want to get me on email, just leave a comment on this post and I’ll get back to you.

Using the System Tray to show progress in Windows Phone 7 Mango

Before Mango it was a little difficult to put a generic status message at the top of your page. The Mango tools have made this a bit easier by giving developers (more) access to the System Tray. That’s this part:

You are still a bit limited in what you can do (i.e. you can’t actually add or remove icons), but there’s a lot more flexibility than before.

You can access the system tray either in code or XAML using the Microsoft.Shell.SystemTray class. This class has the following dependency properties:

  • IsVisible
  • Opacity
  • BackgroundColor
  • ForegroundColor
  • ProgressIndicator

While it’s quite exciting to be able to style the status bar, I cried out of joy when I saw the ProgressIndicator property. Why…? Because now I can add progress information to the top of my pages quickly and easily! J

So, I want to add a downloading message and progress bar to the top of my page (above the application title) as follows:

Using XAML, I can add text and a progress bar to a page by dropping the following into the page:

<shell:SystemTray.ProgressIndicator>
    <shell:ProgressIndicator IsIndeterminate="true" IsVisible="True" Text="Click me..." />
</shell:SystemTray.ProgressIndicator>

Or, using code, I can accomplish the same thing by dropping this into my code:

ProgressIndicator progress = new ProgressIndicator
{
    IsVisible = true,
    IsIndeterminate = true,
    Text = "Downloading details..."
};
SystemTray.SetProgressIndicator(this, progress);

Feel free to download my sample application showing how to manipulate the System Tray:


Open SystemTraySample.zip

Pushing to Windows Phone 7 devices using MetroPimp

Recently I released a little open source project with the aim of making it easier for developers to write services that push information to Windows Phone 7 devices called MetroPimp.

This library is available via nuget and on bitbucket.

Based on a blog post I wrote when WP7 was still in beta, MetroPimp provides a simple and consistent API that allows you to push Toast, Tile (single and double sided) and Raw push notifications to WP7 devices using the Microsoft Push Notification Service (MPNS).

As developers who have tried this already may know, there is quite a bit of work that goes into setting up push notifications. First you have to register for notifications on the device by opening a channel. Then you have to get the URI provided by MPNS and send it to a service of your own. Lastly, using this URI you need to form XML packets and craft HTTP requests with the right headers to push the data to the device.

MetroPimp simplifies the last step of this process by providing a model that represents the messages you want to send to devices, a single method call to handle serializing the message and sending it up the wire and a simple result which, in the case of failure, identifies the reason for the failure and provides informative message.

Enough talking… show us the code!!!

The main entry point of MetroPimp is the Pusher class (which can be mocked via the IPusher interface). It has a single method named Send that accepts a Message and returns a SendMessageResponse. To create a Pusher, simply new it up (or inject it using your preferred IOC container).

var pusher = new Pusher();

The following sections will define the classes you can use to push various notification formats to a device. For more information on message formats, please refer to Sending Push Notifications for Windows Phone on MSDN.

Raw

To send raw data to the phone (i.e. a notification that is not a toast or tile update), create an instance of Raw and send it using the pusher.

var rawMessage = new Raw {
    Uri = /* insert MPNS uri here */,
    Content = "hello world!"
    };
pusher.Send(rawMessage);

MPNS does not limit you to sending strings in the raw message. However, seeing as just about anything can be represented as a string, I decided this may be more universal. Under the covers, MetroPimp simply converts the string to its UTF8 representation and drops it into the request body.

For more information on sending and receiving raw notifications, refer to How to: Send and Receive Raw Notifications for Windows Phone on MSDN.

Toast

Sending a toast message is similar to sending a raw message in that you simply create an instance of a Toast object and pass it into Send. Toast has 3 fields that differ it from a raw:

  • Text1 – The
    first bit of bold text that appears in the toast (required)
  • Text2 – The second bit of text that appears in the toast (optional)
  • Param – A parameter string to be passed to the application if the user taps the notification (optional)
var toastMessage = new Toast {
    Uri = /* insert MPNS uri here */,
    Text1 = "Hello World!",
    Text2 = "This is a toast.",
    Param = "helloWorldToasted"
    };
pusher.Send(toastMessage);

For more information on sending and receiving toast notifications, refer to How to: Send and Receive Toast Notifications for Windows Phone on MSDN.

Tile

Tile notifications can be specified to be either single or double sided tiles. As double sided tiles are only supported by WP7 Mango, the functionality has been split into two classes. Sending a single sided tile is done by specifying properties available on the Tile class.

  • BackgroundImageUri – The URI to the background image for the tile. Can be either embedded or remote. (required)
  • Title – The text to use as the title of the tile. (required)
  • Count – The number to show in the blue bubble. Not defining or using 0 will clear the bubble. (optional)
var tileMessage= new Tile {
    Uri = /* insert MPNS uri here */,
    BackgroundImageUri = "background.png",
    Title = "Hello World",
    Count = 9
    };
pushed.Send(tileMessage);

Double sided tiles are sent by specifying properties on the DoubleSidedTile class. This class has the same set of properties as Tile for the front side of the tile, along with the following properties for the back side:

  • BackBackgroundImageUri – The URI to the background image for the back of the tile.
  • BackTitle – The text to use as the title for the back of the tile.
  • BackContent – The text to display over the top of the background image on the back of the tile.
var doubleSidedTileMessage = new DoubleSidedTile {
    Uri = /* insert MPNS uri here */,
    BackgroundImageUri = "background.png", 
    Title = "Hello World", 
    Count = 9, 
    BackBackgroundImageUri = "back_background.png",
    BackTitle = "Hello Back",
    BackContent = "This is the back"
    };
pushed.Send(doubleSidedTileMessage);

For more information on sending and receiving toast notifications, refer to How to: Send and Receive Tile Notifications for Windows Phone on MSDN.

Auxiliary Properties

Raw, Toast, Tile and DoubleSidedTile all inherit the base Message class. This class provides the following optional properties to give you greater control over your notification messages:

  • Id – a GUID value representing the message identifier.
  • DeliveryInterval – Defines when the message should be delivered to the device. This can either be immediate (default), within 450 seconds or within 900 seconds.

SendMessageResponse

As soon as you’ve started trying to send notifications to devices, you’ll want to know if it gets through and/or why it failed. To handle this, Pusher.Send returns a SendMessageResponse object with the following properties:

  • ErrorMessage – The message returned from MPNS on the HTTP response.
  • MessageId – The
    identifier of the message. Only included if specified when sending.
  • HttpStatusCode – The HTTP status code (e.g. 200, 400, 401, etc.) of the HTTP response returned from MPNS.
  • HttpStatusDescription – The description of the HTTP status code returned from MPNS.
  • StatusCode – The actual status of the notification’s delivery returned from MPNS (i.e. Received, Queue Full, Suppressed or Dropped).
  • DeviceConnectionStatusCode – The status of the device’s connection to MPNS (i.e. Connected, Temporarily Disconnected, Inactive or Disconnected).
  • SubscriptionStatusCode – The status of the device’s subscription to MPNS (i.e. Active or Expired).
  • DetailsStatusDescription – The detailed description of the notification message’s status given the HTTP status code, MPNS status code, connection and subscription status according to the MSDN documentation.

For more information on response codes, refer to Push Notification Service Response Codes for Windows Phone on MSDN.

Back button broken for URL hashes in IE on WP7 Mango

I’ve been on a little twitter rant recently about this, and thought I’d use my blog as another distribution medium.

Feel free to leave comments here, here (connect forum) or here (jQuery Mobile forum).

Here’s the content of my connect forum post on the matter:

Mango seems to have brought along with it a broken browser…

When you link to an anchor on your page using a hash, the back button doesn’t seem to work too well.

For example, go to http://jquerymobile.com/demos/1.0b1/. Those in the know will realise why… To put it simply, jQuery Mobile uses hash changes to navigate between “pages” in a single or multiple page web application. It uses the hash changed events to determine when to use javascript to request the next page, load it into the DOM and perform an animation to display the next page.

Navigating forward on a jQuery Mobile site works perfectly as expected. It’s when you hit the back button that things go wrong. On a desktop browser, going from the landing page to “Into to jQuery Mobile” swipes in the intro page and hitting back swipes it out again to show the landing page. However, on Mango, hitting the back button when on the intro page does nothing. If you were on another site before you went the the demo landing page, then hitting the back button again will take you back to the previous site.

I have been working on an embedded web application recently and this has been driving me crazy! I’m seeing a Navigated event being raised by the WebBrowser control when it goes to the second page in the application, but back buttons (and manually invoking history.back() and history.go(-1) in javascript) just don’t do anything.

This seems to be a breaking change to me and would potentially mean I push to have Windows Phone 7 dropped as a targetted platform for the (relatively high traffic) website I am working on. An embarrassing idea seeing as I pushed for it to be targetted… :-(

UPDATE 14 July 2011 – It’s been noted that the jQuery Mobile docs site mentioned does work in previous builds of WP7, running IE 7 Mobile. This verifies that this issue has been introduced with IE9 Mobile on WP7 Mango.

UPDATE II 14 July 2011 - The issue is a little deeper than I initially realized. If you define a simple page with an anchor at the top of the page referencing a div at the bottom of the page then we see some more exotic behaviour. Clicking the link and hitting back will work the first time. However, you’ll notice that in the address bar the hash is not removed from the URL. This means that clicking the link and hitting back again will get the browser into a tangle. Here is the HTML snippet I used:

<a href="#bottom">bottom</a>
<div style="height: 1000px"></div>
<a id="bottom" href="#" onclick="javascript:history.back();return false;">back</a>

UPDATE III October 2011 - The issue appears to have been fixed in Mango RTM.

Making MVC 3 a little more… dynamic

The other day I ran into a little problem. I wanted to be able to post some JSON to a web service and have it accept a whole bunch of data (not exactly the technical term) that was not predefined.

Given this very vague problem, I decided I wanted to use ASP .NET MVC 3. So starting with File\New Project, I added a method to my HomeController as follows:

[HttpPost]
public ActionResult DoSomething(string a, string b, dynamic c)
{
    return new EmptyResult();
}

The thought behind this was that I wanted to supply two required properties (a and b) and basically have a dynamic bag for everything else. Also, I didn’t want to be restricted to a single layer of properties. Instead, I wanted to be able to pass a deep tree and have it totally accessible.

Then I pulled up fiddler and set up a request with the following details:

Method POST
URL http://localhost:2643/Home/DoSomething
Request Headers User-Agent: Fiddler

Content-Type: application/json

Request Body { a: “Hello”, b: “World”, c: { d: “this”, e: “is”, f: “dynamic” } }

image

When I hit execute and set a breakpoint on the action, I received the following values in my locals:

clip_image002

As expected, the JsonValueProviderFactory has kicked in and populated the values of a and b using the JSON provided. However, it cannot match c properly so simply throws an object at it that is not dynamic and does not have values on it, hence useless.

After some searching, I found a few valid solutions. The most useful one was this blog post by Anoop Madhusundanan. In this post, he describe the process of using a model binder and a custom model binder attribute to identify parameters of an action method that are to use the model binder. This seemed like a great solution for me, but had a couple of little problems… Most importantly, Anoop’s solution does not allow for multiple parameters on an action method or mapping the parameter to the property in the JSON object.

I came up with a very similar way of solving this problem. I created a class named DynamicJsonBinder which implements IModelBinder, just like Anoop. The main difference with my solution is that I provided a way to ensure that the parameter being populated with the dynamic object is mapped based on the name of the parameter. This is done by using a switch on the attribute called MatchName, which will cause the binder to look at the parameter name and find the matching property in the JSON object to return.

Here’s the attribute:

using System.Web.Mvc;

public class DynamicJsonAttribute : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new DynamicJsonBinder(MatchName);
    }

    public bool MatchName { get; set; }
}

And here’s the model binder:

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Web.Helpers;
using System.Web.Mvc;

public class DynamicJsonBinder : IModelBinder
{
    private readonly bool matchName;

    public DynamicJsonBinder(bool matchName)
    {
        this.matchName = matchName;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var contentType = controllerContext.HttpContext.Request.ContentType;
        if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        string bodyText;
        using (var stream = controllerContext.HttpContext.Request.InputStream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream))
                bodyText = reader.ReadToEnd();
        }

        if (string.IsNullOrEmpty(bodyText)) return null;

        var desiralized = Json.Decode(bodyText);

        if (!matchName) return desiralized;

        var members = desiralized.GetDynamicMemberNames() as IEnumerable&lt;string&gt;;
        return members == null
            || members.Contains(bindingContext.ModelName)
            ? desiralized[bindingContext.ModelName] : null;
    }
}

So if by adding a DynamicJson attribute to the c parameter on the action method, we’ll get the following:

public ActionResult DoSomething(string a, string b, [DynamicJson] dynamic c)
{
    return new EmptyResult();
}

Debugging into this with the same post request as earlier:

clip_image004

We see that c has been populated with a DynamicJsonObject (the result of the call to Json.Decode) and that it has recursively mapped the properties under the JSON object to dynamic object. However, the value is the entire JSON object, that is it’s not mapped to the c property.

To enable name matching we get the following code:

[HttpPost]
public ActionResult DoSomething(string a, string b, [DynamicJson(MatchName = true)] dynamic c)
{
    return new EmptyResult();
}

Debugging we get:

clip_image006

And we see that the property has been matched correctly and the correct value is passed through to the parameter.

Using these two simple classes and a bit of dynamic know-how, I’ve managed to post anything to my web service and have it dynamically accessible. This basically means we have the equivalent of a property bag on steroids that can be queried and manipulated in the same way as any dynamic object. We can even re-serialize the dynamic object to JSON and store it as is if required.

A Day in the Life of a Metro-veloper

This is a follow-up post to my Windows Phone 7 presentation last week at the SDDN.

I have uploaded my powerpoint deck to SlideShare.

Some of the sample apps I used are available on MSDN.

And there was a recent video on youtube of an awesome golfing app that really shows the power of the WP7 UX.

Follow

Get every new post delivered to your Inbox.