C# dynamic object and JSON serialization with Json.Net


Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/


I’m working on a project where I don’t need a solid domain model as all the logic is handled by the client-side code using  javascript and various frameworks as SignalR, Knockout.js and jQuery.
That’s why I found myself unwilling to add dumb C# POCO objects just to handle JSON serialization and deserialization in the SignalR hub(s), and I turned to dynamic objects and Json.Net (starting from version 4.0)  to handle this tasks easily and quickly.


Let’s say that for example I want to send data to the browser. All I have to do is to create an ExpandoObject (my new favourite .Net class!) and serialize it using Json.Net “JsonConvert.SerializeObject()”.

Let’s see an example:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

And here is the output:


Json.Net offers a great way to deserialize a JSON string into a dynamic using the JObject (you can find it under the Newtonsoft.Json.Linq namespace and here the details).

Let’s see an example re-using the previous foo object:

dynamic foo = JObject.Parse(jsonText);
string bar = foo.Bar; // bar = "something"

And that’s it, really easy and yet really powerful.
In a more structured application, I would probably not use this trick as I would probably have all of my ViewModels and Domain Models objects ready to use in type safe serialization/deserialization operations, but that’s not always the case.

I hope this helps.


ChatR: just another chat application using SignalR


Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/


Update (30 November, 2012): David Fowler (SignalR co-creator) has made ChatR into an example application downloadable via Nuget to show SignalR beginners how to quickly build a chat web app.
He forked the project on GitHub and updated the code base to the latest version of the library, 1.0Alpha2, and then sent me a pull request that I accepted and merged into the master branch.
Therefore the code that you see now in the latest commit on the master branch is slightly different than the one shown in this post, but this is not a problem, you just need to go back in time in the history of the commits to find exactly what is shown here if you really want to, otherwise just dive into the new code!

Update (17 November, 2012): this blog article is related to version 0.5.2. In these days the SignalR team is working on version 1.0 and has released an Alpha. There are quite a lot of significant changes in the API, but the concepts at the basis still apply.
I hope to be able to post an update article when 1.0 is released.

