Click here to Skip to main content
13,629,044 members
Click here to Skip to main content
Add your own
alternative version


42 bookmarked
Posted 18 Jan 2010
Licenced CPOL

Using Flex to build your real-time chart

, 18 Jan 2010
Rate this:
Please Sign up or sign in to vote.
A dynamic Flash chart that can commnunication with your database.


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.


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: 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;
// Import the dataset file main.xsd you have created.
// of course, you can directly write your 
// aql queries to operate your database.

namespace webtest
    // Change into your own server IP. 
    [WebService(Namespace = "http://localhost:3438/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class LineChartService : System.Web.Services.WebService
        public List<energy> GetEnergy()

            var emplist = new List<energy>();
            Energy emp;
            var ad1 = new chart_2TableAdapter();
            //Using class in dataset

            // InsertQuery(), ScalarQuery(), Deleteone(), 
            // GetDataByOrder(),are define in dataset file
            ad1.InsertQuery(s1, s7);
            if (ad1.ScalarQuery() > 10) { ad1.Deleteone(); }
            var dt = new DataTable();

            //Save the data in a object.
            foreach (DataRow dr in dt.Rows)
                emp = new Energy
                    EnergySum = Convert.ToDouble(dr["EnergySum"]),
                    time = dr["time"].ToString()

            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.


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" 







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 { 
  // Get Data from WebService and fill chart when you click the canvas 
  var timer1:Timer = new Timer(3000); //Trigger, 3s 
  timer1.addEventListener(TimerEvent.timer, SaveEnergy); 

private function GetEnergy(event:ResultEvent):void { 
  // data source 

private function SaveEnergy(event:TimerEvent):void { 
  // To Refresh 

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:CategoryAxis categoryField="time"/>
<mx:LineSeries yField="EnergySum" form="curve" 

  displayName="Energy" lineStroke="{sample}"/>
// Data binding

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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Singapore Singapore
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
manoj kumar choubey17-Feb-12 23:05
membermanoj kumar choubey17-Feb-12 23:05 
GeneralSmart Integration approach Pin
cpearl_s7-Jul-10 19:27
membercpearl_s7-Jul-10 19:27 
GeneralRe: Smart Integration approach Pin
ZHAOBING_NTU7-Jul-10 23:16
groupZHAOBING_NTU7-Jul-10 23:16 
GeneralMy vote of 5 Pin
cpearl_s7-Jul-10 19:22
membercpearl_s7-Jul-10 19:22 
Questioni need the code pls?? Pin
n.pavankumar12-Apr-10 20:32
membern.pavankumar12-Apr-10 20:32 
QuestionWhere's the code? Pin
Dewey18-Jan-10 11:13
memberDewey18-Jan-10 11:13 
GeneralThank you for sharing! Pin
Southmountain18-Jan-10 9:01
memberSouthmountain18-Jan-10 9:01 
GeneralVery good, I really need it Pin
loveice62218-Jan-10 2:18
memberloveice62218-Jan-10 2:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.180712.1 | Last Updated 18 Jan 2010
Article Copyright 2010 by ZHAOBING_NTU
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid