In this section, we'll show you how to use FusionCharts and C# (ASP.NET) to plot charts from data contained in a database. We'll create a pie chart to show "Production by Factory" using:

  • dataXML method first.
  • Thereafter, we'll convert this chart to use dataURL method.

For the sake of ease, we'll use an Access Database. The database is present in Download Package > Code > C# > DB folder. You can, however, use any database with FusionCharts including MS SQL, Oracle, mySQL etc.

Before you go further with this page, we recommend you to please see the previous section "Basic Examples" as we start off from concepts explained in that page.

The code examples contained in this page are present in Download Package > Code > C# > DBExample folder. The Access database is present in Download Package > Code > C# > DB. To view the solution you need to create a blank solution using your ASP.NET editor, copy or import all files to the solution and run it from there.

 
Database Structure
Before we code the ASP.NET pages to retrieve data, let's quickly have a look at the database structure.

The database contains just 2 tables:

  1. Factory_Master: To store the name and id of each factory
  2. Factory_Output: To store the number of units produced by each factory for a given date.

For demonstration, we've fed some dummy data in the database. Let's now shift our attention to the ASP.NET page that will interact with the database, fetch data and then render a chart.

 
Building the ASP.NET Page for dataXML Method
The ASP.NET page for dataXML method example is named as BasicDBExample.aspx (in DBExample folder). It contains the following code (GetFactorySummaryChartHtml() method from code behind page also reproduced below):

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="BasicDBExample.aspx.cs"
Inherits="DBExample_BasicDBExample" %>

<HTML>
 <HEAD>
  <TITLE>FusionCharts - Database Example </TITLE>
  <SCRIPT LANGUAGE="Javascript" SRC="../FusionCharts/FusionCharts.js"></SCRIPT>
 </HEAD>
 <body>
   <form id='form1' name='form1' method='post' runat="server">
      <%=GetFactorySummaryChartHtml()%>
   </form>
 </body>
</HTML>

Code Behind page:

public string GetFactorySummaryChartHtml()
{
    //In this example, we show how to connect FusionCharts to a database.
    //For the sake of ease, we've used an Access database which is present in
    //../App_Data/FactoryDB.mdb. It just contains two tables, which are linked to each
    //other.

    //xmlData will be used to store the entire XML document generated
    StringBuilder xmlData=new StringBuilder();

    //Generate the chart element
    xmlData.Append("<chart caption='Factory Output report' subCaption='By Quantity'     pieSliceDepth='30' showBorder='1' formatNumberScale='0' numberSuffix=' Units'>");

    //Create recordset to get details for the factories
    string factoryQuery = "select a.FactoryId,a.FactoryName,sum(b.Quantity) as TotQ from     Factory_Master a,Factory_Output b where a.FactoryId=b.FactoryID group by a.FactoryId,a.FactoryName";
    DbConn oRs = new DbConn(factoryQuery);

    //Iterate through each record
    while (oRs.ReadData.Read()){
        //Generate <set name='..' value='..' />
        xmlData.AppendFormat("<set label='{0}' value='{1}' />",oRs.ReadData["FactoryName"].ToString(), oRs.ReadData["TotQ"].ToString() );
    }

    oRs.ReadData.Close();
    //Close chart element
    xmlData.Append("</chart>");

    //Create the chart - Pie 3D Chart with data from xmlData
    return FusionCharts.RenderChart("../FusionCharts/Pie3D.swf", "", xmlData.ToString(), "FactorySum", "600", "300", false, false);


}


The following actions are taking place in this code:

  1. We first include DataConnection and InfoSoftGlobal namespace. DataConnection contains the connection parameters to connect to database.
  2. Next, we include FusionCharts.js JavaScript class to enable easy embedding of FusionCharts and call GetFactorySummaryChartHtml() method contained in code behind page.
  3. In GetFactorySummaryChartHtml() function, we then open a connection to database and retrieve the data as per the SQL passed.
  4. Thereafter, we generate the XML data document by iterating through the recordset and store it in xmlData variable.
  5. Finally, we render the chart using FusionCharts.RenderChart() method and pass xmlData as dataXML.

When you now run the code, you'll get an output as under:

 
Converting the example to use dataURL method

Let's now convert this example to use dataURL method. As previously explained, in dataURL mode, you need two pages:

  1. Chart Container Page - The page which embeds the HTML code to render the chart. This page also tells the chart where to load the data from. We'll name this page as Default.aspx.
  2. Data Provider Page - This page provides the XML data to the chart. We'll name this page as PieData.aspx

The pages in this example are contained in Download Package > Code > C# > DB_dataURL folder.

 
Chart Container Page - Default.aspx
Default.aspx contains the following code (with code behind page) to render the chart:
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default.aspx.cs" Inherits="DB_dataURL_Default" %>
<HTML>
 <HEAD>
  <TITLE>FusionCharts - dataURL and Database Example </TITLE>
  <SCRIPT LANGUAGE="Javascript" SRC="../FusionCharts/FusionCharts.js"></SCRIPT>
 </HEAD>
 <body>
    <form id='form1' name='form1' method='post' runat="server">
      <%=GetQuantityChartHtml()%>
   </form>
 </body>
</HTML>

