Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This article is about creating a real time AJAX based line graph, using Microsoft Silverlight and JavaScript.

If you are impatient to see how it really looks, visit my website to see a 'JavaScript-only' demo. Download the source code and run it to see the actual thing in action. In this article, I will explain how to use my WPFGraph.js script along with Silverlight to create custom line graphs.

screen shot of graphsi in action
Images of the line graph in action with two different skins

Writing the XAML

This is the only important part. First, I will explain the bare minimum XAML which my script expects. As show below the graph is actually made of multiple line segments.


Figure showing line segments used for drawing the graph

<Line X1="10" Y1="200" X2="20" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Orange" StrokeThickness="1" x:Name="gline0"/>
<Line X1="20" Y1="200" X2="30" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Orange" StrokeThickness="1" x:Name="gline1"/>
<Line X1="30" Y1="200" X2="40" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Orange" StrokeThickness="1" x:Name="gline2"/>
...
...
<Line X1="30" Y1="200" X2="40" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Orange" StrokeThickness="1" x:Name="glineN"/>
If you want to plot 10 points then you need to have 11 segments. In that case your segments should be named 'gline0, gline1....gline10'. Note that the name 'gline' is hardcoded into the JavaScript. If you decide to change it to something else don't forget to modify the WPFGraph.js file. Apart from this section, we have markup to create the X and Y axis and markers on axis. This can be customized as per your need.

<Line X1="10" Y1="0" X2="10" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>

<Line X1="7" Y1="0" X2="280" Y2="0" Canvas.ZIndex="3" Opacity="0.5" 
      Canvas.Left="00" Canvas.Top="20" Stroke="Red" StrokeThickness="1"/>
<Line X1="7" Y1="40" X2="280" Y2="40" Canvas.ZIndex="3" Opacity="0.5" 
      Canvas.Left="00" Canvas.Top="20" Stroke="Red" StrokeThickness="1"/>
<Line X1="7" Y1="80" X2="280" Y2="80" Canvas.ZIndex="3" Opacity="0.5" 
      Canvas.Left="00" Canvas.Top="20" Stroke="Red" StrokeThickness="1"/>
<Line X1="7" Y1="120" X2="280" Y2="120" Canvas.ZIndex="3" Opacity="0.5" 
      Canvas.Left="00" Canvas.Top="20" Stroke="Red" StrokeThickness="1"/>
<Line X1="7" Y1="160" X2="280" Y2="160" Canvas.ZIndex="3" Opacity="0.5" 
      Canvas.Left="00" Canvas.Top="20" Stroke="Red" StrokeThickness="1"/>
<Line X1="10" Y1="200" X2="280" Y2="200" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>

<Line X1="64" Y1="197" X2="64" Y2="202" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>
<Line X1="118" Y1="197" X2="118" Y2="202" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>
<Line X1="172" Y1="197" X2="172" Y2="202" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>
<Line X1="226" Y1="197" X2="226" Y2="202" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>
<Line X1="280" Y1="197" X2="280" Y2="202" Canvas.Left="00" Canvas.Top="20" 
      Stroke="Red" StrokeThickness="1"/>

Server side code for AJAX

In this example, I have used a simple function (Webmethod) in ASP.NET to do the job. It returns a numeric value. In the real world scenario, this would come from a database or some other source. I have also placed a random delay to simulate real world conditions. This method should be in code-behind file of page where we want to place the graph. It can be invoked from client side JavaScript using PageMethods object.

    [System.Web.Services.WebMethod]
    public static int GetNextValue()
    {
        Random r = new Random();
        System.Threading.Thread.Sleep(r.Next(100, 500));
        return r.Next(0, 190);
    }

Client side HTML and JavaScript

On the *.aspx page, you need to add the following markup to create an instance of the Silverlight control.

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" 
         EnablePageMethods="true"/>
    <div>
        <object id="slvr1"  width="350px" height="270px" 
                type="application/x-silverlight">
            <param name="SourceElement" value=null />
            <param name="Source" value="Graph.xaml" />
            <param name="WindowlessMode" value="false" /> 
            <param name="MaxFrameRate" value="30" /> 
            <param name="OnError" value="myErrorHandler" /> 
        </object> 
    </div>
    <input id="Button1" type="button" onclick="startstop()"
           value="Start/Stop" />
