Generating a dynamic bar graph using ASP.NET and C#

Posted in ASP.NET, C# by Sumit Thomas on November 21, 2004

[tweetmeme style=”compact”]Back in the days of ASP, web developers had to rely on third party components to dynamically create images on a web page. In ASP, we would use colored tables to display a bar graph. But wouldn’t it be great if we could generate a dynamic graph by ourselves instead of relying on some third-party components. Well, the .NET framework allows us to do just that and more.

Consider a scenario where we had to display a graph representing the sales of a company from say 2000-2004. We need to generate a dynamic bar graph using the data provided to us. Let me take you through the step-by-step process to accomplish the task.

I am using Notepad and .NET framework 1.0. Why notepad? Well, I believe it’s the best way to learn .NET or for that matter any programming language and also the code is very clean.

The two classes, which we need to generate images on the fly, are System.Drawing.Bitmap and System.Drawing.Graphics. The Bitmap class is used to represent an instance of an image and the Graphics class can be used to draw lines, curves and other geometric shapes.

Be sure to check about these two classes and their methods from http://msdn.microsoft.com

So lets get started. Open Notepad and type the following two lines

We will be using these two namespaces in our application.

The method we will write to generate the graph is called ‘GenerateBarGraph’

The initial structure of the code will look like this

Bar graph generated using ASP.NET and C#

protected void GenerateBarGraph(
string graphTitle,
ArrayList xValues,
ArrayList yValues,
int barWidth,
int barSpaceWidth,
int graphHeight)
//Our code to generate bar graph will come here
private void Page_Load(object sender, System.EventArgs e)


<img src="" />

The parameters passed to the GenerateBarGraph method are as follows

graphTitle : The title of the graph
xValues : The values in the x-axis
yValues : The values in the y-axis
barWidth : The width of each bar
barSpaceWidth : The space between each bars
graphHeight : The height of the graph(excluding the title and x-values)

Change the GenerateBarGraph method as follows

protected void GenerateBarGraph(
string graphTitle,
ArrayList xValues,
ArrayList yValues,
int barWidth,
int barSpaceWidth,
int graphHeight)
int graphTitleHeight=20; // Height in pixels utilized by the title in the graph
int itemsHeight=35; // Height in pixels utilized by the items in the x-axis

The Graph’s width is calculated by adding the width of a bar and the space between
two bars multiplied by the total values in the x-axis plus the space between two bars
int graphWidth= (barWidth + barSpaceWidth) * xValues.Count + barSpaceWidth;

The maximum height that a bar can attain needs to be found from the y-values passed
as parameter
int maxBarHeight=0;

//Total height of the image is calculated
int totalGraphHeight = graphHeight + graphTitleHeight + itemsHeight;

//Create an instance of Bitmap class with the given width and height
Bitmap barBitmap=new Bitmap(graphWidth, totalGraphHeight);

Graphics class does not have a constructor and hence we call its static method
FromImage and pass the Bitmap object to it
Graphics barGraphics= Graphics.FromImage(barBitmap);

Using the Graphics object we fill the image of given dimensions with light gray color

new SolidBrush(Color.WhiteSmoke),

We create an instance of Font class available in System.Drawing. We will be using this
to display the title of the graph.
Font titleFont=new Font("Verdana",14, FontStyle.Bold);

Use the Graphics object’s DrawString method to draw the title at the specified location
new SolidBrush(Color.Red),
(graphWidth / 2) - graphTitle.Length * 5,
totalGraphHeight - itemsHeight);

//////////////Code to generate bars will come here/////////////////

Save the image to the web server’s D: drive. We use the PNG format to make it look

//Dispose off the Graphics and Bitmap objects

Change the Page_Load method as follows

private void Page_Load(object sender, System.EventArgs e)
ArrayList _years=new ArrayList();

ArrayList _sales=new ArrayList();

