Hi.,

After 10 days., Little bit busy in my work.,

Here I would like to share a basic step that is drawing pie and bar charts dynamically using generic handler and a query string. Here you will see bar and pie charts with random colors.



First we need to create two generic files which will plot bar and pie charts.

Lets see first bar.ashx ., Just include a "Generic file" which is in Visual studio under website ->  Add New Item , Then you will see a templates window in those templates select Generic Handler and name it as "bar.ashx"

Just copy the below code into your bar.ashx file

<%@ WebHandler Language="C#" Class="Bar" %>

using System;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing;

public class Bar : IHttpHandler {
    
    public void ProcessRequest (HttpContext context)
    { 
            string  val1 = context.Request.QueryString["val1"];
            string[] num = val1.Split(',');
                       
            displayImage(num);
            context.Response.ContentType = "image/gif";
            bmp.Save(context.Response.OutputStream, ImageFormat.Gif);
        
        
    }
    Bitmap bmp;
    public void displayImage(string []num)
    {
        
        bmp = new Bitmap(500, 500);
        Graphics graphic = Graphics.FromImage(bmp);
        
        SolidBrush whitebrush = new SolidBrush(Color.White);
        SolidBrush BlackBrush = new SolidBrush(Color.Black);
        Pen blackPen = new Pen(Color.Black, 2);

        graphic.FillRectangle(whitebrush, 0, 0, 500, 500);

        graphic.DrawLine(blackPen, new Point(20, 480), new Point(480, 480));
        graphic.DrawLine(blackPen, new Point(20, 20), new Point(20, 480));
        
        float Heighestval=float.Parse(num[0]);
        for (int i = 1; i < num.Length; i++)
        {
            if (Heighestval < float.Parse(num[i]))
                Heighestval = float.Parse(num[i]);
        }
       if (Heighestval == 0)
           Heighestval = 1;
       Random rnd = new Random();

       int thickness = Convert.ToInt32((440 / num.Length) - ((30.0 / 100) * (440 / num.Length)));
       int gap = Convert.ToInt32 ((30.0 / 100) * (440 / num.Length));
       if (num.Length <  6)
       {
           thickness = 60;
           gap = 20;
       }
       float[] val = new float[num.Length];
       for (int i = 0; i < val.Length; i++)
       {           
           val[i] = (float.Parse(num[i]) / Heighestval) * 450;
           
           graphic.FillRectangle(new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))), (i*(gap+thickness))+40, 478 - val[i], thickness, val[i]);
           graphic.DrawString(num[i], new Font("Arial", 8), BlackBrush, new Point(0, Convert.ToInt32(465 - val[i])));
           graphic.DrawString("--", new Font("Arial", 8), BlackBrush, new Point(15, Convert.ToInt32(470 - val[i])));
           graphic.DrawString((i + 1).ToString(), new Font("Arial", 8), BlackBrush, new Point((((i * (gap + thickness)) + 40) + Convert.ToInt32((thickness / 2))), Convert.ToInt32(485)));
           graphic.DrawString(num[i], new Font("Arial", 8), BlackBrush, new Point(((i * (gap + thickness)) + 40), Convert.ToInt32(465 - val[i])));
       }
        
    }

    public bool IsReusable 
    {
        get 
        {
            return false;
        }
    }

}


Now its time to create pie chart, Again include another generic handler to your project and name it as "pie.ashx"

Just copy the below code into your "pie.ashx"

<%@ WebHandler Language="C#" Class="Pie" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public class Pie : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) 
    {

        string val1 = context.Request.QueryString["val1"];
        string[] num = val1.Split(',');
        displayImage(num);
        context.Response.ContentType = "image/gif";
        bmp.Save(context.Response.OutputStream, ImageFormat.Gif);
    }
    Bitmap bmp;
    public void displayImage(string []num)
    {
        bmp = new Bitmap(500, 500);
        Graphics graphic = Graphics.FromImage(bmp);       
        SolidBrush whitebrush = new SolidBrush(Color.White);
        SolidBrush BlackBrush = new SolidBrush(Color.Black);
        Pen blackPen = new Pen(Color.Black, 2);
        graphic.FillRectangle(whitebrush, 0, 0, 500, 500);

        float tot = 0;
        for (int i = 0; i < num.Length; i++)
        {
            tot += float.Parse(num[i]);
        }
        Random rnd = new Random();

        float[] val = new float[num.Length];
        if (tot == 0)
            tot = 1;

        int gap = Convert.ToInt32((30 / 100) * (440 / num.Length));
        int thickness = Convert.ToInt32((440 / num.Length) - ((60 / 100) * (440 / num.Length)));
        if (num.Length < 16)
        {
            gap = 20;
            thickness = 10;            
        }
        
        float start = 0;
        for (int i = 0; i < val.Length; i++)
        {
            SolidBrush brush = new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255)));
            val[i] = (float.Parse(num[i]) / tot) * 360;
            graphic.FillPie(brush, 0, 0, 400, 400, start, val[i]);
            graphic.FillRectangle(brush, 410, ((i * (gap + thickness)) + 40), thickness, thickness);
            graphic.DrawString(num[i], new Font("Arial", 8), BlackBrush, 420+thickness, ((i * (gap + thickness)) + 38));
            start += val[i];
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Now open your default.aspx page and add the following controls under form tags that is between <form></form>.
<div>
    
        Enter Values with coma as seporator:&nbsp;
        <asp:TextBox ID="txtBar" runat="server" Width="215px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RfvBar" runat="server" 
            ControlToValidate="txtBar" Display="Dynamic" 
            ErrorMessage="Please enter numbers separated by coma" ValidationGroup="g1"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="btnDraw" runat="server" onclick="btnDraw_Click" 
            Text="Genrate Bar Chart" ValidationGroup="g1" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnPie" runat="server" onclick="btnPie_Click" 
            Text="Genrate Pie chart" ValidationGroup="g1" />
    
    </div>
    <asp:Image ID="imgBar" runat="server" />
    <asp:Image ID="imgPie" runat="server" />

Now open default.aspx.cs and add the following code to your page
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnDraw_Click(object sender, EventArgs e)
    {
        imgBar.ImageUrl = "~/Bar.ashx?val1=" + txtBar.Text; 
        
    }
    protected void btnPie_Click(object sender, EventArgs e)
    {
        imgPie.ImageUrl = "~/Pie.ashx?val1=" + txtBar.Text;
    }
}

Now you can generate bar chart and pie chart based on the values you have entered in the text box.

You can download the Source Code from here

I hope you enjoyed it well. If you face any problem please feel free to contact me.

See you again.

Share it

2 comments:

Post a Comment