Code behind:
public string GetQuantityChartHtml()
{
   

   //In this example, we show how to connect FusionCharts to a database
   //using dataURL method. In our other examples, we've used dataXML method
   //where the XML is generated in the same page as chart. Here, the XML data
   //for the chart would be generated in PieData.aspx.

   //To illustrate how to pass additional data as querystring to dataURL,
   //we've added an animate property, which will be passed to PieData.aspx.
   //PieData.aspx would handle this animate property and then generate the
   //XML accordingly.

   //For the sake of ease, we've used an Access database which is present in
   //../App_Data/FactoryDB.mdb. It just contains two tables, which are linked to each
   //other.

   //Variable to contain dataURL
   //Set DataURL with animation property to 1
   //NOTE: It's necessary to encode the dataURL if you've added parameters to it

   String dataURL = Server.UrlEncode("PieData.aspx?animate=1");

   //Create the chart - Pie 3D Chart with dataURL as strDataURL
   return FusionCharts.RenderChart("../FusionCharts/Pie3D.swf", dataURL, "", "FactorySum", "600", "300", false, false);


}

In the above code, we're:

  1. Including FusionCharts.js JavaScript class
  2. Create the dataURL string and store it in dataURL variable. We append a dummy propery animate to show how to pass parameters to dataURL. After building the dataURL, we encode it using Server.UrlEncode function.
  3. Finally, we render the chart using RenderChart() method and set dataURL as dataURL.
 
Creating the data provider page PieData.aspx
PieData.aspx contains the following code to output XML Data:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using DataConnection;

public partial class DB_dataURL_PieData : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    //This page generates the XML data for the Pie Chart contained in
    //Default.aspx.

    //For the sake of ease, we've used an Access database which is present in
    //../App_Data/FactoryDB.mdb. It just contains two tables, which are linked to
    //each other.

    //xmlData will be used to store the entire XML document generated
    StringBuilder xmlData = new StringBuilder();

    //Default.aspx has passed us a property animate. We request that.
    string animateChart;
    animateChart = Request["animate"];
    //Set default value of 1
    if (animateChart != null && animateChart.Length == 0)
    {
        animateChart = "1";
    }

    //Generate the chart element
    xmlData.AppendFormat("<chart caption='Factory Output report' subCaption='By Quantity' pieSliceDepth='30' showBorder='1' formatNumberScale='0' numberSuffix=' Units' animation='{0}'>", animateChart);

    //create recordset to get details for the factories
    string query = "select a.FactoryId, a.FactoryName, sum(b.Quantity) as TotQ from .Factory_Master a, Factory_Output b where a.FactoryId=b.FactoryID group by a.FactoryId, a.FactoryName";
DbConn oRs = new DbConn(query);

    //Iterate through each factory
    while (oRs.ReadData.Read())
    {
        //Generate <set name='..' value='..' />
        xmlData.AppendFormat("<set label='{0}' value='{1}' />",                
            oRs.ReadData["FactoryName"].ToString(), oRs.ReadData["TotQ"].ToString());
    }
        oRs.ReadData.Close();

    //Close chart element
    xmlData.Append("</chart>");

    //Set Proper output content-type
    Response.ContentType = "text/xml";
    //Just write out the XML data
    //NOTE THAT THIS PAGE DOESN'T CONTAIN ANY HTML TAG, WHATSOEVER

    Response.Write(xmlData.ToString());

 }
}

In the above page:

  1. We first request the animate property which has been passed to it (from dataURL)
  2. We generate the data and store it in xmlData variable
  3. Finally, we write this data to output stream without any HTML tags.

When you view this page, you'll get the same output as before.

 
Inside DataConnection Namespace
We have used DataConnection Namespace in the above code and in all subsequent Database examples. Using this class we establish connection to the MS Access database with ADO.NET component. Let's go through the lines of code inside this class:
 

using System;
using System.Data;
using System.Data.Odbc;
using System.Web;
using System.Configuration;

namespace DataConnection
{
/// <summary>
/// DataBase Connection Class.
/// </summary>

  public class DbConn
  {

    // Create a database Connection. using here Access Database
    // Return type object of OdbcConnection

    public OdbcConnection connection;
    public OdbcDataReader ReadData;
    public OdbcCommand aCommand;
    /// <summary>
    /// Data Connection and get Data Reader
    /// </summary>
    /// <param name="strQuery">SQL Query</param>

    public DbConn(string strQuery)
    {
        // MS Access DataBase Connection - Defined in Web.Config
        string connectionName = "MSAccessConnection";

        // SQL Server DataBase Connection - Defined in Web.Config
        //string connectionName = "SQLServerConnection";

        // Creating Connection string using web.config connection string
        string ConnectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
        try
        {
            // create connection object
            connection = new OdbcConnection();
            // set connection string
            connection.ConnectionString = ConnectionString;
            // open connection
            connection.Open();
            // get reader
            GetReader(strQuery);
        }
        catch (Exception e)
        {
            HttpContext.Current.Response.Write(e.Message.ToString());
        }

    }

    // Create an instance dataReader
    // Return type object of OdbcDataReader
    /// <summary>
    /// Get Data Reader
    /// </summary>
    /// <param name="strQuery">SQL Query</param>

    public void GetReader(string strQuery)
    {
        // Create a Command object
       aCommand = new OdbcCommand(strQuery, connection);

        // Create data reader object using strQuery string
        // Auto close connection

        ReadData = aCommand.ExecuteReader(CommandBehavior.CloseConnection);

    }

  }
}

 
What it does:
  • Set up Connection as per the connection string defined in web.config file.

    <connectionStrings>
        <add name="MSAccessConnection" providerName="System.Data.Odbc" connectionString="Driver={Microsoft Access Driver (*.mdb)};Dbq=|DataDirectory|\FactoryDB.mdb"/>
    </connectionStrings>



    To change your connection to any other database server, you only need to setup web.config file.

  • The code to connect to SQL Server Database is also given in comment form. To connect to SQL Server you have to activate the corresponding code.
  • It accepts SQL Query, executes it and returns the result as ASP.NET DataReader object -ReadData.