Dynamic Types Make Unit Testing JSON in ASP.NET MVC a Breeze!

by jmorris 18. October 2010 22:57

The new dynamic type in C# 4 was mainly added to offer simpler creation of objects using reflection and the ability to treat objects as they are no matter where they were created: COM interop, DLR, etc. It basically defers static typing until runtime. The object itself is statically typed, however the compiler bypasses compile-time static type checking until runtime.

One place where this kind of late bound typing is really useful is unit testing ASP.NET MVC action methods that return JSON via JsonResult. For example, given the following controller action method:


And the following unit test you’ll quickly discover that while you can see the values as a watch in Visual Studio or while debugging, you cannot actual run an assert on any of the members (Assert.AreEqual(1, data.FeedId) will throw an exception:


It should be relatively obvious as to why this will not work, notably anonymous types are internal to the assembly that they were created in and results.Data returns a System.Object. Using the dynamic keyword, one might assume that the we should be able to run asserts on the properties of the JSON result, but unfortunately, it’s not that simple:


The exception gives some subtle hints as to what the problem is:

'MyFantasyFootBallGuruTests.Controllers.AlertsControllerTests.GetCurrentPick2' failed: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'object' does not contain a definition for 'FeedId' at CallSite.Target(Closure , CallSite , Object )  at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) Controllers\AlertsControllerTests.cs(47,0): at MyFantasyFootBallGuruTests.Controllers.AlertsControllerTests.GetCurrentPick2()

Well it’s somewhat of a hint…the object does not contain a definition for ‘FeedId’ is caused by the fact that while we can see the values with the debugger, the reality is that the ‘object’ is really an anonymous type, which exists in the assembly containing the controller. Since anonymous types by definition are always internal to the assembly they are defined in, the runtime throws an exception. Fortunately, the fix is for this is easy.

When you create a new project (assembly) in Visual Studio, a “Properties” folder with a class called “AssemblyInfo.cs” is automatically created. This class contains attributes that define the metadata of the assembly: the name, description, title, whether or not the assembly is visible to COM components, the version, and other information related to the assembly. There is also another very important attribute to those wishing to test anonymous types in assemblies other than the assembly that the anonymous type is defined in: InternalsVisibleToAttribute.

The InternalsVisibleToAttribute makes types that are normally only visible in the defined assembly to other assemblies specified in the attribute. For instance:


Adding this attribute to the assembly that contains the controller classes, makes any anonymous types visible to the unit test assembly, MyFantasyFootballGuruTests. After adding this attribute, the unit tests will not only compile, but allow the properties of the anonymous type to be tested:



Tags: , , , , , ,

Unit Testing

A Couple of Useful JSON Viewers

by jmorris 19. May 2010 09:40

I recently stumbled upon this viewer from a comment on another blog: http://jsonviewer.stack.hu/

A quick google search and I found a few more JSON viewers -

  1. A Firefox add-on: https://addons.mozilla.org/en-US/firefox/addon/10869
  2. Another online viewer 'service': http://chris.photobooks.com/json/default.htm
  3. A standalone viewer and a VS2005 plugin:  http://jsonviewer.codeplex.com/

To bad the plugin from codeplex only looks like it supports VS2005 and hasn't been updated in 3 years :(

Tags: , , ,

Using Datatables.net JQuery Plug-in with WCF Services

by jmorris 17. May 2010 13:42

There are several JQuery plug-ins that provide the basic functionality of an html grid: paging, sorting, etc. In essence these plug-ins provide a consolidated display of the data and typically means of which to interact with the data (update, insert, delete, etc). I recently had the opportunity to work with the DataTables.net grid and have been very impressed.

The following post describes the steps I used to make the DataTables grid work in an ASP.NET Webforms environment using a WCF Service as an endpoint. I’ll also go over some of the pitfalls I ran into which required a bit of ‘tweaking’ to get things working smoothly. One cool thing was that for every roadblock, a workaround was quickly discovered. This is huge when investing any time or resources on any third party plug-in or control.

First up, if you are not aware of what the DataTables is, it’s a JQuery Plug-in that written by Allan Jardine. According to the DataTables website:

“DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. “

It offers a plethora of features including pagination, filtering, sorting, auto loading of data via Ajax, Fully theme-able by CSS, etc. The documentation on the DataTables website is thorough and the quality excellent. There are also forums…good stuff. Additionally DataTables is licensed dually under the GPL v2 License and the BSD license for those who inquire…

Here is an example of Datatables with built in JQuery UI theme support:

The WCF Service
Datatables allows you to either have client-side paging, sorting and searching, which is the default, or you can do it on the server. Doing it on the client is the simplest and easiest way to get up and running with Datatables, however you will quickly find that it leads to larger page sizes and longer initial load times as all of the data must be piped from the server before Datatables is ready.  Performing the actions on the server makes for much a much snappier and scalable UI, but it adds complexity.

