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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:PlaceHolder ID="ChartPlaceHolder" runat="server" />
    </div>
    </form>
</body>
</html>

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");

conn.Close();

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:

chart.Graphs.Add(graph1);
chart.Graphs.Add(graph2);

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

chart.DataBind();
ChartPlaceHolder.Controls.Add(chart);

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

 amcharts_code_behind

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

Download the source code here: CodeBehindBar.zip (1kb)

kick it on DotNetKicks.com

Tags: , , ,

Spread amMap

5/29/2008 11:57:05 AM

Download Day 2008Mozilla is aiming at Guiness record by trying to force as much people as possible to download Firefox on a certain "Download Day" with actual date not set yet. The idea is brilliant marketing move and lame flashmob in general but that's not important. What's important is that the use my friend's Antanas' amMap interactive map control on the site's front page.

I bet he's biting his elbows right now guestimating how much pageviews/downloads/sales he would get if they've used a free version (with link back to amMap.com) rather than bought a commercial license :)

Tags: , ,

New ASP.NET Controls for amCharts

4/18/2008 4:00:45 PM

We've just released a new version of ASP.NET Controls for amCharts.

Thanks for spreading the word! Highly appreciated.

Tags: ,

Property Naming

4/17/2008 4:10:53 PM

I'm implementing support for new features in amCharts 1.5 where you can set Left and Top coordinate of several objects to be measured from opposite side meaning that if you set Left to 20px and specify that this should be actually 20px to the left from the right side of parent object (but it's still a coordinate of the Left corner (not right)). I know it's confusing :)

First I thought I would name new properties Bottom and Right but then I understood that this is not accurate since these are still Top and Left and only the axes change. Now I decided to add 2 boolean properties TopMeasuredFromBottom and LeftMeasuredFromRight but these look quite ugly to me.

Do you have an idea for better naming or/and approach?

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" 
CodeFile="ExternalDataForPieChart.aspx.cs"
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
        "http://www.hillaryclinton.com/", "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
        "http://www.barackobama.com/", "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
    Response.Write(myChart.Items.GetItemsXml().OuterXml);
}

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:

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:

 default_settings

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">
</cc1:piechart>

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" 
    backgroundfile="../../images/usa_flag_by_freefotouk_520.jpg"
    colors="Blue,Red" externaldatafileurl="~/ExternalDataForPieChart.aspx"
    height="340px" pieangle="30" pieheight="15"
    reloaddatainterval="30" slicelinktarget="_blank" 
    DataLabelLineColor="#FFFFC0" ForeColor="#FFFFC0" LegendBackgroundAlpha="30" LegendColor="Black">
    <Labels>
        <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" />
    </Labels>
</cc1:piechart>

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:

final_result

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 DotNetKicks.com

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

sqldatasource

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

choose_your_connection

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

save_connection_string

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

configure_select_statement

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

test_query

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.

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

disable_legend

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

databound_piechart

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

pie_properties

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.

grouping_properties

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.

tilted_grouped_donut

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 DotNetKicks.com

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.

Setup

First we need to download amCharts controls and setup our environment. To download amCharts navigate to http://www.amcharts.com/download . 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.

choose_toolbox_items_dialog

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

dll

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

 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.

ampie_files

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.

design_pane

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.

 properties_labels

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.

label_editor

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

properties_items

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

dataitemeditor

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">
    <Items>
        <cc1:PieChartDataItem PullOut="True" Title="Yes" Value="32" />
        <cc1:PieChartDataItem Title="No" Value="68" />
    </Items>
    <Labels>
        <cc1:ChartLabel Align="Right" Text="Do you smoke?" TextColor="#FF8000" TextSize="20" />
    </Labels>
</cc1:PieChart>

and when we run our project it looks this way

in_browser

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

kick it on DotNetKicks.com

Tags: , ,

ASP.NET Controls for amCharts Released

3/18/2008 4:13:13 PM

Recently I've been working on a product called "ASP.NET Controls for amCharts". For those who don't know - amCharts is the best interactive web charting software available and ASP.NET Controls for amCharts make it easier to generate and customize the charts from ASP.NET/Visual Studio.

Today we have finally released version 1.0 of the controls.

Download ASP.NET controls for amCharts.

Tags: ,

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