Skip to content
Zoran Maksimovic edited this page Apr 3, 2017 · 4 revisions

Currently through "Chart Tools", Google is offering a possibility to generate Javascript based charts directly in the browser. *

In general this could be achieved in two different ways:

  • Directly coding the javascript in order to display the chart on the page. This means everything gets executed on the client's browser.
  • Use the javascript, but download the data by using Ajax. This involves the server which would be responsible for returning the right data in order to generate the chart.

The Google DataTable .NET Wrapper library's aim is to address the second scenario, where the server side code is involved.

As I couldn't find an easy way to generate the needed Json formatted output directly in Microsoft.NET, this library has been created in order to accomplish this.

Getting Started

Lets see the scenario for which this library becomes really useful:

  1. You are using .NET
  2. You want to use the Google Chart Tools in order to display charts on your web page.
  3. You want to generate the needed data directly on the server, and enable the browser to execute perhaps an Ajax call, and return all the necessary data
  4. You want to be sure to have the type safety and not generate the Json as required by google by yourself

Lets see a basic example

Client Side

First of all, the web page should contain a reference to google visualization api's,

<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<!--Get the latest version of jquery -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']('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 });
    }
</script>

and all this will be visualized as part of the "chart_div"

<div id="chart_div" style="width: 900px; height: 500px;"></div>

Server Side

Here is where we create a Json string to be returned to the browser.

  1. Reference the Google.DataTable.Net.Wrapper.dll in your project, by simply using "Add reference" wizard, and you are ready to go.

Here is a possible implementation:

public string GetStatisticsForChart(string messageCode)
{
    //some repository that returns data....
    var data = _statisticsRepository.GetPerMessage(messageCode);

    //It simply returns a list of objects with Year and Count properties.
    var query = (from t in data
                    group t by new {t.TimeStamp.Year}
                    into grp
                    select new
                        {
                            grp.Key.Year,
                            Count = grp.Count()
                        }).ToList();

    //let's instantiate the DataTable.
    var dt = new Google.DataTable.Net.Wrapper.DataTable();
    dt.AddColumn(new Column(ColumnType.String, "Year", "Year"));
    dt.AddColumn(new Column(ColumnType.Number, "Count", "Count"));

    foreach (var item in query)
    {
        Row r = dt.NewRow();
        r.AddCellRange(new Cell[]()
            {
                new Cell(item.Year),
                new Cell(item.Count)
            });
        dt.AddRow(r);
    }
           
    //Let's create a Json string as expected by the Google Charts API.
    return dt.GetJson();
}

The output

{
	"cols": [
				{"type": "string", "id": "Year",  "label": "Year"}, 
				{"type": "number", "id": "Count", "label": "Count"}
			], 
	"rows": [
				{"c": [{"v": "2011"}, {"v": "1860"}] }, 
				{"c": [{"v": "2012"}, {"v": "2000"}] }
			]
}

Convert a System.Data.DataTable to Json

It is possible to convert an ordinary .NET DataTable into a Google DataTable. The code below shows a very easy conversion of a table with three columns

using (var sysDt = new System.Data.DataTable())
{
    sysDt.Columns.Add("firstcolumn", typeof(string));
    sysDt.Columns.Add("secondcolumn", typeof(int));
    sysDt.Columns.Add("thirdcolumn", typeof(decimal));
    sysDt.Locale = CultureInfo.InvariantCulture;
 
    var row1 = sysDt.NewRow();
    row1[0](0) = "Ciao";
    row1[1](1) = 10;
    row1[2](2) = 2.2;
    sysDt.Rows.Add(row1);
 
    var dataTable = sysDt.ToGoogleDataTable();    
     
    var json = dataTable.GetJson();
}

Convert a List into Google DataTable

This simple code shows how to use the extension method "ToGoogleDataTable() in order to conver the IEnumerable object into a DataTable.

var list = new[]()
                {
                    new {Name = "Dogs", Count = 5},
                    new {Name = "Cats", Count = 2}
                };
 
var json = list.ToGoogleDataTable()
               .NewColumn(new Column(ColumnType.String, "Name"), x => x.Name)
               .NewColumn(new Column(ColumnType.Number, "Count"), x => x.Count)
               .Build()
               .GetJson();

For multiple series chart please check the following post: * Chart with two series

Further information

For further information, please check the following blog-posts:

References

In order to check how the "Chart Tools" works please visit directly the official google web page

For more information and common issues check StackOverflow https://stackoverflow.com/search?q=Google.DataTable.Net.Wrapper