Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

3D Pie Chart Web Control

4.94/5 (16 votes)
8 Apr 2010CPOL3 min read 1   2.1K  
3D Pie Chart ASP.NET Server Control using Julijan Sribar's modal

Introduction

Although Microsoft Chart Controls are much superior and popular, they only work with Microsoft .NET Framework 3.5 or greater. But thanks to Julijan Sribar for his wonderful 3D pie chart control for Windows Form. I have converted his Windows Form control ASP.NET server controls without many changes to his core architecture. As a result, we now have a useful 3D pie chart for ASP.NET 2.0 developers. I believe there are more Framework 2.0 developers than any other .NET Frameworks and I thought it's worth writing a nice 3D pie chart control for these majority .NET developers.

Screen.gif

The Origin

As mentioned above, this project is a slight modification of Julijan Sribar's 3D Pie Chart control. For a deeper understanding of how this 3D Pie Chart is implemented, refer the original post '3D Pie Chart' by Julijan Sribar.

So What's Changed?

Nothing drastic! Added 2 new classes and modified the main PieChartControl.cs.

PieChartControl.cs

  1. Removed inheritance from Windows Form Panel
  2. Removed mouse functions, as they are not relevant in a web environment
  3. Made the DoDraw() function to draw on a Bitmap instead of the Panel Canvas
  4. Removed Tooltip property and implemented it in Pie3DWebControl.cs
  5. Added a new property to return PieSlices in order to create Image Map Anchors
  6. Added Font and ForeColor property to set text attributes

PieChart.cs

  1. Made PieSlices visible to external members, in order to create Image Map Anchors

PieSlice.cs

  1. Has a new property which gives the Arc area - this enables creating precise Image Maps
    C#
    public GraphicsPath ArcPath
    {
        get {
            GraphicsPath arcPath = new GraphicsPath();
            arcPath.AddPie(m_boundingRectangle.X, m_boundingRectangle.Y,
                m_boundingRectangle.Width, m_boundingRectangle.Height,
                (float)m_startAngle, (float)m_sweepAngle);
            return arcPath;
        }
    }

Pie3DWebControl.cs

  1. ASP.NET Server Control Wrapper
  2. Converts comma separated strings to arrays:
    C#
    public string Values
    {
        get {return string.Join(",", Array.ConvertAll<decimal,>(
            m_Values, new Converter<decimal,>(Convert.ToString)));}
        set {m_Values = Array.ConvertAll<string,>(
            value.Split(",".ToCharArray(),
            StringSplitOptions.RemoveEmptyEntries),
            new Converter<string,>(Convert.ToDecimal));}
    } 
  3. Easy to use ASP.NET control:
    ASP.NET
    <cnt:PieChart3D 
        runat="server" 
        id="ChartControl1" 
        Links="http://www.mozi...,http://www.microsoft..,http://www.google...,
                http://www.apple...,http://www.opera..."
        Colors="orange,blue,yellow,purple,red"
        Values="46.5,35.3,11.6,3.8,2.1"
        Texts="Firefox,Internet Explorer,Google Chrome,Safari,Opera" 
        SliceDisplacments="0.05,0.05,0.4,0.05,0.05"
    />

IeImgHandler.cs

In order to reduce the number of call backs to server and to avoid temporary storages, I have used the data URI scheme technique to store the images within the HTML itself. But Internet Explorer 7 and earlier versions don't support this and, Internet Explorer 8 does support but limits the image size to be not more than 32K. In order to tackle this incompatibility, I have used the old fashioned Temporary Storage mechanism if the user agent is Internet Explorer.

C#
//NOTE: This code is in Pie3DWebControl.cs
if (Page.Request.Browser.IsBrowser("IE"))
{
    Context.Session[m_ChartImg.ClientID] = oMem.ToArray();
    m_ChartImg.Src = "_getchart.aspx?imgId=" + m_ChartImg.ClientID;
}
else
    m_ChartImg.Src = "data:image/png;base64," + 
                    Convert.ToBase64String(oMem.ToArray(),
                    Base64FormattingOptions.None);

