You must have Visual Studio 2010 to use the bits. Downloading and installing the WCF Support for jQuery 10.10.27 release from wcf.codeplex.com will install Visual Studio templates, as well as copy reference files and samples to %ProgramFiles%\Microsoft SDKs\WCF Support for jQuery.
Visual Studio project template
Create a new project and choose the “WCF jQuery Service Application” template in the “Web” group:
The template creates a web application project that contains a WCF service (WcfJQueryService.cs) and a sample HTML page that demonstrates how to invoke that service with an Ajax call using jQuery (default.htm):
The project references include two assemblies that have been installed as part of the WCF Support for jQuery release (you get get the source code of these assemblies from the wcf.codeplex.com site). System.Runtime.Serialization.Json.dll contains the JsonValue component which facilitates operating on JSON data in an untyped manner (JsonValue is to JSON what XElement is to XML). JsonValue supports serialization and deserialization to the JSON format. It has already shipped in Silverlight before, now we are porting it with some enhancements to .NET Framework.
The WCF Support for jQuery package also includes an item template that allows a jQuery-enabled WCF service to be added to an existing web application project.
From jQuery client to WCF service
Let’s have a look at the WCF service to see what the programming experience is:
The method above is extending the WCF HTTP programming model available since .NET Framework 3.5 SP1 with support for JsonValue as the method parameter and return value type. If JSON or application/x-www-form-urlencoded data arrives in the body of the POST request, it will be deserialized into the JsonObject instance passed to the Post method. The JsonValue instance the method returns will be serialized into JSON format on the HTTP response.
The corresponding HTTP request with this data is shown below, with line 4 containing the complex ‘person’ structure serialized into an application/x-www-form-urlencoded format using the $.param() convention from jQuery:
Although jQuery Ajax calls use application/x-www-form-urlencoded format by default, it is very easy to serialize the request payload in JSON format instead. Using Douglas Crockford’s json2 serializer (line 4), one can make a jQuery call like this:
Which results in the following HTTP request:
A great feature of the JsonValue programming model in WCF is that regardless of the client’s choice of JSON or application/x-www-form-urlencoded as the serialization format for the request, WCF will deserialize and normalize the data into an instance of JsonValue. Given that, the application code may stay decoupled from the protocol.
So how does one access the data the client sent from the WCF service? JsonValue offers dictionary-like programming model. For example, to determine the favorite toy of the second child of the person, one could write the following code:
If the return type of a WCF method is JsonValue, the response content type is always application/json. Note that in line 5 above we are actually returning a string instance, but an implicit cast exists between a number of primitive data types and JsonValue. In this case the specific HTTP response would look as follows:
Surely enough, donkey is the favorite toy of John’s second child.
JsonValue 201: dynamic properties
JsonValue supports a few more interesting constructs that facilitate operating on untyped data.
First of all, there is support for dynamic properties, which is more than just a syntactic improvement over array indexers. The two lines below extract the same value from a JsonObject:
Given that the data received from the client has not been validated against a specific schema of a CLR type, one cannot be sure the JsonObject really contains the data the server application expects, or whether the object even has the correct structure. For example, a malicious client could try to send an arbitrary string in the “Age” field instead of a number, or could completely omit the Children array. In that case, the indexer APIs (line 1 above) would throw an exception as soon as the code attempts to access a non-existing property (which is consistent with the behavior of indexers in the .NET Framework in general). One would therefore have to write a lot of validation code before accessing the data in the JsonValue object using indexers, especially if the data hierarchy is deep.
The dynamic properties of JsonValue offer a much more convenient validation experience. One can “dot into” any level of a complex object without any exceptions being thrown, only to perform a test of the value’s existence and CLR type match at the very end, with a very Fluent-like experience.
You can imagine how this programming model is reducing the amount of code you need to write when navigating deep data hierarchies:
JsonValue 301: LINQ to JSON
Here is another useful feature JsonValue offers: LINQ to JSON. Using the ‘person’ object introduced above, let’s assume you are writing a method that is supposed to return the favorite toys of those children of the person whose name begin with ‘J’ (does this sound like a test from your SQL class?). Here is the code you could write:
There are several interesting properties of the code above:
- You don’t have to worry whether the ‘Children’ property exists on the ‘body’ JsonObject (line 3), or whether it is a JSON array. If it does not, the LINQ expression will just not return any matches. No exception is going to be thrown.
- You don’t have to worry whether the ‘Name’ property exists on a child object (line 4). Instead, you can provide a default name in the ReadAs method that will be returned in the absence of the property.
- Similarly, in case a child whose name starts with ‘J’ has been found, you don’t have to worry whether the child has a ‘BestToy’ property (line 5) – if she does not, you can just fall back to returning a ‘No favorite toy’ string.
In other words, writing compact and robust LINQ expressions against JSON data with unknown structure is easy.
I have only touched on the key features of the WCF support for jQuery release. Find out more in the dedicated documentation section on wcf.codeplex.com. Let us know what you think and help us shape the direction of this feature going forward.