In this article I will try and describe how to set up your Visual Studio 2008 project so you can display some Microsoft Charts on your ASP.NET pages. The first thing you will want to do is install MS Charts on your development machine (and of course, it will need to be run on each of your web servers that you plan on having chart pages on).
You can download the MS Charts installation file from the Microsoft site, located here: http://www.microsoft.com/downloads/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en
You will also need to install the MS Charts Add-In for Visual Studio 2008 so you can develop your charts from the Microsoft sites, located here: http://www.microsoft.com/downloads/details.aspx?familyid=1D69CE13-E1E5-4315-825C-F14D33A303E9&displaylang=en
Now, you will want to make sure that your web site has a reference to the newly installed .NET component, so add the following .NET component to your web solution: “System.Web.DataVisualization”.
In order to work properly, you will need to make some Web.Config changes. Here are the necessary Web.Config changes for your charts to execute.
The following goes in <appSettings> section (usually located beneath the </configSections> section)
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\Temp\;"/>
Important: You will want to change the c:\Temp\ directory. If you are using a web farm, I recommend using a shared folder that all the web servers can read and write to, but you may have to discuss this with your system administrator.
The following goes into the <system.web><pages><controls> section:
<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
The following goes in <system.web><compilation><assemblies> section
<add assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
The following goes in <system.web><httpHandlers> section
<add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
The following goes in <system.webServer><handlers> section
<remove name="ChartImageHandler"/> <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
That is all the Web.Config changes complete. Now it is time to place a chart into your web page.
Select the web page that you want to use to display the chart. You will want to place a chart object onto the page, so enter code similar to that shown below into the aspx page.
<asp:Chart ID="Chart1" runat="server" EnableViewState="true"> <Series> <asp:Series Name="Default" BorderColor="180, 26, 59, 105" Color="220, 65, 140, 240"> </asp:Series> </Series> <ChartAreas> <asp:ChartArea Name="Default" BackColor="Transparent" BorderColor="Transparent"> </asp:ChartArea> </ChartAreas> </asp:Chart>
In the code-behind file, you will need to reference the charting namespace. Also, you will need to set up the chart in the page load. You may also want to set up a click event also, like shown in the code below:
Imports System.Web.UI.DataVisualization.Charting Partial Class SomePage Inherits System.Web.UI.Page Protected _PieExplodedIndex As Integer = 0 ' Default exploded pie slice Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then LoadMSChart() End If End Sub ' Load the chart Private Sub LoadMSChart() Dim arXValues As ArrayList = New ArrayList Dim arYValues As ArrayList = New ArrayList ' Build up the x and y values (pull from a database, whatever) arXValues.Add("Stefan") arXValues.Add("Rodger") arXValues.Add("Andersen") arYValues.Add(100) arYValues.Add(80) arXValues.Add(100) ' Set chart type Chart1.Series("Default").ChartType = SeriesChartType.Pie ' Show hand pointer so user knows they can click on the pie chart Chart1.Style.Add("Cursor", "Hand") ' Databind the x and y values to the chart Chart1.Series("Default").Points.DataBindXY(arXValues, arYValues) ' Enable 3D Styling Chart1.ChartAreas("Default").Area3DStyle.Inclination = 20 Chart1.ChartAreas("Default").Area3DStyle.Enable3D = True Chart1.ChartAreas("Default").Area3DStyle.LightStyle = LightStyle.Realistic Chart1.ChartAreas("Default").Area3DStyle.Rotation = 45 Chart1.ChartAreas("Default").BackGradientStyle = GradientStyle.DiagonalRight ' Say that we want the slice index as the postback value when user clicks on the chart Chart1.Series(0).PostBackValue = "#INDEX" ' Size up the chart Chart1.Width = 270 Chart1.Height = 250 ' Calculate Chart Size, since exploding pie chart slices can distot the size of the pie chart CalculateChartSize() End Sub ' Clicking on the chart event handler Protected Sub Chart1_Click(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ImageMapEventArgs) Handles Chart1.Click Dim str As String = e.PostBackValue If IsNumeric(str) Then _PieExplodedIndex = CInt(str) End If ' Explode / Insert the desired data point If Chart1.Series("Default").Points(_PieExplodedIndex)("Exploded") = "true" Then Chart1.Series("Default").Points(_PieExplodedIndex)("Exploded") = "false" Else Chart1.Series("Default").Points(_PieExplodedIndex)("Exploded") = "true" End If ' Calculate Chart Size, since exploding pie chart slices can distot the size of the pie chart CalculateChartSize() End Sub ' Calculate chart size depending on exploded slice Private Sub CalculateChartSize() ' For some reason, when no slices are exploded and in 3-D, the pie chart is huge. So, make the pie chart smaller when there are no exploded indexes Dim blnExploded As Boolean = False ' See if there is an exploded slice For i As Integer = 0 To Chart1.Series("Default").Points.Count - 1 If Chart1.Series("Default").Points(i)("Exploded") = "true" Then blnExploded = True End If Next If blnExploded Then ' Normal Chart Size If Chart1.ChartAreas("Default").Area3DStyle.Enable3D Then Chart1.ChartAreas("Default").InnerPlotPosition = New ElementPosition(0, 0, 100, 100) Else Chart1.ChartAreas("Default").InnerPlotPosition = New ElementPosition(9, 9, 82, 82) End If Else ' Smaller Chart Size Chart1.ChartAreas("Default").InnerPlotPosition = New ElementPosition(9, 9, 82, 82) End If End Sub End Class
Just one more thing – at run time, you may occasionally receive an “image not found” exception. This usually happens when IIS is restarted, the bin folder contents modified or any other reason for the application to restart. To stop this error from occurring, add the following property to the code-behind of your global.asax file:
Shared _chartInitialized As Boolean
And your application begin request method should have the following piece of code. What this essentially does is instantiate the charting object before any charts are trying to render and should stop the above exception from occurring (more information about this exception can be found at http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/a5b09b47-23b2-4cb4-bc0a-966e486a65a2
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) ' Check that MS Charts is initialised If Not _chartInitialized Then _chartInitialized = True Dim s As String = ChartHttpHandler.Settings.FolderName End If End Sub
And that is pretty much it. Hope it sets you up and you make some nice charts with this cool little .NET bonus.
Hope this helps,
Stefan.
For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.