Monday, November 22, 2010

Google Charts API for ASP.NET

Google Visualization has provided a powerful set of JavaScripts which allows us to develop various graphs and charts. I think if we are developing something like dashboard or something like Google Analytic dashboard, then using Google Visualizations is amazing idea. In case of Asp.net we can simply develop a logic to use DataTables as input and Graph will be generated automatically. Again we can capture the click events for the graph and display alerts or run some JavaScript as per our logic (DemoCode).

In this article we will simply check out different graphs and its integration with asp.net. Check out following Screen shots.





Google Charts API can be implemented effectively in Asp.net, this is just a small part of actual assignment I did for the development of a dashboard.
Step 1: Understanding Table structure of Google API.Google Charts API accepts table as input and generate graphs accordingly. It takes Table in Following format. (for more information check out  Google References )


We should be careful while generating Table in HTML, i.e. while adding Rows and Columns in Google DataTable. Google Data Table creation looks as follows

var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Salary');
        data.addRows(4);
There are many things we can do with Google Table which I am not including in this article.

Check out following JavaScript code for creating Google Table and Adding data in it
var data = new google.visualization.DataTable();
   function setDataforGraph()
        {
         // Create and populate the data table.
       var raw_data =  [['INFOSYS', 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95]];
            var xAxis = ['05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'];

            data.addColumn('string', 'Date');
            for (var i = 0; i < raw_data.length; ++i) {
                data.addColumn('number', raw_data[i][0]);
            }
            
            data.addRows(xAxis.length);
            for (var j = 0; j < xAxis.length; ++j) {
                data.setValue(j, 0, xAxis[j].toString());
            }
            for (var i = 0; i < raw_data.length; ++i) {
                for (var j = 1; j < raw_data[i].length; ++j) {
                    data.setValue(j - 1, i + 1, raw_data[i][j]);
                }
            }
          
        }

We also need to include JavaScript sources, there are some packages Google Provides, as we are going to use this for Charts we include coreCharts
Add script file "http://www.google.com/jsapi"


Once we done with DataTable creation we go for the logic to display Charts. We need to call Google Function

function drawVisualization(Type) {

            // Create and draw the visualization.
            var targetDiv = document.getElementById('visualization');
            var chart;
            if(Type == "ColumnChart") chart = new google.visualization.ColumnChart(targetDiv);
            else if(Type == "PieChart") chart = new google.visualization.PieChart(targetDiv);
            else if (Type == "AreaChart") chart = new google.visualization.AreaChart(targetDiv);
            else if (Type == "BarChart") chart = new google.visualization.BarChart(targetDiv);
            else if(Type == "LineChart") chart = new google.visualization.LineChart(targetDiv);
            chart.draw(data);
            new google.visualization.events.addListener(chart, 'select', selectionHandler);

            function selectionHandler(e) {
                selection = chart.getSelection();
                for (var i = 0; i < selection.length; i++) {
                    var item = selection[i]; 
                    alert(data.getValue(item.row, 1));
                }
            }
        }

Above function can be called on any event. Which will generate Chart of Particular Type. Refer Demo Code. We can add selectionHandler to capture events on click of chart. Above function will give us value of the Item i.e. Data. Check out following image.


HTML Structure of form is something like below, where we have Div tag for Google Visualization.

At this point we are done with the Google Charts API usage in HTML. Now to make Google Charts work in asp.net we simply need to develop a logic in code behind which will enable us to Create GoogleDataTable.

To generate data in code behind we use string elements which we can simple get in JavaScript on page render.

public string x_Axis = string.Empty;
    public string graphTable = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            graphTable = getGoogleVisualizationStr(DemoDataTable);
            x_Axis = "'05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'";
        }
    }

We keep Demo Table in c# code, with same data values used in above table.
private DataTable DemoDataTable
    {
        get
        {
            DataTable DT = new DataTable();
            DT.TableName = "GENERAL";
            DT.Columns.Add(new DataColumn("Name", typeof(string)));
            DT.Columns.Add(new DataColumn("Data1", typeof(long)));
            DT.Columns.Add(new DataColumn("Data2", typeof(long)));
            DT.Columns.Add(new DataColumn("Data3", typeof(long)));
            DT.Columns.Add(new DataColumn("Data4", typeof(long)));
            DT.Columns.Add(new DataColumn("Data5", typeof(long)));
            DT.Columns.Add(new DataColumn("Data6", typeof(long)));
            DT.Columns.Add(new DataColumn("Data7", typeof(long)));
            DT.Columns.Add(new DataColumn("Data8", typeof(long)));
            DT.Columns.Add(new DataColumn("Data9", typeof(long)));
            DT.Columns.Add(new DataColumn("Data10", typeof(long)));
            DT.Rows.Add(new object[] { "INFOSYS", 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95 });
            return DT;
        }
    }

We write a simple code to generate rowData used in above lines of code.

private string getGoogleVisualizationStr(DataTable DT)
    {
        string googleVisualTable = string.Empty;
        googleVisualTable = "[";
        for (int i = 0; i < DT.Rows.Count; i++)
        {
            for (int j = 0; j < DT.Columns.Count; j++)
            {
                if (j == 0)
                {
                    googleVisualTable += "[ '" + DT.Rows[i][j] + "'";
                }
                else if (j == DT.Columns.Count - 1) googleVisualTable += "," + DT.Rows[i][j] + "]";
                else googleVisualTable += "," + DT.Rows[i][j];

            }
            if (i != DT.Rows.Count - 1) googleVisualTable += ",";
        }
        googleVisualTable += "]";
        return googleVisualTable;
    }
We replace our JavaScript code with
var raw_data = <%= graphTable %>
var xAxis = [<%=x_Axis %>];

Thats it we are done with development of Google Charts API for ASP.NET. Above code used data of only one company to keep things simple. To add more companies simply add it in data table. So that our graphs will look like




Download Democode for reference --> GoogleVisualizationDemo.zip
Submit this story to DotNetKicks

6 comments:

Maxime November 30, 2010 at 3:10 AM  

pitotDoes it use POST request or only GET ?
as a reminder, we are limiter to 2K in querystrings...

Ashish November 30, 2010 at 12:38 PM  

@Maxime
You can develop Logic in Code behind to convert it directly in googleTable format.

And use JavaScript to develop Charts.
Well it also depends on what kind of statistics you are looking for.
Let me know if you are facing any issue.

Killer January 16, 2012 at 12:29 PM  

Thanx this tutorial was a great help :).

blog.agile-code.com February 4, 2014 at 4:37 AM  

HI,
Very informative article. Indeed I was following a similar approach for creating the JSON related literals in the Google.DataTable.Net.Wrapper library.
Compile time code is way simpler than building strings.

Something I have written about here http://www.agile-code.com/blog/using-the-google-datatable-net-wrapper/

No Necesario September 25, 2014 at 4:30 AM  

The example code can not be downloaded, please you can upload it again

Thank you.