Click here to Skip to main content
15,868,141 members
Articles / Web Development / ASP.NET

Using Flex to build your real-time chart

Rate me:
Please Sign up or sign in to vote.
4.50/5 (8 votes)
18 Jan 2010CPOL3 min read 57.8K   42   8
A dynamic Flash chart that can commnunication with your database.

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.

Image 1

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.

Image 2

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:

C#
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)]
    [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();
            //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();
            dt=ad1.GetDataByOrder();

            //Save the data in a object.
            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:

Image 3

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:

XML
<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.

JavaScript
private function init():void { 
  // Get Data from WebService and fill chart when you click the canvas 
  webse.GetEnergy(); 
  var timer1:Timer = new Timer(3000); //Trigger, 3s 
  timer1.addEventListener(TimerEvent.timer, SaveEnergy); 
  timer1.start(); 
}

private function GetEnergy(event:ResultEvent):void { 
  // data source 
  linechart1.dataProvider=event.result; 
}

private function SaveEnergy(event:TimerEvent):void { 
  // To Refresh 
  webse.GetEnergy(); 
}

Lastly, use the<mx:LineChart> template to create your chart. What you should do is bind the data to your chart.

XML
<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.

License

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


Written By
Singapore Singapore
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey17-Feb-12 23:05
professionalManoj Kumar Choubey17-Feb-12 23:05 
GeneralSmart Integration approach Pin
cpearl_s7-Jul-10 19:27
cpearl_s7-Jul-10 19:27 
GeneralRe: Smart Integration approach Pin
ZHAOBING_NTU7-Jul-10 23:16
ZHAOBING_NTU7-Jul-10 23:16 
GeneralMy vote of 5 Pin
cpearl_s7-Jul-10 19:22
cpearl_s7-Jul-10 19:22 
Questioni need the code pls?? Pin
Pavan_N12-Apr-10 20:32
Pavan_N12-Apr-10 20:32 
QuestionWhere's the code? Pin
Dewey18-Jan-10 11:13
Dewey18-Jan-10 11:13 
GeneralThank you for sharing! Pin
Southmountain18-Jan-10 9:01
Southmountain18-Jan-10 9:01 
GeneralVery good, I really need it Pin
loveice62218-Jan-10 2:18
loveice62218-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.