ailon's DevBlog: Development related stuff in my life

Add Interactive Flash Charts to Your ASP.NET Web Application. Part 4: Column Chart from Code-behind

8/8/2008 10:29:36 AM

This is the fourth part in the series of tutorials showing how to add dynamic, interactive, data-driven charts to your ASP.NET web applications. These tutorials use amCharts Flash charting components and "ASP.NET Controls for amCharts" for ASP.NET integration.

This part is long overdue. Sorry for that. A tutorial on adding amCharts to ASP.NET page from code-behind was the most requested on amCharts ASP.NET controls forum. So, here we go.

Make sure you have your environment setup, ASP.NET controls for amCharts DLL added and amCharts Column chart added to your project. Details on doing that were provided in Part 1 of the series so I wont repeat it here.

Now let's add a new ASP.NET web form to our project and let's call it CodeBehindBar.aspx. We will only add a single PlaceHolder object to the markup side of our script so it looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CodeBehindBar.aspx.cs" Inherits="CodeBehindBar" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="ChartPlaceHolder" runat="server" />

Now let's switch to the code-behind file.

We will be creating a column chart with two graphs and we'll use Northwind database as data source. The first graph will represent sales totals for 1997 grouped by category and divided by 1000 (just for the sake of being in the same range as our second graph). The second graph will show quantities of products in each group we have in stock.

Make sure that you have access to some SQL Server instance with Northwind database installed, connection string setup, and let's start by pulling our data from SQL Server and placing it into DataSet:

// Get data from Northwind
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);

