Wednesday, 26 March 2014

Google Chart in Asp.net

Through this article, I'll try to explain how we can use Google charts for reporting purposes in ASP.NET web applications. Report generation is something quite common and we need to generate self explanatory and good looking reports to the users almost every time. “Images always speak more than words”. So instead of just showing the figures in our reports, we can let the users see diagrammatic charts which can help the users to analyze the whole data more quickly and easily. Though Microsoft itself has its charting controls for .NET, but we integrate it with other great technology by Google.
Google has its own, very awesome and simple application for charting purposes which we will be using here. I will request you to get a brief idea of what Google charts are, by visiting the following link:
So to brief stuff down, let’s look at one example. This may give you a better understanding of Google charts. To generate charts using “Google charts”, we need to pass the proper parameters.
Visit the below link:
In the chart, you can clearly see the chart title as “Amount Collection”. If you see the URL carefully, you’ll notice that the name has been passed by the URL, similarly the other details like the type of graph, axes, data on which chart is plotted, etc. all are passed through the URL only.
Now let’s go through all the parameters that we need to pass to get the required charts.
Parameter Description
cht The chart type. Google offers around a dozen different chart types, including line charts, bar charts, pie charts, and others.
chs The chart size. This value is expressed as chs=WIDTHxHEIGHT, where WIDTH and HEIGHT are the number of pixels wide and tall to draw the chart. E.g., chs=250x100. The maximum height and width is 1,000 pixels, and the product of the height and width cannot exceed 300,000 pixels.
chtt The chart title.
chd The chart data. When using this parameter, you must specify the data format. The Google Chart API allows for different data encodings. The simplest to use is text encoding and is denoted by the letter t. Following the encoding, place a colon (Smile | :) and then a comma-delimited list of data point values. The default text encoding requires that the data points be floating point values between zero (0.0) and one hundred (100.0). To correctly scale the data, convert each data point into a percentage of the largest data point. Ergo, the largest value will have a value of 100.0, whereas the others will be expressed in terms of a percentage of the largest – 50.0 for one that’s half as large as the largest, 25.0 for one that’s 25% of the largest, and so forth. To render a chart with data points of 10, 20, and 8, you’d send: chd=t:50,100,40. Note the t:, which indicates that the data is formatted using text encoding. You can alternatively use the text encoding method with data scaling, which allows data points of any positive or negative floating point number. With this approach, you must specify a scaling parameter (chds). The examples in this article use the default text encoding, limiting all data point values between zero and one hundred.
The above mentioned parameters are just the basic ones that you will need to plot charts. There are more advanced options that you can use as per your requirements.
Till now, we were just discussing about Google charts. As you are now having an idea of what Google charts, we can go forward with how we can implement these in our web application.
You can refer the below code for much better understanding. All I have done is that I have used an image control and the image path is the Google chart path. In the below example, we are trying to generate charts as per the options selected.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace WebApplication1
{
    public partial class graphs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            int count = 0;
            int count1 = 0;
            int maxvalue = 0;
            float amount = 0;
            string[] amounts = null;
            string[] months = null;
            string query = “”;
            if ((Convert.ToInt32(to_month.SelectedItem.Value) – 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1) > 0)
            {
                amounts = new string[Convert.ToInt32(to_month.SelectedItem.Value) - 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1];
                months = new string[Convert.ToInt32(to_month.SelectedItem.Value) - 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1];
                query = “select * from chart_table where month>=’” + 
  from_month.SelectedItem.Value + “‘ and month }
                StringBuilder chartUrl = new StringBuilder
        (“http://chart.apis.google.com/chart?chs=500×200&chtt=Amount%20Collection”);
                string connection = 
  System.Configuration.ConfigurationManager.ConnectionStrings
   ["ApplicationServices"].ConnectionString;
                SqlConnection con = new SqlConnection(connection);
                SqlDataAdapter da = new SqlDataAdapter(query, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
                maxvalue = Convert.ToInt32(ds.Tables[0].Rows[0][1].ToString());
                while (count1 {
                  if (maxvalue < Convert.ToInt32(ds.Tables[0].Rows[count1][1].ToString()))
                  {
                      maxvalue = Convert.ToInt32(ds.Tables[0].Rows[count1][1].ToString());
                  }
                  count1++;
                }
                chartUrl.Append(“&chxt=x,y”);
                chartUrl.AppendFormat(“&chxr=1,0,{0}”, maxvalue.ToString(“0?));
                chartUrl.AppendFormat(“&cht={0}”, Server.UrlEncode
    (chart_type.SelectedValue));
                while (count{
                    amount = (Convert.ToInt32(ds.Tables[0].Rows
   [count][1].ToString()) * 100) / maxvalue;
                    amounts[count] = amount.ToString();
                    months[count] = ds.Tables[0].Rows[count][2].ToString();
                    count++;
                }
                chartUrl.AppendFormat(“&chxl=0:|{0}”, String.Join(“|”, months.ToArray()));
                chartUrl.AppendFormat(“&chd=t:{0}”, String.Join(“,”, amounts.ToArray()));
                Image1.ImageUrl = chartUrl.ToString();
                Image1.Visible = true;
         }
    }
}
 
 
Google provided an open API for generating the charts which can be used in our commercial web applications. We can generate various graphs using the Google chart API.
The Google Chart API lets you dynamically generate charts. To see the Chart API in action, open up a browser window and copy the following URL into it:
http://chart.apis.google.com/chart?cht=p3&chd=s:hW&chs=250x100&chl=Hello|World The following types of charts are available:
  • Line Chart
  • Bar Chart
  • Pie Chart
  • Venn diagram
  • Scatter Plot
The following article demonstrates the usage of graph in ASP.NET.
Use the image tag and place the source there:
<img src="http://chart.apis.google.com/chart?cht=p3&chd=s:asR&chs=400x150&chl=A|B|C" /> We can pass a variety of parameters to enhance the graph. Following are a few:
Graph Title
We can place the chart title using:
e.g.: chtt=Welcome chts
Graph Style
We can place the graph tile color and size of the font:
chts for Title Style : color,size
e.g.: chts=225ff0,20
Graph Colors
We can have different colors:
chco for colors: one or many
e.g.: chco=ff0000,00ff00,0000ff

Passing the Data

The data can be passed using various encoding techniques like simple, text, etc. I have done the simple encoding for you in C#:
public string GenerateGraph() { //Get the Data to draw the graph DataTable dt = new DataTable(); dt = dtGraphData; //Get the max vals in the Data int maxval = GetMaxVal(dt); //SAMPLE: http://chart.apis.google.com/chart? // cht=p3&chs=400x200&chd=s:asR&chl=A|B|C string GReqURL = http://chart.apis.google.com/chart?chts=+ GTitleColor+","+GTitleSize+"&chtt="+GTitle+"&chco="+GColors+ "&cht=p3&chs="+GWidth+"x"+GHeight; //chts for Title Style : color,size //chtt for title text //chco for colors: one or many string simpleEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; string chartData = string.Empty; string chartLabels = string.Empty; StringBuilder strbchartData = new StringBuilder(); StringBuilder strbchartLabels = new StringBuilder(); strbchartData.Append("&chd=s:"); strbchartLabels.Append("&chl="); int strlen = simpleEncoding.Length - 1; foreach (DataRow dr in dt.Rows) { //Generate the chart DATA int arrVal = Convert.ToInt32(dr[2]); int len = strlen * arrVal / maxval; strbchartData.Append(simpleEncoding.Substring(len, 1)); //Generate the Chart Labels strbchartLabels.Append(dr[1] + "|"); } //Converting the string builder to string chartData = strbchartData.ToString(); chartLabels = strbchartLabels.ToString(); chartLabels = chartLabels.Substring(0, chartLabels.Length - 1); return GReqURL + chartData + chartLabels; } The code is written in C#. You can assign all the properties you want to assign and finally call the GenerateGraph method which returns the string. Below is the code sample. The entire article is explained using the PIE graph example. The remaining graphs can also be achieved using the same method.
DataTable dt = new DataTable(); //Get the Data the data table and pass it dt = GetGraphData(); PieGraph pg = new PieGraph(); pg.GraphColors = "5566AA"; pg.GraphHeight="125"; pg.GraphWidth="250"; pg.GraphTitle = "Welcome to Test Graph"; pg.GraphTitleColor = "112233"; pg.GraphTitleSize = "20"; pg.dtData = dt; GGReq = pg.GenerateGraph(); this.DataBind(); } DataTable GetGraphData() { SqlConnection con = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand("Select * from GraphSupp", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); return dt; } I took 3 cols id, description and the count and generated a string and assigned that to the image source.
This is to show how to pass data to the PI graph, we can also perform simple encoding for other graphs...

Steps for Generation of the Graph

  1. Create a DataTable which contains column-2 as labels and column-3 as Data
  2. Create an instance of PieGraph (refer to the text doc I have attached)
  3. Assign the properties
  4. Place the return string to the source of the image tag
  5. Graph is generated

Points of Interest

  1. Easy way of generation of graphs
  2. Less effort on the web server as there is no need to render the image using Drawing name space
  3. Enhanced look and feel and open to all
 

No comments:

Post a Comment