In order to use a WCF service with DataTables, you have to both honor the signature that DataTables expects and the data must be returned in a format that DataTables expects. Fortunately this is relatively easy to do; you simple need to a) map the HTTP variables from the GET request and b) generate a JSON string matches a specific format.

The HTTP variables that DataTables will post are as follows:

Note that the websiteId and categoryId are custom variables and that for each column specified, additional variables will be posted for the following fields with a consecutive numerical postfix: bSearchable_0, bSearchable_1, bSearchable_2, etc.

For my example the following WCF service method was used:

Note that I only specified a subset of the parameters in the WCF method that Datatables posts with its GET request:

Too be honest, I do not know why Datatables sends so many (looks like one variable per option per column for most), but from the WCF service method perspective they are optional. Also, note that Datatables uses some form of Hungarian notation to qualify the variables type. While a bit confusing at first, it did help a bit when debugging. The variables that we did specify in the WCF service method signature will be used for sorting, filtering, paging, etc.

Datatables expects to receive a JSON object with a two dimensional array called “aData” from this service. Here is an example of the server output that Datatables will receive:

Where “d” is the wrapper type appended by WCF and from the Datatables website:


Basically, note that the service must correctly compute and return the “iTotalRecords”, “iTotalDisplayRecords” and the data in “aaData”. Also, the length of each data returned must match the DataTables jQuery definition provided on the web page where the data will be displayed.

Here is the complete code listing for the internals of the WCF service method:


Note that depending your architecture, this code may look considerable different. However the steps are same:

  1. Query the datastore based upon the passed in parameters
    1. Calculated paging values
    2. Column to search by
    3. Column to sort by
  2. Create a JSON return result matching the JSON structure defined above.

Another thing to note here is that Datatables does not send column names; it sends the ordinal of the column with respect to the table. In order to sort by a column or filter by a column, you need to resolve the ordinal to a column name of your datastore:


The GetSortFieldFormOrder(int order) returns a string column name based upon the ordinal of the column so that the datastore (in this case via a sproc call) can sort the data by the correct column.

The Convert(object record) method makes an array from the values of properties of an object: each becomes an “aaData” record that is returned and used by Datatables on the client.

Just an architecture note here: in my opinion there is too much “busy” work going on here at the service level. Ideally this will be refactored into your entities so that the behavior is encapsulated outside of your data “delivery”.

The Client Code
The client JQuery code for Datatables can be very simple or rather complex depending upon the formatting and features your situation requires. Below you will see the code that I used and I will explain the major initialization required for using Datatables with a WCF service.


Lines 4-6 I get a reference to the DOM element I will load into using a typical JQuery selector. Let me explain the relevant settings:

A.    I am using the Datatables built in support for JQuery UI Themes
B.    I am setting the “bServerSide” flag to true so that Datatables will use AJAX to get the data source
C.    The URL of the AJAX method to call for loading data
D.    Since I want to set some custom variables to post to my service method and I want to override the default HTTP POST method that Datatables uses for invoking the AJAX method, I am overriding the “fnServerData” callback with a custom implementation.
E.    Datatables uses POST be default, I overridden the AJAX method to use a GET
F.    The results from the server are then passed into the fnCallBack callback and Datatables can now render the results.

The target for the selector is a div element on an ASP.NET UserControl:


   kick it on DotNetKicks.com

Tags: , , ,

SerializationExceptions and DataContractJsonSerializer: XYZ Type is not expected

by jmorris 16. March 2010 12:47

I have been doing a bit of Web code where the state of an object must be persisted per Session, between HttpRequests within an HttpCookie. In the past I have stored data of this type in as an encrypted string of XML in the FormsAuthentication cookie and use XmlSerializer to serialize/de-serialize between the requests and responses, which ahas worked quite nicely. However, in this scenario I decided to persist as encrypted JSON string and use the DataContractJsonSerializer to do the serialization and de-serialization.

The DataContractJsonSerializer works similar to any other serializer, like XmlSerializer, and the code to do so is pretty simple:

However, I quickly ran into an issue while unit testing this code:

System.Runtime.Serialization.SerializationException: Type 'Genesis.Framework.Web.ADAM.Security.AdamPrincipal' with data contract name 'AdamPrincipal:http://schemas.datacontract.org/2004/07/Genesis.Framework.Web.ADAM.Security'is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

The problem is that while it seems rather obvious that the serializer should be able to simple use the interface definition to perform the serialization/de-serialization, this is simple not the case. You have to supply a list of “known types”, which are simply the implementation of the said interface. The serializer uses the known type(s) to determine which data contract to serialize or de-serialize to: it is the target type.


Alternatively, instead of adding a list of known types to the DataContractJsonSerializer constructor like I did above, you can adorn your types with the KnownTypeAttribute, which has the same effect. In this case I chose _not_ to ‘dirty up’ my types with attributes ;)

Jeff Morris

Tag cloud

Month List

Page List