Working with FusionCharts using ASP.NET
 
Published: 07 Jun 2011
Unedited - Community Contributed
Abstract
Nowadays, users are constantly looking for more intuitive user interfaces. Because of this, it is vital to develop ASP.NET applications with diagrams such as Charts. FusionCharts enables you to plug-in several charts from a wide range of sources easily with a small amount of code. In this article, Anand examines the usage of FusionCharts in a step-by-step manner using three different scenarios. He initially examines the plotting of charts using the data from an XML file and also demonstrates the same using the values entered by users. Finally, Anand delves deep into the database connectivity aspects using an Access 2010 database with the help of relevant source code examples and screenshots.
by Anand Narayanaswamy
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 42369/ 25

Introduction

Presenting facts in chart format helps users to decipher the subject matter easily, especially for those who build applications with reports. The .NET Framework 4.0 does not provide any control to create charts. However, many third party vendors have developed products with which developers can incorporate different type of charts into their ASP.NET applications. FusionCharts is one such product and is developed by FusionCharts located in India. In this article, you will learn the various ways by which you can implement FusionCharts into your ASP.NET applications in a step-by-step manner.

Getting Started

In order to work with FusionCharts, you should first download a fully functional evaluation version from www.fusioncharts.com. You then need to extract the contents of the ZIP file package. It contains the required files required to build charts including sample applications in all supported languages.

The core library is contained in FusionCharts.DLL file located under Code/CS folder. The FusionCharts directory contains the various types of charts which you can use to build applications. FusionCharts is completely code intensive and you have to create charts only using code.

As regards the text editor, Notepad is sufficient for development purposes. However, I highly recommend you to make use of either Visual Studio 2010 or Visual Basic 2010 Express Edition since you can manage the development of charts easily. I assume that you have installed any one of these tools since the explanations I have covered in this article make use of Visual Studio 2010.

Creating Charts from an XML File

Below are a series of steps you have to follow to create charts from an XML file:

1.   Start Visual Studio 2010

2.   Select File | New | Web Site and choose ASP.NET Empty Web Site and Visual C# from the Installed Templates section.

You need to add data somewhere to create a chart. For the purpose of this walkthrough, we will make use of an XML file.

3.   From within Visual Studio 2010, select Website | Add New Item | XML File and click Add button. A new file will be created inside the Solution Explorer. I will use the following data for this example.

<chart caption='Indian Premier League Points' xAxisName='Teams' yAxisName='Points' 
  showValues='0' formatNumberScale='0' showBorder='0'>
  <set label='Mumbai Indians' value='16' />
  <set label='Chennai Super Kings' value='14' />
  <set label='Kolkata Riders' value='12' />
  <set label='Bangalore Royals' value='14' />
  <set label='Kochi Tuskers' value='10' />
  <set label='Kings XI Punjab' value='10' />
</chart>

You should rename the XML file to something which is understandable.  As I mentioned above, you should copy folders named bin and FusionCharts from Code/CS folder to your working directory. Select the path inside the Solution Explorer and select Refresh Folder option. You should view the copied folders inside the explorer window.

4.   Add a button and Literal Control from Visual Studio Toolbox to The Design view of Default.aspx file. 

Before proceeding further, you should call FusionCharts.js file located inside FusionCharts folder.

<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>

The above code should be placed inside the Head section.

5.  Double Click Button control and add the following piece of code

Literal1.Text = FusionCharts.RenderChart("FusionCharts/Column3D.swf", 
"XMLFile.xml", "", "myFirst", "700", "500", false, true);

As you can see, we call the RenderCharts() method which accepts several arguments. The shockwave file contains elements for drawing charts. You can increase or decrease the height and width of the chart by altering the values.

That's it. You can now execute the project. The chart appears immediately after clicking the Button control as shown below.

Figure 1

You can also place the code inside Form_Load() event so that the chart will be displayed upon loading of the application.

Creating Charts using Form Data

Forms are widely used to gather inputs from visitors. FusionCharts has the ability to plot charts using the data entered on the forms. The steps mentioned below examine the steps in detail.

1.   Create an ASP.NET file by selecting Website | Add New Item option and add a reference to FusionCharts.js file under the <head> section as shown below

<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script> 

2.   You can add Form controls by creating a table from within Visual Studio 2010 (Table | Insert Table) as shown below.

Figure 2

3.   Double click the Button control and add the following line of code:

