ailon's DevBlog: Development related stuff in my life

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: , ,

Fresh Reinstall of HTC Touch

3/19/2008 5:55:25 PM

I've upgraded my microSD card to 4GB and decided that this is a good time to reinstall my HTC Touch hopefully fixing some of mistakes I've made during the first 6 months I own it. This post is for my future references for the most part, so I don't have to invent the wheel if I need to do this again. But you are welcome to use this as a reference too.

  1. Hard Reset. Hard Reset on HTC Touch is performed by holding both Call and End buttons and pressing Reset with stylus (hold Call and End until you see a warning message). Details and pictures here. Follow the instructions on screen. Install WMDC/ActiveSync on your PC if you don't already have it.
  2. My Mobiler. My Mobiler is a great free software to control your Windows Mobile device from your PC. I don't use it much in everyday life but in cases like this when you install lots of things it makes life way easier.
  3. Alternative HTC Home Plugin. This is probably the only "hack" that I do. So I decided to do it first in case I screw everything up and have to start over.
    Default HTC Touch Home plugin includes only 3 tabs: home, weather and program launcher. I want to add quick dial and profiles to that. To do that I've used HTC Home Customizer (HHC).
  4. Hide SIM Contacts. In my experience SIM contacts interfere with "normal" phone contacts so I tend to hide them. To do that we need to edit the registry. I've used CeRegEditor for that but there are many registry editors out there that work quite well:
    1. Go to HKEY_CURRENT_USER\ControlPanel\Phone
    2. Create new DWORD key named ShowSim and value 0 to hide SIM contacts.
  5. WMDC setup. Windows Mobile Device Center (for Vista) is available on HTC's CD or as a download from Microsoft. I leave all details intact, except I uncheck email synchronization with Outlook (since I don't use it).
  6. PocketCM Keyboard and PocketCM Contast. Finger friendly virtual keyboard and contact manager.
  7. GPRS. For my operator (Bite) I just go to Settings->Connections->Add a new modem connection and specify access point name "wap". Nothing else.
  8. WiFi. Just enable WiFi and connect to my network. All default encryption parameters. Enter appropriate key.
  9. GMail. I check my GMail mailbox via IMAP using Pocket Outlook. Don't allow it to try to get the settings automatically. Here are important general settings for GMail via IMAP:
    • Incoming mail server: imap.gmail.com:993
    • Account type: IMAP4
    • Username: full email address
    • Outgoing (SMTP) mail server: smtp.gmail.com:587
    • Outgoing server requires authentication: checked
    • Use the same user name...: checked
    • Advanced server settings: require SSL for both incoming and outgoing email
    • Advanced download settings: When deleting messages - delete them off the server.
    • Message format: Plain Text
  10. Microsoft Office Mobile 6.1. I don't remember why would I want this update but I still install it. This time I wont make the same mistake of installing this into the device memory.
  11. eBook readers. I use CHM eBook Reader for my technical CHM ebooks and AlReader for my fiction (official site seems to be unavailable but download links are available here)
  12. Instant messaging. I don't chat much on my phone but I have Skype and mChat installed and configured just in case.
  13. ClearTemp. ClearTemp is a small utility to free your device from temporary files and other garbage in case you run out of space. It also lets you change your temp directories to memory card so you have more space to waste :)
  14. Bluetooth and GPS. I have an external GPS receiver of some Taiwanese brand I forgot :). The model name is HI-406BT. I don't have it with me today but here are the required settings for it to work:
    • In Bluetooth setting partner the devices and assign COM6 to the GPS receiver
    • In "External GPS" settings:
      • GPS program port: COM2
      • GPS hardware port: COM6
      • Baud rate: 4800
      • Access: Manage GPS automatically - checked
    • However in navigation software I've still used the COM6 so I don't actually know what are the generally correct settings and can't check now.

So basically this is it. That's what I want to have on my phone right away after the hard reset. Everything else can wait.

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: ,

Photoshop: Universal Rounded Corners Action

3/13/2008 5:45:39 PM

Note: I'm not an experienced Photoshop user. I know next to nothing about Photoshop but I was presented with a task and this is how I solved it. There could be easier, faster and/or better solutions but this one worked for me.

The problem