SqlCommand myCommand = new SqlCommand("select CategoryName, CategorySales/1000 as CategorySales from [Category Sales for 1997]", conn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
da.Fill(ds, "Category Sales for 1997");

myCommand.CommandText = "select CategoryName, sum(UnitsInStock) as UnitsInStock from [Products by Category] group by CategoryName";
da.Fill(ds, "Products by Category");


Now it's time to create our chart. We create a ColumnChart object and setup it's DataSource. This is what will be used for the chart series (X axis).

// create column chart
ColumnChart chart = new ColumnChart();
chart.DataSource = ds.Tables["Category Sales for 1997"].DefaultView;
chart.DataSeriesIDField = "CategoryName";
chart.DataSeriesValueField = "CategoryName"; // here it's the same as ID and could've been ommited

Notice that we've specified "CategoryName" as both SeriesIDField and SeriesValueField. This isn't necessary in case like this were we have the same field for both ID and Value. It would suffice to just specify the ID, but I've added Value line so you know you can use different data fields for that.

What we've done so far is created a grid where to add actual data graphs. Now let's create 2 graphs:

// crete sales graph
ColumnChartGraph graph1 = new ColumnChartGraph();
graph1.DataSource = ds.Tables["Category Sales for 1997"].DefaultView;
graph1.DataSeriesItemIDField = "CategoryName";
graph1.DataValueField = "CategorySales";
graph1.Title = "Sales (in thousands)";

// crete stock graph
ColumnChartGraph graph2 = new ColumnChartGraph();
graph2.DataSource = ds.Tables["Products by Category"].DefaultView;
graph2.DataSeriesItemIDField = "CategoryName";
graph2.DataValueField = "UnitsInStock";
graph2.Title = "Units in stock";

and add these graphs to our chart:


What's left is just data-binding the chart and adding it to our place holder control on the page


And that' basically it. This is what you should see if you run this:


You can customize the look and feel by changing various properties according to your taste.

Download the source code here: (1kb)

kick it on

Tags: , , ,

Migrating from LifeType to BlogEngine.NET

4/8/2008 6:37:46 PM

Note: this post doesn't cover BlogEngine.NET installation.

Yesterday I've moved my personal blog (in Russian) from LifeType to BlogEngine.NET.

I've used LifeType blogging platform (formerly know as pLog) since 2003. It's a decent, mature blogging engine for both standalone blogs and multi-blog communities. I didn't move away from it because there's something seriously wrong with it. I just had several minor reasons for the move:

  1. I have a personal Windows/.NET hosting account, but my blog was hosted on my company's server because of the blogging engine's PHP nature;
  2. I can do my share of PHP coding but I feel more at home with .NET these days;
  3. The most frustrating thing and the one which was the main reason for the move and main obstacle - there's no way to export blog content from LifeType into some widely supported format (like BlogML)

Unsolved Problems

In case you are going to follow my path, I want to warn you right away:

  1. I've lost all comments in the old blog. Since there are no tools to export them and no comment RSS, I decided to sacrifice comments rather than try and create some tool to export them from the MySQL database and then map to the posts in the new blog
  2. Back links to your own posts will be broken. To resolve this you'd need to make a mapping table of your old and new post IDs and then replace all the links based on that. I decided to skip this


The only readily accessible way to export posts from LifeType is RSS feed. The number of posts in RSS feed is controlled by "Number of recent posts" setting in LifeType. Since we need them all you should set this value to something that is undoubtedly higher than the number of posts in your blog.

Basically one may think that this is it - just feed your feed (sorry) to BlogEngine.NET's Blog Importer and you are set. Unfortunately it's not that simple.

First of all, as of this writing (BE.NET v.1.3), it looks like Blog Importer has problems opening feeds with parameters in the URL. But since LifeType's rss.php can serve default RSS profile (can be set in configuration) this is not a major issue. However, in my case, Blog Importer still choked on my feed. Maybe it was the number of posts (1200) in my blog, maybe something else but it didn't work out that way.

Anyway even if Blog Importer doesn't choke on your feed, you wouldn't want to import your posts that way unless you've never touched LifeType's Resource Gallery. So, we just need to save our full RSS feed content as file by simply downloading it with your favorite download manager. Make sure you set locale of your blog to English US even if your blog is not in English. At least in my case importing with Russian locale resulted in incorrect dates.

You can specify File Path in Blog Importer. Everything under that path is considered a file by it and will be downloaded into your new blog as is and appropriate URLs in your content will be modified accordingly. Unfortunately if you've used Resource Gallery in LifeType most of your images will have an src attribute looking something like this:;resource=someimage.jpg

Setting File Path to (or something like this) doesn't work. Fortunately the image is physically accessible at (I guess this can vary slightly in different installations).

What we need to do is open our saved RSS file and run a replace changing;resource=


Now we need to place our static RSS file on the server, because there's no option to load RSS file from disk in Blog Importer. I don't know what MIME-TYPE it expects to get but I was unable to find an extension for it to accept my RSS file. Finally I've changed extension to .aspx and voila, my RSS was finally declared valid.

I've set File Path field to, entered connection information for my BE.NET blog and pressed Import. In a matter of seconds all my posts were imported into Blog Engine.

However there were still some issues left.

  1. File Path URLs were replaced with http://localhost/... URLs (I did the import on my local machine which is the only logical approach, imho);
  2. Author wasn't set on my posts, even though I've tried importing with "Use Source Author" checked and unchecked and usernames in both blogs were identical.

I've solved both of these issues by running a find & replace in files on App_Data/posts/ directory replacing http://locahlost/ with just a slash, and <author /> with <author>ailon</author>. The later wont save you if you had more than one author in your blog.

After that I've just uploaded all the files to my hosting server and everything (except the known issues above) seems to be working fine.

Hope this helps someone.

kick it on

Tags: , ,

Add Interactive Flash Charts to Your ASP.NET Web Application. Part 3: Auto-reloading Data

3/28/2008 1:38:57 PM

This is the third part in the series of tutorials showing how to add dynamic, interactive, data-driven charts to your ASP.NET web applications. These tutorials use amCharts Flash charting components and "ASP.NET Controls for amCharts" for ASP.NET integration.

In the first two parts of the series we've learned how to add a simple pie chart to your pages and how to bind the chart to real data. This time we will learn the way of making the chart reload it's data in specified intervals and see more options for visual customization.

External Data Source

To make our pie chart reload it's data we need to create an external data source for it. The nicer way of doing this would be to implement IHttpHandler interface but since the objective of this tutorial is to show you the main relevant principles, we will do it with a web form pretending to be an XML file.

So, let's start by creating our dynamic data file. Add a new web form to your web site and call it ExternalDataForPieChart.aspx. In the web form source remove all the contents except the @Page directive so it looks like this:

<%@ Page Language="C#" AutoEventWireup="true" 
Inherits="ExternalDataForPieChart" ContentType="text/xml" %>

Notice the ContentType="text/xml" attribute. In the code-behind file add using am.Charts; directive and implement the Page_Load() handler like this:

protected void Page_Load(object sender, EventArgs e)
    PieChart myChart = new PieChart();

    // get a random value for Clinton votes
    Random rnd = new Random();
    int clintonValue = rnd.Next(80000, 120000);
    // add items to pie chart

    // Hillary Clinton's slice
    myChart.Items.Add(new PieChartDataItem("Hillary Clinton", clintonValue, // title and value
        "", "Votes for Hillary Clinton", // url and description
        (byte)(clintonValue < 50 ? 70 : 90), // opacity: make leading candidates slice solid and losing candidates semi-transparent
        (clintonValue > 50 ? true : false) // make leading candidates slice pulled out
    // Barack Obama's slice
    myChart.Items.Add(new PieChartDataItem("Barack Obama", 200000 - clintonValue, // title and value
        "", "Votes for Barack Obama", // url and description
        (byte)(clintonValue > 50 ? 70 : 90), // opacity: make leading candidates slice solid and losing candidates semi-transparent
        (clintonValue < 50 ? true : false) // make leading candidates slice pulled out

    // output data xml to response stream

As you can probably see from the code for the sake of simplicity we are going to generate random data imitating the live voting process in the 2008 Democratic US Presidential primaries.

We create a PieChart instance and add 2 PieChartDataItems to it with random values. Basically you can create this items using only 2 arguments: first for the title of the slice and second for the value. Here we've used another version of constructor which lets us specify a link URL, description, opacity, and pull-out flag for each slice.

Finally we get the XML data for our data items and just output it to response stream. That's it for our data file.

The Chart

Now let's create our main chart page. Add an new web form to your site called PieChartWithExternalData.aspx and drop a PieChart control on it.

All you need to do is specify the external data settings:


We've selected our data file for the ExternalDataFileUrl property, set AddTimeStamp property to True (to prevent unwanted caching issues) and set ReloadDataInterval to 30 seconds.

If we run this page now we will see something like this:


And the chart will be refreshed every 30 seconds to show the new data.

The mark-up for this chart is as simple as this:

<cc1:piechart id="PieChart1" runat="server" addtimestamp="True"
    externaldatafileurl="~/ExternalDataForPieChart.aspx" reloaddatainterval="30">

Spice It Up 

Now when we have our initial goal achieved let's add some bells and whistles to our chart. Without going into detail about every possible setting let's see the code we've got for the beautified chart (all of these properties could be set in designer):

<cc1:piechart id="PieChart1" runat="server" addtimestamp="True" 
    colors="Blue,Red" externaldatafileurl="~/ExternalDataForPieChart.aspx"
    height="340px" pieangle="30" pieheight="15"
    reloaddatainterval="30" slicelinktarget="_blank" 
    DataLabelLineColor="#FFFFC0" ForeColor="#FFFFC0" LegendBackgroundAlpha="30" LegendColor="Black">
        <cc1:ChartLabel Align="Right" Text="The 2008 Democratic Primaries" TextColor="#FFFFC0"
            TextSize="20" Width="500" />
        <cc1:ChartLabel Align="Right" Text="Live Voting Results in State X" TextColor="White"
            TextSize="14" Width="500" />

In two words what we've done here is added a background image, changed font and pie slice colors, made the pie three dimensional and added a couple of labels.

And the result looks like this:


Photo of the flag by freefotouk.

As they say a picture is worth a thousand words, but a live demo is worth a thousand pictures. Click here to see this example in action.

That's it for today and for pie charts in general. In the next parts we will move on to other chart types.

kick it on

Tags: , ,

Add Interactive Flash Charts to Your ASP.NET Web Application. Part 2: Data binding

3/26/2008 5:05:47 PM

This is the second part in the series of tutorials showing how to add dynamic, interactive, data-driven charts to your ASP.NET web applications. These tutorials use amCharts Flash charting components and "ASP.NET Controls for amCharts" for ASP.NET integration.

In the first part of the series we have looked at how to setup your Visual Studio environment to use amCharts and how to add a simple pie chart based on static data. That was easy but by using such dynamic environments as ASP.NET and Adobe Flash most likely you weren't looking for a way to display static hard-coded data. So in this part we will look at how to bind our pie chart to a real data source plus we will cover a couple of visual enhancement options.

Pie chart looking from data binding point is the simplest of all chart forms (at least in amCharts lineup). Column, Line and XY charts can have more than one graph drawn on a single chart but Pie chart can't. This makes it a perfect starting point to learn how to bind amCharts to data.

Data source

We will be using sample Northwind database included with MS SQL Server. Unfortunately it's not included with SQL Server Express Edition but here's an article on how to set it up with Express. You can use MS Access version of Northwind if you like.

We will start by adding a new Web Form page to our web site. Let's call it DataboundPieChart.aspx. First we will add an SqlDataSource object to our page by dragging and dropping it from the toolbox


Now we need to configure it. Press "Configure Data Source..." link in the Smart Tag and configuration dialog will appear.


Create a new connection to your SQL Server or select an existing connection from the dropdown and press "Next". Let's save the connection string in web.config for future reference


Let's call it "NorthwindConnectionString" and press "Next". Now we need to select a table or view containing our data.


We will use the one called "Category Sales for 1997". On the next screen we just press "Test" to make sure that our simple query works and press "Finish".


Let's rename the data source from generic SqlDataSource1 to a more meaningful CategorySalesSource

Data-bound pie chart 

Now that we have our data source configured, it's time to add a pie chart by drag-n-dropping the PieChart control from the toolbox. All we need to do is to specify our datasource object and associate the fields in datasource with chart properties.


We set DataSourceID to CategorySalesSource, DataTitleField (this would be the title of a pie slice) to CategoryName and DataValueField to CategorySales. And that basically it.

One more thing we want to do is disable chart legend because there will be too much slices in our chart and the legend would take too much space without making much sense. To do that we set LegendEnabled property to false.


Now if we run our project our pie chart would look like this


Some tweaks 

Default chart looks just fine but suppose we want to add a little 3D effect to it. This is done by setting the PieAngle property to a value different from 0


We've also set PieHeight property so our pie has some volume and decided to make it a donut instead of a pie by setting PieInnerRadius to 30 (in other words this is the radius of the hole).

One more thing we want to do is highlight our top selling categories by grouping our slow-sellers into one slice called "Others". To do that we set grouping properties to group all the slices with value less than 10% of the total into one slice. This is done by setting GroupPercent property to 10.


Let's make the others slice pulled out of the donut on load. Set GroupPullOut to true.

Let's run the project and see what we got. This is a screenshot of our pie with mouse hovering over the "Confections" slice.


That's it for Today. In the next part we will talk about feeding the data to our chart from external data source and forcing the chart to refresh itself every now and then.

P.S.: thanks for linking, "kicking" and promoting these tutorials in other ways!

kick it on

Tags: , ,

Add Interactive Flash Charts to Your ASP.NET Web Application. Part1: Basics

3/21/2008 4:26:22 PM

This is the first part in the series of tutorials showing how to add dynamic, interactive, data-driven charts to your ASP.NET web applications. These tutorials use amCharts Flash charting components and "ASP.NET Controls for amCharts" for ASP.NET integration.

In this first installment I will show you how to add ASP.NET Controls for amCharts into your Visual Studio toolbox and add a simplest form of pie chart to your page.


First we need to download amCharts controls and setup our environment. To download amCharts navigate to . Today we will need "Pie & Donut" chart and "ASP.NET Controls for amCharts". Download the files and extract the archives to your preferred location.

Now let's create a new web site in Visual Studio/Visual Web Developer Express and add amCharts to the Toolbox and the site.

To add ASP.NET Controls for amCharts to your Visual Studio toolbox select "Choose Toolbox Items ..." from Tools menu.


There select "Browse..." and navigate to the directory were you extracted "ASP.NET Controls for amCharts". Select am.Charts.dll and press "Open".


Press "OK" and you should see 4 new controls added to your toolbox


Now we need to add Flash files for amCharts Pie & Donut chart to our web site. To do that we will create a directory called "amcharts" under the root of our web application and copy the directory "ampie" from the downloaded Pie & Donut chart archive and all of it's contents under that directory.


This is were ASP.NET Controls for amCharts assume to find amPie files. This location could be changed in your web.config file or in your code. See documentation for details.

We are all set to start adding pie charts to our pages.

Basic pie chart

Today we are going to add a simple, static pie chart. To do that we drag the PieChart control from the toolbox to the designer surface and drop it there.


We want to add a title to our chart. In amCharts this is done by adding a label. You can add virtually unlimited number of labels but we only want one this time. In the properties window locate a property called "Labels" and press "..." button next to it.


Collection editor opens. Press "Add" and add label text (title in our case) and modify other properties if you want. We will change color of our title, make it bigger and right-align it.


Press "OK". Now let's add our data items. In the properties window locate "Items" and press "...".


In the opened window press "Add" to add our first data item.


Type in Title (this will be shown in the legend and next to the slice), Value (this doesn't have to be in percents, amCharts will calculate the percents automatically). We'll make our first slice pulled out. To do this we set PullOut to True. Press "Add" to add another item and modify appropriate properties. Press "OK" and save your page.

That's it. In the source view this looks like this:

<cc1:PieChart ID="PieChart1" runat="server">
        <cc1:PieChartDataItem PullOut="True" Title="Yes" Value="32" />
        <cc1:PieChartDataItem Title="No" Value="68" />
        <cc1:ChartLabel Align="Right" Text="Do you smoke?" TextColor="#FF8000" TextSize="20" />

and when we run our project it looks this way


In the next part I'll show you how to bind pie chart to data.

kick it on

Tags: , ,

Copyright © 2003 - 2018 Alan Mendelevich
Powered by BlogEngine.NET