StringBuilder xmlData = new StringBuilder();
xmlData.Append("<chart caption='IPL Points' subCaption='For Season 2011 so far'     
    showPercentValues='1' pieSliceDepth='30' showBorder='1'>");
xmlData.AppendFormat("<set label='Mumbai' value='{0}' />", txtMumbai.Text);
xmlData.AppendFormat("<set label='Chennai' value='{0}' />", txtChennai.Text);
xmlData.AppendFormat("<set label='Kochi' value='{0}' />", txtKochi.Text);
xmlData.Append("</chart>");
Literal1.Text = FusionCharts.RenderChart("FusionCharts/Pie3D.swf", "", 
xmlData.ToString(), "Sales", "500", "300", false, false);

As you can see above, the values captured from the form are appended to an XML file and the chart is drawn by calling the RenderChart() method. We have created an object of the StringBuilder class and then created the XML file using the Append() and AppendFormat() methods. Finally, a literal control has been added and the chart is plotted. The final output will look like as shown in figure given below.

Figure 3

Creating Charts from a Database

In order to build charts from a database, you need to create a database and add data to it. FusionCharts supports typical database formats such as Microsoft Access and SQL Server 2008; however, for the purpose of this article, I have created an MS Access 2010 database. You can’t call data directly from the database fields. Instead, you need to convert the database fields into XML. The steps given below examine the whole procedure in detail:

Step – 1: Creation of Database

1.   Open Microsoft Access 2010 and double click Blank Database template

2.   Right click Table1 under Tables section, select Design View and enter the fields and its data type. You have to provide a name for the table if prompted.

3.   Save the design view and enter few data to the fields.

4.   Place the database inside App_Data folder. You can create this folder if it doesn’t exist.

Step – 2: Establishing Database Connection

In order to connect ODBC connectivity, you need to create a new file named DbConn.cs and add the following line of code. You should place the file inside App_Code folder.

using System;
using System.Data;
using System.Data.Odbc;
using System.Web;
using System.Configuration;
namespace DataConnection
{
    public class DbConn
      {   
        public OdbcConnection connection;
        public OdbcDataReader ReadData;
        public OdbcCommand aCommand;
        public DbConn(string strQuery)
        {
            string connectionName = "MSAccessConnection";
            string ConnectionString = 
ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            try
            {
                connection = new OdbcConnection();
                connection.ConnectionString = ConnectionString;
                connection.Open();
                GetReader(strQuery);
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write(e.Message.ToString());
            }
        }
        public void GetReader(string strQuery)
        {
            aCommand = new OdbcCommand(strQuery, connection);
            ReadData = aCommand.ExecuteReader(CommandBehavior.CloseConnection);
        }
      }
}

In the above code, we have created an object of OdbcConnection, OdbcDataReader and OdbcCommand classes. You can also see that a function named DbConn which accepts the SQL Query argument has been created and the appropriate code has been added to read and execute the query.

If you are using SQL Server 2008 database, then modify the line of the above code as follows:

string connectionName = "SQLServerConnection";

Step – 3: Adding Libraries

FusionCharts.dll is the core assembly file which you need to include in your bin folder.

Step – 4: Placing Charts

FusionCharts ships with numerous charts in shockwave flash format. You need to include the folder named "FusionCharts" located inside the product package file into your working directory. This folder also contains a FusionCharts.js file which you need to call from your ASP.NET application.

Step – 5: Creating configuration file

Web.Config is one of the most important files in every ASP.NET application. It will have relevant parameters for database connection and other information.

Add the following code by creating a new web.config file. If you create the file from Visual Studio 2010, you only need to provide the code within <connectionStrings></connectionStrings> tag.

<?xml version="1.0"?>
<configuration>
      <appSettings/>
      <connectionStrings>
<add name="MSAccessConnection" providerName="System.Data.Odbc" 
connectionString="Driver={Microsoft Access Driver (*.mdb, 
*.accdb)};Dbq=|DataDirectory|\ipl.accdb"/> 
  </connectionStrings>
      <system.web>      
            <compilation debug="true">
            </compilation>
            <authentication mode="Windows"/>
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
      </system.web>
</configuration>

You need to add following code if you are using the SQL Server 2008 database:

<add name="SQLServerConnection" providerName="System.Data.Odbc" 
connectionString="Driver={SQL 
Server};;uid=USERNAME;pwd=PASSWORD;server=HOST;database=DATABASE_NAME"/>

Step – 6: Creating an ASP.NET Application

We have so far completed the initial steps to plot a simple chart. The final process is to create the relevant ASP.NET application. For this purpose, you need to create a Default.aspx file and add the following code under the <Head> section

<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>

We also need to add a literal and button control. The chart will be drawn upon clicking the Button control.

In the code behind file, we have to create an instance of the StringBuilder class, pass the SQL query as a parameter to the DbConn function which we created in Step 1. You then have to create an XML file with the help of AppendFormat() method and plot the chart using RenderChart() method. The required snippet of the code is given below:

StringBuilder xmlData = new StringBuilder();
string query = "";
query = "select Team, Points from IPL_POINTS";
DbConn db = new DbConn(query);
xmlData.AppendFormat("<chart>");
while (db.ReadData.Read())
 {
   //Generate <set name='..' value='..' />           
   xmlData.AppendFormat("<set label='{0}' value='{1}' />", 
db.ReadData["Team"].ToString(), db.ReadData["Points"].ToString());
 } 
    xmlData.AppendFormat("</chart>");
    Literal1.Text = FusionCharts.RenderChart("FusionCharts/Column2D.swf", "", 
xmlData.ToString(), "chart1", "500", "400", false, true);

You should also make sure to import the following name spaces

using DataConnection;
using System.Text;
using InfoSoftGlobal;

The chart will appear as shown below after an initial animation which you will observe during the execution of the application.

Figure 4

In real world scenario, you can also use SQL Server 2008 database by following the steps mentioned above except the change in the connection string.

Summary

In this article, you have learned the steps required for creating charts from an ASP.NET application using FusionCharts. Firstly, you have seen the chart creation using an XML file and then learned how to make use of a WebForm to plot charts. Towards the end of the article, you learned to make use of the values from an MS Access database to draw charts.

Acknowledgments

I am thankful to Sanjukta Mukherjee and Rahul Kumar of the FusionCharts team for their support and assistance.

About the Author

Anand Narayanaswamy (Microsoft MVP and ASPInsider) is the author of Community Server Quickly. He works as a freelance technical writer based in Trivandrum, India. Anand maintains www.learnxpress.com and www.dotnetalbum.com.



User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 6:50:26 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search