There's no "single click" solution to create rounded corners for your photo (or some other image) in Photoshop. There are several ways to achieve this effect with "rounded rectangle" method being probably most popular. At least it is the most popular in Google search for "photoshop rounded corners". In short: you just draw a path using rounded rectangle tool, make selection out of it, inverse the selection and delete what's left.

This is all fine when you need to do it once. But what if you need to do it multiple times on images of various orientations and sizes? You can create a simple "Action" to repeat these simple steps but you will be stuck with a fixed size.

The solution

In short: my solution was to deal with one corner at a time, rotate the canvas and work with the same corner which is now actually not the same corner and so on.

Here are the "Action" steps in detail:

This is our original image

IMG_4578

1. Open your image and select "Rounded Rectangle Tool"

01_rounded_rectangle_tool

2. Select "Paths" as drawing method

02_paths_mode

3. We select a desired rounding radius - 10px in our case. Now we want to work with only one corner so we have to make the rectangle larger than the image. And since we are recording an "Action" we need to make it fixed size. I made it 5000x5000px (picture shows "cm" but that's too much and I was too lazy to make another screenshot)

03_rounded_rectangle_options

4. We place our rounded rectangle by the top left corner of our image

04_place_rounded_rectangle

5. In the Paths palette select "Make Selection..."

05_make_selection

6. In "Make Selection" dialog leave the defaults (unless you want something else) and click OK

06_make_selection_dialog

7. Inverse the selection and we have our rounded corner selected. Now just delete the selected contents

07_inverted_selection

8. Now we rotate the canvas by 90 degrees in your preferred direction

08_rotate_90

9. Repeat steps 4-8 three more times and you are done. Here's the result

cat_rounded

Download

Here's the "Action" to automatically create 10 pixel rounded corners for images of any dimensions and forms (up to 5000x5000px). Download rounded.zip (0.5kb)

Tags:

Converting HTML font sizes to pixels

3/7/2008 11:40:12 AM

When you create a custom ASP.NET control most of the times you inherit it from WebControl class or one of it's derivatives. Among other properties WebControl has a Font property of FontInfo type which in turn has a Size property of FontUnit type. Users can set the yourControl.Font.Size to any HTML/CSS compatible value from 12pt to 1.2em to x-large.

This is all fine while your control outputs plain HTML. But at this moment I'm working on a controls which use Flash controls as their output and Flash knows nothing about font sizes in points let alone x-small & co. (at least I was told so by my flash developer colleague). So what I needed was a way to convert all the reasonable FontUnit values to some more or less equivalent pixel sizes. So after some experiments I came up with this FontSizeConverter class with only one static method to convert FontUnit to pixels.

Keep in mind that this is only a raw approximation and doesn't pretend to be completely correct and universal solution. Em and Percentage values use 16px as base.

public class FontSizeConverter
{
    public static int ToPixels(FontUnit unitSize)
    {
        int result = 16;

        if (unitSize.Type != FontSize.NotSet && unitSize.Type != FontSize.AsUnit)
        {
            // size in x-small, etc
            switch (unitSize.Type)
            {
                case FontSize.XXSmall:
                    result = 9;
                    break;
                case FontSize.XSmall:
                    result = 10;
                    break;
                case FontSize.Smaller:
                case FontSize.Small:
                    result = 13;
                    break;
                case FontSize.Medium:
                    result = 16;
                    break;
                case FontSize.Large:
                case FontSize.Larger:
                    result = 18;
                    break;
                case FontSize.XLarge:
                    result = 24;
                    break;
                case FontSize.XXLarge:
                    result = 32;
                    break;
                default:
                    result = 16;
                    break;
            }
        }
        else if (unitSize.Type == FontSize.AsUnit)
        {
            switch (unitSize.Unit.Type)
            {
                case UnitType.Pixel:
                    result = (int)Math.Round(unitSize.Unit.Value);
                    break;
                case UnitType.Point:
                    result = (int)Math.Round(unitSize.Unit.Value*1.33);
                    break;
                case UnitType.Em:
                    result = (int)Math.Round(unitSize.Unit.Value * 16);
                    break;
                case UnitType.Percentage:
                    result = (int)Math.Round(unitSize.Unit.Value * 16 / 100);
                    break;
                default:
                    // other types are not supported. just return the medium
                    result = 16;
                    break;
            }
        }

        return result;
    }
}
kick it on DotNetKicks.com

Tags: , ,

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