GenerateBarGraph("ABC Ltd. Sales (2000-2004)",_years, _sales, 50, 25, 400);

Change the source of the IMG tag used in our aspx page as follows

<img />

Now, if you run this page you will see an image displayed on the browser with the title “ABC Ltd. Sales (2000-2004)” displayed in red at the bottom

If you notice in the Page_Load method, we have passed two ArrayLists to the GenerateBarGraph method and also the other previously mentioned parameters. We will be using these two ArrayLists to display the bars.

Now replace //////////////Code to generate bars will come here///////////////// in GenerateBarGraph method with the following code.

Find the highest value in the yValues ArrayList and set it as the maximum height of the bar
foreach(int _value in yValues)
if(_value > maxBarHeight) maxBarHeight=_value;

//barXPos will store the x position of a bar
int barXPos = barSpaceWidth;
int barHeight;

Font itemsFont=new Font("Verdana",9, FontStyle.Bold);
Font valuesFont=new Font("Verdana", 7, FontStyle.Italic);

Random rnd=new Random();

for(int i=0;i  Gives the bar height in percentage with respect to
the maximum bar height set by us

((((int)yValues[i]* 100 / maxBarHeight) )* graphHeight)/100 will give the bar height in
barHeight=((((int)yValues[i]* 100 / maxBarHeight) )* graphHeight)/100;

//Draw the bar with the set brush, x and y positions, width and height

//Draw the x-value along the x-axis

//Draw the respective y value on top of the bar

//Change the x position of the next bar
barXPos += (barWidth + barSpaceWidth);

If you now run the aspx page you will notice the bar graph representing the sales of a company from 2000-2004. If you refresh the page you will see that each bar will have a new color.

The Graphics API provided by the .NET framework is very extensive and what we have seen gives us a useful startup. Do take time to understand the classes and its methods used in this article.

Technorati: , ,
Tagged with: , ,

Creating a Word document using ASP.NET and C#

Posted in ASP.NET, C# by Sumit Thomas on June 30, 2004

[tweetmeme style=”compact”]In one of my projects recently, I had to create word documents dynamically using ASP.NET. I turned to MSDN for help and was surprised to find how easy it was to do so.

I am using Visual Studio 2002 and .NET Framework 1.0. Therefore if you are using the latest versions, unlike me 😦 then do check out for the updates in the classes and methods that I am going to use in this article.

1) OK, lets start. Open up Visual Studio and create an ASP.NET Web application using C#.

2) Now we have to add a COM reference to our project. In the references dialog box, under COM you will find Microsoft Word 9.0 Object Library. Select it and add it to the project. This will add few COM dll’s in the bin directory.

3) Now the code…

object fileName="D:\\MyWord.doc";
object novalue=System.Reflection.Missing.Value;

Word.ApplicationClass objWord = new Word.ApplicationClass();
Word.Document objWordDoc=objWord.Documents.Add(ref novalue, ref novalue, ref novalue, ref novalue);


objWord.Selection.TypeText(".NET Rocks!!!");
objWord.Selection.TypeText("Savage loves .NET");

objWordDoc.SaveAs(ref fileName, ref novalue, ref novalue, ref novalue,
            ref novalue, ref novalue, ref novalue, ref novalue, ref novalue,
            ref novalue, ref novalue); 

objWord.Quit(ref novalue, ref novalue, ref novalue);

Now check the MyWord.doc file in the D: drive.

The code is pretty simple and intuitive, hence a quick explanation.

* We are first creating a object of Word.ApplicationClass
* Next we add a Word document to this object. Incase you don’t want to pass a particular parameter, use the ‘novalue’ object that we have created in the code.
* The following steps are pretty self explanatory.

The Visual Studios’ Intellisense feature will let us know of the expected parameters of each method. In the latest versions of .NET framework the number of parameters required is more.

Do check out http://msdn.microsoft.comto learn about automation in .NET

Technorati: , ,
Tagged with: , , , ,