As you can see above, if the client browser is Internet Explorer, the PNG image is stored in a Session with an Unique ID and Internet Explorer gets it in a separate request. In order to handle this request, an httpHandler is implemented to process the requests that come for the '_getchart.aspx' without having a physical file. Processing the request for _getchart.aspx is the functionality of this class and it implements System.Web.IHttpHandler and System.Web.SessionState.IRequiresSessionState interfaces.

  • System.Web.IHttpHandler: Defines the contract that ASP.NET implements to synchronously process HTTP Web requests using custom HTTP handlers.
  • System.Web.SessionState.IRequiresSessionState: Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.
C#
public void ProcessRequest(System.Web.HttpContext context)
{
    context.Response.Clear();
    context.Response.Cache.SetExpires(DateTime.Now.AddDays(1));
    context.Response.Cache.SetValidUntilExpires(true);
    context.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
    context.Response.Cache.AppendCacheExtension("post-check=900, pre-check=3600");
    context.Response.ContentType = "image/png";
    context.Response.BinaryWrite((byte[])System.Web.HttpContext.Current.Session[
                                    context.Request["imgId"]]);
} 

How to Use this Control?

Once you download and compile the PieChart3DWebcontrol project...

  1. Create a Web Project / Or open your existing web project
  2. Add reference to PieChart3DWebcontrol.dll
  3. Open the web.config and add the following line under the <system.web>:
    XML
    <httpHandlers>
        <add verb="*" path="_getchart.aspx" 
          type="WebControl.IeImgHandler,PieChart3DWebcontrol" />
    </httpHandlers>

    This line is to process the requests that come to '_getchart.aspx' by the IeImgHandler - as explained earlier in this article.

  4. Open the aspx page where you want to insert the control and register the control on top.
    ASP.NET
    <%@ Register Namespace="System.Drawing.PieChart.WebControl" 
        Assembly="PieChart3DWebcontrol" 
        TagPrefix="cnt" %>
  5. Finally insert the control:
    ASP.NET
    <cnt:PieChart3D 
        runat="server" 
        id="chart1" <!-- control id -->
        Width="500" <!-- (int) Width of the chart Default:400 -->
        Heght="300" <!-- (int) Height of the chart Default:200 -->
        Values="10,11.5,23.23,30.567" <!-- (float array) Comma separated values to 
                                         plot chart-->
        Texts="aaaaa,bbbbbb,cccccc,ddddd" <!-- (string array) 
    				Comma separated strings to 
                                         label each segment-->
        Links="http://www.aaa.com,http://www.bbb.com..." <!-- (string array) Comma 
                                         separated string - links for each segment-->
        Colors="blue,red,#3388FA..." <!-- (string array) Comma separated string - 
                                        colours for each segment -->
        SliceDisplacments="0.05, 0.1, 0.05..." <!-- (float array) 
    					comma separated length 
                                                  of displacement for each segment-->
        Opacity="150" <!-- (int) Transparency level of all segments, Default: 160-->
        ShadowStyle="GradualShadow" <!-- NoShadow/UniformShadow/GradualShadow - 
                                        Default:GradualShadow  -->
        EdgeColorType="DarkerThanSurface" <!-- NoEdge/SystemColor/SurfaceColor/
                 DarkerThanSurface/DarkerDarkerThanSurface/LighterThanSurface/
                 LighterLighterThanSurface/Contrast/EnhancedContrast/FullContrast 
                           - Default:DarkerThanSurface -->
        FontFamily="Arial" <!-- (string) Font name Default:Verdana-->
        FontSize="12" <!-- (int) Font size Default: 10 -->
        FontStyle="Bold" <!-- Regular/Bold/Italic/Underline/Strikeout -->
        ForeColor="#cceedd" <!-- (string) Label color, Default: Black -->
    />

History

  • V 1.00 - 08/Apr/2010 15:00 - First submission

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)