As I have just published the Google DataTable .Net Wrapper project on CodePlex, the following post intends to be a quick introduction on the rationale on why this project has been created and its implementation.
Quick Project Background
While working on the implementation of the www.linktotweet.com web site, which is one of my side projects, I had to choose a way of displaying charts in order to show the statistics. I mainly had two options, either to return an image, that would be fully generated server side, or to use a bit of a different way and use one of the existing JavaScript libraries and generate those charts directly in the client’s browser.
As I wanted to free up the server resources from generating images at runtime, and to be honest, haven’t had experience with javascript charting libraries, I’ve chosen to go with the JavaScript approach. Among a large number of JavaScript libraries I’ve chosen the “Google Chart Tools”. Google Chart Tools is one of the most extensive libraries of charts on the web. It supports both HTML5 or SVG rendered charts. One of the good points of the Google Chart Tools is that is as well compatible with the iOS and Android. In any case, all the information about the Google Charts can be directly consulted on the official project page.
Why the Google DataTable .NET Wrapper?
As in my case of a web site project, there are mainly two ways that Google Chart Tools library uses to handle the data that would be later displayed:
- Data, directly generated, client side, on the page, which means directly in the JavaScript.
- Data prepared and then retrieved, i.e: by using a Ajax call, from the server
Let’s see both examples of how this can be done by looking at the client, JavaScript side:
Generating a chart with data generated directly on the client
In this example, the data has been generated directly in the JavaScript (the data.addRows(...) part. This is pretty much easy, but somehow cumbersome if you need to generate and return some complex dynamic data.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the DataTable directly in the javascript.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart =
new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Using Ajax in order to get the server side generated data
In this, second, JavaScript example, the data has been generated on the server and Ajax has been used to retrieve data from a RESTful service. In order to achieve this, a reference to jQuery needs to be added to the page.
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/Statistics/GetStatisticsForChart?messageCode=SomeCodeHere",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart =
new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
for more info on this particular usage, please check the google site.
Server Side generated content
When retrieving data from the server, the data transfer format has to be expressed in JSON and in order to generate a Google Charts compatible DataTable format, a specific “schema” has to be used. Below is an example of a DataTable that Google Chart Tools understand, and expressed in JSON.
{
"cols":
[
{"id":"", "label":"Topping", "pattern":"", "type":"string"},
{"id":"", "label":"Slices", "pattern":"", "type":"number"}
],
"rows":
[
{"c":[{"v":"Mushrooms", "f":null}, {"v":3,"f":null}]},
{"c":[{"v":"Onions", "f":null}, {"v":1,"f":null}]},
{"c":[{"v":"Olives", "f":null}, {"v":1,"f":null}]},
{"c":[{"v":"Zucchini", "f":null}, {"v":1,"f":null}]},
{"c":[{"v":"Pepperoni", "f":null}, {"v":2,"f":null}]}
]
}
Google DataTable .Net Wrapper to the rescue
Are you willing to manually generate the above JSON code for every single case? I wasn’t and therefore I created, what I called, Google DataTable .NET Wrapper, that could simplify drastically the Json generation by following a full POCO lightweight object model.
Let’s see it in action
using Google.DataTable.Net.Wrapper;
private DataTable GetDataTableJson()
{
DataTable dt = new DataTable();
//Act -----------------
dt.AddColumn(new Column(ColumnType.Number, "Year"));
dt.AddColumn(new Column(ColumnType.String, "Count"));
var row1 = dt.NewRow();
var row2 = dt.NewRow();
row1.AddCellRange(new[] {new Cell(2012, "2012"), new Cell(150, "150")});
row2.AddCellRange(new[] {new Cell(2013, "2013"), new Cell(100, "100")});
dt.AddRow(row1);
dt.AddRow(row2);
return dt.GetJson();
}
would result in the following generated JSON
{
"cols":
[
{"type": "number", "id": "Year"},
{"type": "string", "id": "Count"}
],
"rows":
[
{"c": [{"v": "2012", "f": "2012"}, {"v": "150", "f": "150"}]},
{"c": [{"v": "2013", "f": "2013"}, {"v": "100", "f": "100"}]}
]
}
Wrapping it all together
As you may see in the above example, the Google DataTable .Net Wrapper is a simple library that contains several classes:
- DataTable
- Column
- Row
- Cell
and that gives a great way of expressing the data in a strongly typed way, by offering the possibility to export the Json data in exactly the format that the Google Chart Library needs. This will make you avoid writing any specific code in order to transform your object data into JSON format.
Objects are lightweight and made very simple, so this should affect in any way the performance of your application.
What comes next?
There are still some unfinished things, as the “full” Google DataTable support. As the Google library supports a lot of different scenarios, especially when it comes to what Google calls “Property Map”, where additional data could be added to the Cell or the DataTable itself. For the time being this has been implemented as a single string, when in reality should be more a List of NameValue pair objects.
Project page
- Download the latest version of the source code
- Download the library
Get the library directly from NuGet:
PM> Install-Package Google.DataTable.Net.Wrapper
or get more information by following the NuGet library page: https://nuget.org/packages/Google.DataTable.Net.Wrapper
References:
- http://my.opera.com/tagawa/blog/list-of-javascript-charting-libraries
- http://javascripted.me/top-5-free-javascript-chart-libraries.html
- Google Charts DataTable Reference


Is there a complete working example. I don’t understand where to use the ” return dt.GetJson();”. Can you give me a full working project as sample code.
Hi Ammar,
As I get some time I will provide a full example (with a project).
In the meanwhile, dt.GetJson() is a function that has to be placed Server Side, depending on a project you are using, this would be a MVC Controller, Code behind, or a restful service. The idea is that JavaScript (client side) calls a method on the server that would return a string generated by the dt.GetJson().
I hope it is just a bit more clear?
cheers,
Zoran