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 (http://www.macromedia.com). 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 http://www.macromedia.com.
- 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.
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:
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.
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 (http://www.infosoftglobal.com). 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 http://www.infosoftglobal.com/fusioncharts/lite 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.
Figure 2: Code used to embed a FusionCharts chart.
In Figure 2 the code between
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:
Exploring the XML Data Format
If you open Data.xml, you ll see the contents as shown in
Figure 3. The
xaxisname='Country' numdivlines='3' zeroPlaneColor='333333'
yaxisname='Points' xaxisname='Country' numdivlines='3'
zeroPlaneColor='333333' zeroPlaneAlpha='40' numberSuffix='%'>
Figure 3: The
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.
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 http://www.microsoft.com/downloads/details.aspx?FamilyId=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en.
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.
decimalPrecision='0' xAxisName='Country' yAxisName='Sales'
showvalues='0' decimalPrecision='0' xAxisName='Country'
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).
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).
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: