Tuesday, 25 October 2011

Silverlight, JSON and dynamic types...

Todays Dynamics 2011 task was to investigate using JSON within a Silverlight control. I started this task with high levels of excitement being new to the whole restful/JSON scene. Yes, I know, I am a bit of a late-comer here! The purpose of this task was to create a generic control I could put on a Dynamics CRM Form. This control was going to be driven by data from an external restful service. I don't want to have to reconfigure this control every time my data changes, so the purpose is to drive the label and value from this external source. So, this isn't about communicating with a Dynamics database using OData/JSON.

A quick google on how I do this results in me writing the following snippet:

var proxy = new WebClient();
proxy.OpenReadCompleted += proxy_OpenReadCompleted;
proxy.OpenReadAsync(new Uri("restfulurl"));

// Calling the following method...
private void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
var strm = new StreamReader(e.Result);
string jsonText = strm.ReadToEnd();
// ... etc

This is where I hit my first road block: Cross site scripting. I spent quite a while on that, and still haven't figured out what I'm going to do, so I'm going to save that for another post. Plus, this really boils down to a Dynamics 2011 cloud issue, so let's move on. If you're not doing this via Dynamics 2011 then you should be able to do the above in a standard Silverlight control. For now I shall spoof the JSON by hardcoding the string...

Next, how do we parse this into a dynamic type? In C# 4.0 we can do some really nice stuff like this:

using System.Web.Script.Serialization;


JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize(jsonText);

Roadblock 2... JavaScriptSerializer was depreciated after Silverlight 1.1... HRMPH!

Silverlight, sometimes I hate you...

After countless searches and getting very close to embarking on a journey to build a JSON parser... I'm going to give a call out to a great blog post by jprichardson here. Saved me a few days effort, cheers mate! I quickly grabbed this source from GIT, built it, and stuck the silverlight libraries into my project. Now I do this:

var jsp = new JsonParser();
dynamic json = jsp.Parse(jsonText);

Whazzam, I have dynamic object from my JSON!

I have to say though, the deeper I dig into Silverlight the more shocked I am at the little things that take so much effort...