Fri, 18 Mar 2011

Todo List App Using ASP.NET MVC 3 and Windows Azure Tables

For this week’s episode of Cloud Cover, Wade and I talked about how to use Windows Azure Tables from .NET code, and we focused on using ASP.NET MVC 3 and doing paging over tables.

Rather than rehash the entire episode here, I’d like to point you to the episode itself (should go live Friday morning), the running app (http://smarxtodo.cloudapp.net), and the full source code (http://cdn.blog.smarx.com/files/smarxtodo_source.zip).

The one piece of code I’d like to highlight here is the code that performs paging. This is from ApiController.cs:

[HttpPost]
[ValidateInput(false)]
public ActionResult Get(string token)
{
    var account = CloudStorageAccount.Parse(
        RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
    var ctx = account.CreateCloudTableClient().GetDataServiceContext();
    var query = ctx.CreateQuery<TaskEntity>("Tasks")
        .Where(t => t.PartitionKey == string.Empty).Take(5).AsTableServiceQuery();
    var continuation = token != null
        ? (ResultContinuation)new XmlSerializer(typeof(ResultContinuation))
            .Deserialize(new StringReader(token))
        : null;
    var response = query.EndExecuteSegmented(query.BeginExecuteSegmented(continuation, null, null));
    var sw = new StringWriter();
    new XmlSerializer(typeof(ResultContinuation)).Serialize(sw, response.ContinuationToken);
    return Json(new {
        tasks = response.Results,
        nextToken = sw.ToString(),
        hasMore = response.ContinuationToken != null });
}

This code is invoked by an AJAX call from the client. The JSON data it returns includes nextToken, which references the continuation token, if any, returned by table storage. The format of the nextToken string is actually an XML-serialized version of the ResultContinuation object. I did that because ResultContinuation is a sealed class with no public constructor or properties. The only way to save it and reinstantiate it is to use XML serialization. The above code uses this serialized representation to pass the token down to the client, and then the client passes it back when it wants to retrieve the next page.

Check out the rest of the code to see how tasks are created, updated, and deleted. You may also be interested in the JavaScript code that manages the client-side view. This is the first time I’ve used Knockout.