Introduction
Are you dreaming of drawing a real-time smooth curve chart in your web application without refreshing your web page? Such as a stock chart, but much faster sampling rate (2 sec or 1 sec).
As we know, traditional web applications are mostly used for static information display or simple data interaction. Many timer control programs which are easy to realize in Windows Forms applications are very difficult to implement in web applications perfectly. The AJAX technology relieves some real-time data display problems as it can refresh just the places where you want in the web pages rather than refresh the whole page. However, AJAX is also not enough to display a smooth real-time chart. How can we make our charts look like playing a Flash and also communicate with our database, all at run time?
Adobe Flex owns these features. Flex is primarily a developer's tool. Although Flex creates a .SWF file which can be easily embedded in a web application, the way you develop Flex applications is entirely different from the way you develop Flash RIAs. All Flex development is based upon a framework that provides you with reusable and extendable UI components, data communication and retrieval services, event handling functionality, and much more.
Background
Development tools used
- C# on Visual Studio 2008 with .NET Framework 3.5
- Adobe Flex Builder 3.0
- SQL Server 2005 Express
To understand this article, you should have some basic knowledge about how to use Flex: http://learn.adobe.com/wiki/display/Flex/Getting+Started. This website has many good tutorials including video tutorials that would help you to quickly get to know how to use Flex.
Using the code
Flex can not directly exchange data with a database. It can only interact with an ordinary ASP.NET application as the interface between Flex and a database. Normally, it supports HTTP services and Web Services in order to get data from a database. I used a Web Service to realize the data exchange.
First, we create a database table to save the data.
The data in the database should change on the sampling time you set. This is a crucial part we should notice because a Flex chart is bound to this table. In other words, a Flex chart will change when the data table changes. This is easy to implement with SQL. My design method is shown below:
- Insert a new data during every sampling time.
- The table always reserves 10 data (it can be changed as you like). So before you insert 11th data, delete the 1st data you have saved before.
- Don't forget to order the data in terms of the time sequence.
- This part of the program is in the Web Service. Every time Flex calls a method in a Web Service, the database should be updated at the same time.
The code in the Web Service is shown below:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using webtest.mainTableAdapters;
namespace webtest
{
[WebService(Namespace = "http://localhost:3438/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class LineChartService : System.Web.Services.WebService
{
[WebMethod]
public List<energy> GetEnergy()
{
var emplist = new List<energy>();
Energy emp;
var ad1 = new chart_2TableAdapter();
ad1.InsertQuery(s1, s7);
if (ad1.ScalarQuery() > 10) { ad1.Deleteone(); }
var dt = new DataTable();
dt=ad1.GetDataByOrder();
foreach (DataRow dr in dt.Rows)
{
emp = new Energy
{
EnergySum = Convert.ToDouble(dr["EnergySum"]),
time = dr["time"].ToString()
};
emplist.Add(emp);
}
return emplist;
}
public class Energy
{
public double EnergySum = 0;
public string time = string.Empty;
}
}
}
Here is the dataset main.xsd:
Note the call to the Web Service with the URL: http://localhost:3438/ LineChartService.asmx?WSDL.
You can see that I defined an operation: GetEnergy
. The work in the ASP.NET application has finished.
Flex MXML
First, you need to add a <mx:WebService>
tag to your Flex application MXML file. Here is what I have now:
<mx:WebService id="webse"
wsdl="http://localhost:3438/LineChartService.asmx?WSDL"
fault="fault(event)">
<mx:operation
name="GetEnergy"
resultFormat="object"
result="GetEnergy(event)"
/>
</mx:WebService>
In the <mx:Canvas>
tag, I used click="init()"
so that the init()
method will be called when you click the Canvas
. Inside init()
, I call the Web Service method webse.GetEnergy()
.
Then, we write the script code to refresh the chart in the sampling time.
private function init():void {
webse.GetEnergy();
var timer1:Timer = new Timer(3000);
timer1.addEventListener(TimerEvent.timer, SaveEnergy);
timer1.start();
}
private function GetEnergy(event:ResultEvent):void {
linechart1.dataProvider=event.result;
}
private function SaveEnergy(event:TimerEvent):void {
webse.GetEnergy();
}
Lastly, use the<mx:LineChart>
template to create your chart. What you should do is bind the data to your chart.
<mx:Stroke id="sample" color="green" weight="2"> //Change the line color here
<mx:Canvas width="100%" height="100%" label="Energy Curve" click="init()">
<mx:LineChart id="linechart1" height="155" width="627"
paddingLeft="5" paddingRight="100"
showDataTips="true" x="45" y="31">
<mx:horizontalAxis>
<mx:CategoryAxis categoryField="time"/>
</mx:horizontalAxis>
<mx:series>
<mx:LineSeries yField="EnergySum" form="curve"
displayName="Energy" lineStroke="{sample}"/>
// Data binding
</mx:series>
</mx:LineChart>
</mx:Canvas>
Now, when you debug your Flex code, a .swf file will be created. You can embed it anywhere in your web pages. Of course, you can also add some events in your Flex chart to enhance the interactivity and make your chart more attractive.