</form>

Notice that there is a ScriptManager control on the ASP.NET page with it's EnablePageMethods property set to true. Also I have put a button which can be used to start and stop real time plotting on the graph.

The next important part is writing the JavaScript.

<script type="text/javascript" src="WPFGraph.js"></script>
<script language="javascript">

var mygraph;
var start =true;

function OnCanvasLoaded(sender,args)
{
    mygraph = new WPFGraph("slvr1",26,200);
    PageMethods.GetNextValue(OnComplete,null);
}

function OnComplete(a)
{
    mygraph.PlotValue(a);
    if(start ==false)return;
    window.setTimeout("PageMethods.GetNextValue(OnComplete,null)",500);
}

function startstop()
{
    start=!start;
    if(start)PageMethods.GetNextValue(OnComplete,null);
}
</script> 

The first thing to note here is the parameters to the constructor of WPFGraph class. The first is the id of the Silverlight control, the second is the number of points to be plotted(= no of segments -1) and the last parameter is the maximum value the graph will be used to plot (range). The second parameter relates to the XAML file while the third is related to values coming from the server side function. You should set them appropriately in your code.

Further customization

There are lot of interesting things that you can do with XAML to alter the appearance of the graph. In Example2.aspx, I have created the same graph using different XAML. You will find it in the downloaded source. Hope you find my code useful. If you do happen to use it in your application, I would be happy to hear from you !

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHow can i use the Data from the DB
ranjith537
20:57 9 Sep '09  
hi ashish
your code was really useful
But i want to use my database data (MSSQL) for displaying in the graph.
how to replace this random number generation from the datasource.?
Kindly help. Its really urgent for me..!!
GeneralProblems
rantinori
16:28 15 Dec '08  
I am running VS2005 and loaded your sample code. This is REALLY cool!!

It runs great in VS IDE, but when I publish the application it does not work.

Why?

I am running this on Vista Home Premium and IIS7..
GeneralRe: Problems
ashish_patil++
19:40 22 Dec '08  
Hmm ..Make sure that all your URLs are correct.That could be an issue. Also check javascript file reference is pointing to right place. Try debugging a bit. Let me know what error/problem u r getting...that should enable me to help u more !

- Ashish
http://ashishware.com

GeneralRe: Problems
rantinori
12:22 27 Dec '08  
Ashish,
I got everything working. I ended up going to VS2008 and used all your conventions for automating the graph.

As I learn Silverlight, I am even more impressed with it's capabilities!

Thanks for your response!
GeneralWhats the requirement for running this project?
nasserdw
23:13 12 Sep '07  
what software requirements needed exactly to run this sample project and start modifying on its code?

thanks
GeneralRe: Whats the requirement for running this project?
ashish_patil++
19:02 13 Sep '07  
You need to have following things installed:

1] ASP.NET AJAX (Recent version) [for ASP.NET 2.0]
2] Silverlight plugin 1.0 RC


Unzip the code somewhere. This should create SilverlightGraph folder with code files. In Visual Studio 2005 , select File->Open->Website. Set any *.aspx file as 'start page'

Hit, run !Big Grin

This should work. Another way would be to create a new ASP.NET AJAX website with VS and 'import' all the items into your solution.

- Ashish
http://ashishware.com

GeneralRe: Whats the requirement for running this project?
nasserdw
21:06 13 Sep '07  
Thanks, i voted 5 for the article its realy greate example Cool

Nasser Hamdan,

GeneralRe: Whats the requirement for running this project?
ashish_patil++
23:20 13 Sep '07  
Thank you very much !Smile

- Ashish
http://ashishware.com

GeneralThanks
Mykola Tarasyuk
0:38 12 Sep '07  
A little off-topic.
Presence of such handy and powerful feature of ScriptManager as PageMethods support was quite new for me.
Thanks a lot.


Last Updated 7 Aug 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010