Off the Chart

Build Powerful and Sophisticated Web Apps with ASP.NET and Macromedia Flash



Off the Chart

Build Powerful and Sophisticated Web Apps with ASP.NET and Macromedia Flash


By Pallav Nadhani


If you re someone who spends all your time with computers, chances are you ve heard something about Macromedia Flash ( Flash is a platform for delivering vector graphics, animations, interactive content, and even videos on the Web. It s the perfect medium for getting graphical elements to slide and fade and bounce around the screen to your heart s content, free from the dull constraints of the predictable and stationary HTML that makes up so much of the Web.


As .NET developers, you might be wondering why I am blabbering about Flash; it might not seem relevant to what we do to make ends meet. After all, it s a design tool that probably takes months of fiddling with the mouse to draw a proper trapezoid!


Granted, that s how many non-designers see it. But, with the advent of powerful scripting support, in the form of ActionScript, Flash is much more than an interactive motion tool. We re actually looking at two powerful technologies that dovetail very nicely, and make it very easy to build powerful, sophisticated, and impressive Web applications.


In this article, we ll be using the fluid beauty of Flash animations backed by the power of ASP.NET to create slick, data-driven, animated Flash charts for our Web applications. As .NET developers, we won t be coding any of the Flash movies. Instead, we ll cover a panoramic view of the integration options available, and use a few of the readymade Flash movies that expose APIs for integration with .NET.


But before we get into that, let s quickly consider the pros and cons of Macromedia Flash charting.


Why Use Flash Charting?

Because of a difference in platform and techniques, Flash charts offer many advantages that conventional methods of charting cannot offer; here are just a few:

  • Animated and interactive charts. Animated charts add to the aesthetics of a site, as opposed to static images generated by .NET or COM components. Also, with Flash charts, you have a range of interactivity options, from basic tool tips and hot spots to advanced simulation (planner) charts, wherein you can visually drag the data to change chart data.
  • Reduces load on server. Because the Flash charts are rendered on the client side they reduce the load on the server (which is required to generate complex chart images). The client needs only to have the Macromedia Flash 6 player, which, according to Macromedia Census, is present in more than 96% of the computers worldwide. Even if the viewers don t have the player installed, it s a small-sized (free) installation from
  • No installation affairs. Because Flash charts are simple .swf files, all you need to do is copy and paste them onto your server, thereby not involving any complicated registry entries or installation procedures. You can simply upload them like your normal .aspx pages.
  • Compatible with multiple scripting languages. Flash charts are compatible with all the scripting languages, as they accept their data in XML format. Whether you are using ASP.NET, ASP, PHP, ColdFusion, or any other scripting technology, you can always use Flash charts, providing a standard look to all the charts on your corporate network and, most importantly, saving a lot of cost by using one solution.
  • Multi-browser compatibility. The issue of browser compatibility arises if you plan to use advanced features with your image-based charting components; older versions of browsers might not support the JavaScript (or Image map functions) required to drive these functionalities. With Flash charts, you re always sure that the chart will look and behave the same in all browsers, as this is handled by the Macromedia Flash player.
  • Acts like a fat client, allowing advanced client-side options. The Macromedia Flash player makes the thin client behave like a fat client, allowing us to play with a lot of options on the client side. For example, you can use client-side JavaScript to completely update a chart without involving any pings to the server.


I could only think of one negative side of Flash charting: the inability to save the final chart output as an image. However, although there isn t a direct method in Flash, there are third-party tools that can help you save the final Flash output as an image.


Let s explore the integration options that Macromedia Flash provides to integrate our ASP.NET applications with Flash charts.


Integrating ASP.NET and Flash

When it comes to ASP.NET and Flash, Flash is the client part of the client-server application. We have information and logic that sits on our Web server, and we want Flash to graphically expose that information to our users. The data transfer between ASP.NET and Flash can take place in a number of ways; let s cover them briefly.


Plain text name/value pair data. In this method, our server (ASP.NET pages) provides data in name/value pairs, using & (ampersand) and = format as used in the query string portion of URLs. Flash ActionScript provides us with options to grab this text and make it available to our end users.


For example, if we were to read information about an artist and display it in Flash, our back-end ASP.NET page would have to provide data in the following format:


&artistName=Bryan%20Adams&artistId=26353&genre=Soft Rock


This method, however, is not very efficient when dealing with larger amounts of data because duplication of name pairs can create quite a confusion when handling groups and sub-groups of data.


XML data structures. XML is the easiest and most widely adopted data interchange format for ASP.NET and Macromedia Flash.


We all know about the tremendous capabilities of ASP.NET when it comes to XML. Flash also has native objects that very well support manipulating, sending, and receiving XML documents over HTTP (or HTTPS).


The best part about XML data is that it is always structured; this is one of the main reasons we will be using XML to transfer data from our ASP.NET pages to our Flash movie later in this article.


XML Sockets. Using XML Sockets, Flash implements client sockets that allow the computer running the Flash player to communicate with a server identified by an IP address or domain name. Flash ActionScript allows us to open a continuous connection with a server. A socket connection allows the server to push information to the client as soon as that information is available. This open connection removes latency issues and is commonly used for real-time applications such as Chats and Stock tickers.


Macromedia Flash Remoting. Flash Remoting is an add-on to Macromedia Flash MX that provides a way to directly connect your Flash applications to remote server-side functions and Web services. Using Flash Remoting, you can easily connect ActionScript client logic directly to remote services without writing any wrapper code, proxy code, or data marshalling code. Flash Remoting exposes application APIs and services (whether implemented in VB.NET, C#, Java, or ColdFusion) transparently to Flash as ActionScript APIs. However, using this method, data exchange takes place in a proprietary data format as opposed to open data structures, and involves additional cost per server.


JavaScript. JavaScript can be used to communicate with Flash on the host HTML page (the HTML page in which the Flash movie is embedded) from JavaScript functions and vice-versa. Later in this article we ll see how JavaScript can be used to update charts on the client-side.


Now that you re familiar with the various data integration options available with Flash, you can decide the best method for your application. For Flash charts we would use XML because it offers a lot of advantages, including cross-application compatibility, open source data structure, simple and structured data transfer, etc.


A Flash Charting Component

As .NET developers we won t get our hands dirty in learning and coding Flash. Instead, we ll use an existing Flash charting component that allows us to create animated charts, accept XML as its mode of data, support interactive options (tool tips, hot spots, etc.), and interact with the chart on the client side.


Considering these points, I chose a Flash charting component called FusionCharts Lite from InfoSoft Global ( FusionCharts Lite is a free charting component that you can download and use in your private and commercial projects. Also, open source developers can redistribute FusionCharts Lite with their applications for free.


First, download FusionCharts Lite from and extract it to any folder of your hard drive. You can now cruise through any of the examples present in the download package, like the My First Chart examples present in FusionCharts_Lite_1_0\Contents\Code\MyFirstChart folder (you ll see a sample of an animated column chart). When you view MyFirstChart.html, you ll see an animated column chart (see Figure 1), which is driven by the XML data contained in Data.xml (present in the same folder). If you open the HTML file (MyFirstChart.html), you ll see the code shown in Figure 2, which is used to embed the FusionCharts chart.


Figure 1: This animated 3D column chart shows the decline in net interest margins.


FusionCharts Sample Chart



WIDTH="565" HEIGHT="420" id="FC2Column" ALIGN="">

 quality=high bgcolor=#FFFFFF WIDTH="565" HEIGHT="420"



TYPE="application/x-shockwave-flash" PLUGINSPAGE="">

Figure 2: Code used to embed a FusionCharts chart.


In Figure 2 the code between tags is the code you need to embed a Flash movie in any HTML page. Also, and tags have been used to embed FusionCharts Column Chart (FC2Column.swf) within the HTML page. The string &dataUrl=Data.xml indicates the source of data to FusionCharts (Data.xml in this case). This method is known as the dataURL method of providing XML data to FusionCharts, as you simply specify the URL of the data source in this method.


To display a Flash movie correctly in a browser, the HTML page should contain two tags that specify the Flash movie file to be opened and played: and tags. The tag is used by Internet Explorer under Microsoft Windows and the tag is used by Netscape Navigator under Microsoft Windows or Mac OS. Each of these tags acts in the same way; however, using only one tag may cause incompatibility of one of the browsers. Let s take a look at the XML that drives this chart.


Exploring the XML Data Format

If you open Data.xml, you ll see the contents as shown in Figure 3. The element is the main element of any FusionCharts XML document it represents the starting and ending points of data. The graph element can have a number of attributes that help manipulate the chart functionally and visually. For the chart in Figure 1, the caption is defined as Decline in Net Interest Margins of Asian Banks (1995-2001) ; the sub-caption as (in Percentage %) ; the x-axis name (the horizontal axis) as Country ; and the y-axis name as Points , which represents the percentage decline for each country. There is another attribute, numberSuffix, which has been defined and set to %. This attribute helps you format all the numbers on the chart by adding % as the suffix to the number.


 yaxisname='Points' xaxisname='Country' numdivlines='3'

 zeroPlaneColor='333333' zeroPlaneAlpha='40' numberSuffix='%'>








Figure 3: The element is the main element of any FusionCharts XML document.


It s not possible in this space to cover the long list of attributes supported by each FusionCharts chart; for a detailed explanation of each attribute view the FusionCharts documentation in the download.


Each element in the XML data document represents a data row on the chart. The name (Country), value (Points), and color (color of the column) are defined for the data row by setting them as attributes of this element. In short, the XML in Figure 3 represents the data shown in Figure 4.








Hong Kong










Figure 4: The XML in Figure 3 represents this data.


So, to create a Flash chart, you need these three things:

  • XML Data document (provides data to the chart)
  • Chart .swf file (depending on which chart you want to plot)
  • HTML wrapper code (in your HTML/ASP.NET page)


We can now move to the most interesting part of the entire process connecting these charts with real-time data stored in your database.


Creating Database-driven Charts

Now let s see how to provide dynamic data (stored in a database) to the Flash charts. We ll be using the Northwind database for SQL Server (this is the default database provided with Microsoft SQL Server and Microsoft Access). This database contains the sales data for a fictitious company called Northwind Traders, which imports and exports specialty foods from all around the world. You can download this database from


Our first example plots a simple column chart showing the sales of the top five countries for 1998. The pertinent data to be extracted is stored in a SQL Server View called Invoices in the Northwind database. Use the following SQL query to extract this data:


SELECT TOP 5 Country, SUM(ExtendedPrice) As Total

FROM Invoices WHERE YEAR(OrderDate)=1998

GROUP BY Country ORDER BY SUM(ExtendedPrice) DESC


This query executes to give the output illustrated in Figure 5.


Figure 5: SQL Query Analyzer results for the top-five query.


Our first job is to create a .aspx page, which does the following:

  • Connects to the database
  • Executes the above query and retrieves the recordset
  • Creates an XML document
  • Outputs the XML


For this purpose create Data.aspx, which contains the following:


<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SQLClient" %>

We first include the required namespaces for data. Next, we connect to the database and retrieve the recordset using the code shown in Figure 6.



Now when you run this page independently in the browser and see the source, you ll get the XML data shown in Figure 9.


 showvalues='0' decimalPrecision='0' xAxisName='Country'

 yAxisName='Sales' numberPrefix='$'>

Figure 9: The XML data we expected.


Bingo! Exactly what we had been looking for! The next step is to copy the column chart .swf file to the same folder where Data.aspx is placed. Then the only step remaining is to create the HTML container for the chart. For this, create another page Chart.aspx, in the same folder, with the code shown in Figure 10. Although, we re simply embedding the Flash chart and specifying its width, height, and data source, you ll be pretty impressed when you now see the results in your browser (see Figure 11).


 ",0,0,0" height="420" width="565"

 classid="clsid:D27CDB6E-AE6D-11cf-96B8- 444553540000"


 quality=high bgcolor=#FFFFFF WIDTH="565" HEIGHT="420"

 NAME="ColumnChart" TYPE="application/x-shockwave-flash"



Figure 10: Create the HTML container for the chart.


Figure 11: Column chart generated from our query.


You ve seen how easy it is to create dynamic data-driven charts using Flash charts. Now let s see how to change the chart to a 3D pie chart.


Changing Chart Types

To change a chart type, simply change the name of the .swf file. For example, if you want to depict the previous figures using a 3D pie chart instead of a column chart, simply copy FC2Pie3D.swf and in Chart.aspx make the changes shown in Figure 12; there s absolutely nothing else necessary (see Figure 13).


 ",0,0,0" height="420" width="565"



 high bgcolor=#FFFFFF WIDTH="565" HEIGHT="420"

 NAME="PieChart" TYPE="application/x-shockwave-flash"



Figure 12: Changing chart types ...


Figure 13: ... is easy as pie.


That s simple enough, but now let s now consider an example where the end user plays a role in what s to be displayed on the chart.


Creating Data-driven Charts Based on User Input

In our previous example we plotted a chart for the year 1998; but what if users want to view the top five countries for any year in the database? For this scenario we need to:

  • Display in Chart.aspx in the form of a dropdown list the years available in the database.
  • The value is submitted back to Chart.aspx when the user selects a value from the dropdown list.
  • Chart.aspx reads the submitted form value and passes it to Data.aspx as a part of dataURL in URLEncoded form (&dataURL=Data.aspx should now read &dataURL= Data.aspx%3Fyear%3D1997).
  • Data.aspx can retrieve the year passed to it as a normal QueryString; thereafter, it could query the database based on these parameters and output the resulting XML.


We need to add to Chart.aspx the code shown in Figure 14 to show the list of years and present them in a dropdown.


Figure 14: Retrieve a list of unique years present in the database.


The script in Figure 14 retrieves the list of unique years present in the database. It also handles any form postback and generates the dataURL, in the form Data.aspx?Year=199x:


Please select the year for which you want to see the chart:

 "server" class="Select">


In the main body, the dropdown list is rendered showing the list of years. Lastly, we embed the Flash chart and convey the XML data URL to it (see Figure 15).


 ",0,0,0" height="420" width="565"



 quality=high bgcolor=#FFFFFF WIDTH="565" HEIGHT="420"

 NAME="ColumnChart" TYPE="application/x-shockwave-flash"



Figure 15: Embed the Flash chart and convey the XML data URL.


Shifting to Data.aspx, we now need to request the year passed to this page from the Flash chart in Chart.aspx. The year value is passed as a QueryString to this page, which queries the database based on this year (see Figure 16). The rest of the code remains the same. When you view this chart now, you ll see the options for changing the chart data by selecting different years present in the dropdown list.



'Request the year passed to this page

 Dim strYear as String

 strYear = Request.QueryString("Year")


'Get Top 5 Countries the database.

MyConnection =

 New SqlConnection( ConfigurationSettings.AppSettings(

 "appDSN") ) MyCommand = New SqlDataAdapter(

 "SELECT TOP 5 Country, SUM(ExtendedPrice) As Total,

 COUNT(DISTINCT OrderID) As orderNumber FROM Invoices

 WHERE YEAR(OrderDate)=" & strYear & " GROUP BY Country

 ORDER BY SUM(ExtendedPrice) DESC", MyConnection)

Figure 16: Pass the year value as a QueryString.


You should now be able to drive all your Flash charts using data stored in your database. Next we ll explore the most unique feature that only Flash charts can offer: client-side dynamic updates to the chart.


Flash as the Fat Client

Whenever we .NET developers need to update a chart, we are accustomed to forcing page refreshes that involve a new image generation on the server, then that image is served to the end user (along with the other elements present in the same page). In this process, we re consuming more-than-required end-user bandwidth and server resources, which we can save by using Flash charts.


Flash charts allow you to dynamically update the chart currently being viewed by the end user, with new sets of data at the client side, without involving any requests to the server. In this entire process, the Macromedia Flash player plays a big role in converting the thin client to a fat client.


The Macromedia Flash player offers close integration between JavaScript and Flash movies. It exposes a set of methods that allows for bi-directional flow of information and commands:

  • from the Flash movie to JavaScript functions in the host page, and
  • from JavaScript functions present in the host page to the Flash movie embedded in the same page.


When talking about client-side dynamic chart updates in a charting scenario, the information flow would occur as listed in the second point, i.e., from JavaScript functions in the host page to the Flash movie (chart .swf). The JavaScript functions would pass XML data stored in local JavaScript variables to the Flash charts and the charts would update themselves, without even a flicker of the screen.


Let s consider a quick example to explain further the need for client-side updates. In our previous example we built a year-wise top five countries chart, wherein the user could select a year to view the chart and the new data was provided by the server based on the selection. Whenever the user selected a new year, the value was being passed to the server, and the server responded with a new XML document pertinent to that year. Now, for this small chunk of data, we had to call the server every time the user selected a new year, and most importantly, the user had to wait until the new chart downloaded from the server. Moreover, when you browse the Web, you ll find that most of the pages containing the chart also contain a lot of other items, like images, data tables, etc. So, whenever that page is refreshed, the rest of the content (which remains unchanged) must still be downloaded afresh along with the chart, which results in unnecessary bandwidth consumption.


Because we know that we re not dealing with huge amounts of data, we can transfer all the XML data documents to the client, whenever the page is first invoked and rendered. These XML data documents, pertinent to each year, would be stored in local client-side JavaScript variables. So, whenever the user selects a new year from the dropdown list or clicks a chart change button, we can initiate JavaScript events to pass the required XML data document (currently stored in JavaScript variables) to the Flash chart and the chart would update itself on the client side.


The entire communication model from JavaScript to FusionCharts Flash chart can be explained using the diagram shown in Figure 17.


Figure 17: JavaScript to Flash chart communication model.


To simulate this process using Flash charts and ASP.NET you ll need to download FusionCharts 2.3, as FusionCharts Lite doesn t support the JavaScript update feature. An evaluation version of FusionCharts 2.3, the commercial version of FusionCharts, is available from


Getting back to our process, the FusionCharts Flash chart exposes a JavaScript function, setFCNewData, which you can use to pass XML data from JavaScript to the required Flash movie in the page (see Figure 18).


function setFCNewData(objFlash, strXML) {

 //This function updates the data of a FusionCharts

 //present on the page

 //Get a reference to the movie

 var FCObject = getObject(objFlash);

 //Set the data

 //Set dataURL to null


 //Set the flag


 //Set the actual data


 //Go to the required frame

 FCObject.TGotoLabel('/', 'JavaScriptHandler');


function getObject(objectName) {

 if (navigator.appName.indexOf ("Microsoft") !=-1) {

      return window[objectName]

 } else {

      return document[objectName]



Figure 18: The JavaScript function, setFCNewData.


Let s first analyze the getObject(objectName) function. This function takes in the name of an object and returns the reference to that object present in the HTML page, based on the browser on which the page is running (IE and Netscape reference the object differently). If you look at the HTML code we used previously to embed a chart, you ll note the following:




Here, ColumnChart is the name of the chart object we embedded in our page.


Getting back to setFCNewData function, this function takes two parameters:

  • objFlash. The name of the Flash object (ColumnChart in the above example).
  • strXML. The updated XML data document that you want to pass to the chart.


Now if we want to modify our previous example to support dynamic client-side data updates, we ll need to do a few changes to our page (all we need is one page, Chart.aspx).


In this page, we first query the database to retrieve the data for three years, and store that data in local ASP.NET variables, say strXML1996, strXML1997, and strXML1998. Thereafter, when the HTML code for the page is being rendered, we ll also render the following JavaScript code, along with the above two JavaScript functions (see Figure 19).