There’s a lot of buzz these days around SignalR (http://signalr.net/) and more in general around real time communication techniques for the web (http://www.webrtc.org/).
There are many scenarios where real time can be embedded in web applications in a way that is actually useful for the user, but the most easy to understand scenario is the good old chat 🙂
That’s why today I’m going to write about…


A chat web application! Yes, I know it’s not the most original example, but it’s still a good starting point to excercise the fundamentals of the framework.
The user will be able to choose a username and then join the (single room) chat, where he/she will be able to chat with the others and see a list of currently connected users.
This list will obviously update itself everytime someone joins or disconnect the chat.

Source code and demo

As always the code for this tutorial is published on GitHub at https://github.com/vgheri/ChatR
A working demo is deployed on the fantastic AppHarbor at http://chatr-1.apphb.com  (if you want to run a test, simply load up new tabs… SignalR is not relying on Sessions so it will be safe). 


This project relies on Asp.Net MVC 3 for the general architecture and the basic client-server communication.
As anticipated, I’ll be using SignalR for real time client-server communication, Twitter’s Bootstrap for basic UI layout and CSS and Knockout Js (knockoutjs.com) to automatize the view.

Before starting, I’d like to spend a few words about SignalR: it’s growing up as a solid library to use in order to build production code and it’s dead easy to use (https://github.com/SignalR/SignalR/wiki) once you grasp the fundamentals (which I’ll cover later on). It not only gets the job done, but also sports an awesome client-server async communication pattern, that makes really easy to invoke methods from Js to C# and viceversa (there is even someone who proposed to use it for general purpose communication http://www.novanet.no/blog/yngve-bakken-nilsen/dates/2012/7/clean-up-your-mvc-app-with-signalr/)
If you are interested in understanding more about the internals, I suggest you clone the repository on GitHub (https://github.com/SignalR/) and read something like http://ayende.com/blog/93185/reviewing-signalrndash-part-ii.


This application will feature a 1-click process to join the chat:

Step 1: landing page with a form to enter username
Step 2: chat page

The landing page is really simple, just a few text elements and an HTML form with an input text and a submit button that will trigger a HTML POST handled by the server via a MVC action.


I’m going to use 2 objects as Domain models and 1 repository object to store users currently connected to the system.
Let’s see them briefly:
ChatUser has two properties, Id and Username. The former uniquely identifies a client during a session and is assigned by SignalR.
ChatMessage is super easy and has a minimal set of properties: username (I could have used the ChatUser object, but because I’m displaying just a username and not the user id, I chose to transfer the minimum set of information), content and timestamp.
InMemoryRepository implements the Singleton pattern and helps clients retrieve the list of users.

Basic UI structure

Super simple and clean: a title bar on the top of the page that holds the name of the app, a container on the left that holds the usernames of currently connected users, a container, side by side with the previous one, that holds the chat messages and below an input box to enter a message with a submit button.
All the client-server communication round-trips here are handled by SignalR.
To dynamically update the UI, I’ve used Knockout Js and its data-binding declarations.

Javascript namespace and Knockout view models

I chose to create a separate Js file to declare a namespace and the Knockout viewmodels.
Therefore I created a separate folder called “Js” and a javascript file called chatR.js.
The code is pretty straightforward, as you can see:

The rest of the javascript code is inside chat.cshtml as I needed to access the Model binding engine to retrieve the username chosen by the user.


Server side code

Let’s start with the server side part of SignalR.
Do  you remember what I mentioned earlier in the post, that this library sports a great communication pattern that makes really easy to call C# methods from Javascript and viceversa? Well, the C# methods that we can call from the client side are those declared (as public) in the so called Hub.
What is a Hub? Well, a Hub is an abstraction that, to cite the Wiki,  “provides a higher level RPC framework over a PersistentConnection. If you have different types of messages that you want to send between server and client then hubs is recommended so you don’t have to do your own dispatching”.
SignalR offers two options to build a RTC app, leaving to the developer the choice between two built-in objects: Persistent Connections and Hubs.
It took me a while to fully understand what are the differences between these two, and why choose one over another.
Basically Hubs allow you to dispatch whatever object you want to the server, taking care of JSON serialization and deserialization, integrate model binding and are easier to setup, as you won’t have to write additional code to manually register additional routes (the SignalR specific routes). (You may want to read this question on SO, with words from David Fowler, creator of SignalR:  http://stackoverflow.com/questions/9280484/signalr-why-choose-hub-vs-persistent-connection).
I think it’s pretty safe to say that if you are writing a common web application or .Net application, you’ll be fine with Hubs.

N.B It’s imporant to note that Hubs are created on a “per request” basis, so no static stuff in it should be declared.

To start with, create a Hubs folder and create a new class that derives from Hub.
Here I called mine “ChatHub” and I defined the methods that will be used by the clients:
GetConnectedUsers: retrieves the list of currently connected users
Joined: fired when a new client joins the chat. We add the user to the repository and notify all the clients (even the newly joined) that this new client connected.
Send: broadcasts the message to all the clients (plus some extra work, like formatting links and youtube urls embedded in the messages, showing them as active links and embedded video player respectively. This part is mostly taken by the Jabbr codebase, thanks again David Fowler 🙂 )

Here’s the code:

As you can see, there’s something more: this class implements an interface called IDisconnect, part of SignalR, which allows us to handle the Disconnect() event fired when a user leaves the application. Again what we do here is remove the user from the repository and notify the other clients of the event.
There is another interface, called IConnected, that allows us to catch connection events like Connect and Reconnect, but I chose not to use them because unfortunately (at least in Connect) the round-trip state (see https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client-Hubs) is not available, therefore I cannot access the state set on the Hub with information like the username set on the client that caused the event to fire.
Later on I’ll explain in more detail with code.
This is also the reason why I have a Joined event handler, because I need an event handler, fired after the Connect event, where I can access the round-trip state. Just for the record, Jabbr uses the same philosohpy, not implementing IConnected.
Finally, as you can see almost all of the methods have a void return type, but one: GetConnectedUsers has a ICollection<ChatUsers> return type and this means that only the client invoking the method will get the data back and furthermore the library will handle the JSON serialization and deserialization of the collection.
Alternatively I could have used Caller.callback and set a void return type to the method.

Client side code

On the client side, the first important thing to note is the order of the script references:
1) jQuery 2) jQuery.signalR 3) <script src=”signalr/hubs” type=”text/javascript”></script>

The last one is important because navigating to /signalr/hubs will dynamically generate the script based on the hubs declared on the server. Each hub on the server will become a property on the client side $.connection, e.g. $.connection.myHub.

Let’s see now how to hook up the client and the server:

It’s important to note that all Hub names (methods and class name) are in  camelCase, so for example
var chatHub = $.connection.chatHub;   is creating the proxy to invoke server code.

The next statement,
chatHub.username = currentUser.username;
is setting the round-trip state on the Hub, in this case I’m setting the username so that it will be accessible from the server and I’ll be able to add this user to the list of currently connected clients.

Following we have client-side event handlers, as invoked by the server (remember? Clients.onMessageReceived(message); )

We also apply knockout bindings so that the UI will start updating itself as the ViewModels change.
Finally we have the code block to start the SignalR connection and invoke two Hubs method:

// Step 1: Start the connection
// Step 2: Get all currenlty connected users
// Step 3: Join to the chat and nmotify all the clients (me included) that there is a new user connected
            .done(function () {
                              .done(function (connectedUsers) {
                                   ko.utils.arrayForEach(connectedUsers, function (item) {
                                      users.contacts.push(new chatR.user(item.Username, item.Id));
                               }).done(function () {

method $.connection.hub.start provides two callbacks, done and fail.
So in the code above I’m saying that if the connections is successfully estabilished, we can now try to retrieve the list of connected users and if this worked too, we can notify all the clients that this new client connected via chatHub.joined().
At this point the round-trip state will be available and therefore we will be able to register a new User, along with its connection ID and username.

One final note: by default DateTime is serialized by SignalR using ISO8601 format (http://en.wikipedia.org/wiki/ISO_8601), which is ok to parse for Chrome and latest browsers, but, guess what?, not for IE 9 and older versions. That’s why I had to search the web for a nice and quick solution, that you can find in the source code on GitHub.

Useful links

ChatR on GitHub: https://github.com/vgheri/ChatR
ChatR on AppHarbor: http://chatr-1.apphb.com
SignalR Wiki: https://github.com/SignalR/SignalR/wiki/Hubs
Hubs vs Persistent Connections: http://stackoverflow.com/questions/9280484/signalr-why-choose-hub-vs-persistent-connection
Useful tutorial: http://www.amazedsaint.com/2011/11/introduction-ksigdo-knockout-signalr-to.html
Jabbr on GitHub: https://github.com/davidfowl/JabbR