mercoledì 9 ottobre 2013

Grafici in .Net con il DataVisualization Charting

Dalla versione 4.0 del framework .Net è disponibile un ottimo componente per disegnare grafici, ad esempio, in una pagina aspx.
Per la versione 3.5 invece bisogna scaricarlo dal sito Microsoft. Mi riferisco al componente DataVisualization.Charting che è possibile referenziare in Vistual Studio.
Visual Studio Chart

Di seguito è rappresentato un esempio di come raffigurare dei dati in un grafico a torta.
Grafico a torta

Parametri nel Web.Config
<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" >
          <assemblies>
            <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          </assemblies>
        </compilation>
      <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
        <controls>
          <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </controls>
      </pages>
      <httpHandlers>
        <add path="ChartImg.axd" verb="GET,HEAD,POST"
          type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"  />
      </httpHandlers>
    </system.web>
  <system.webServer>
    <handlers>
      <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=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  />
    </handlers>
  </system.webServer>
  <appSettings>
    <add key="ChartImageHandler" value="storage=memory;timeout=20;" />
  </appSettings>
</configuration>

Componente Chart nella pagina .aspx
<asp:CHART id="Chart1"  runat="server" Palette="BrightPastel" BackColor="#D3DFF0" Height="330px" 
        Width="530px" BorderlineDashStyle="Solid" BackGradientStyle="TopBottom" BorderWidth="2" 
        BorderColor="26, 59, 105" IsSoftShadows="False" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)">
        <Titles><asp:Title Alignment="TopRight" Text="CARS" Font="Microsoft Sans Serif, 8pt, style=Bold"></asp:Title></Titles>
      <legends>
       <asp:Legend TitleFont="Microsoft Sans Serif, 8pt, style=Bold" BackColor="Transparent" IsEquallySpacedItems="True" Font="Trebuchet MS, 8pt, style=Bold" IsTextAutoFit="False" Name="Default"></asp:Legend>
      </legends>
      <borderskin SkinStyle="Emboss"></borderskin>
      <series>
       <asp:Series ChartArea="Area1" XValueType="Double" Name="Series1" ChartType="Pie" Font="Trebuchet MS, 8.25pt, style=Bold" 
                CustomProperties="DoughnutRadius=25, PieDrawingStyle=Concave, CollectedLabel=Other, MinimumRelativePieSize=20, CollectedSliceExploded=true" 
                MarkerStyle="Circle" BorderColor="64, 64, 64, 64" Color="180, 65, 140, 240" YValueType="Double" Label="#PERCENT{P1}">
         
       </asp:Series>
      </series>
      <chartareas>
       <asp:ChartArea Name="Area1" BorderColor="64, 64, 64, 64" BackSecondaryColor="Transparent"
                    BackColor="Transparent" ShadowColor="Transparent" BackGradientStyle="TopBottom">
        <axisy2>
         <MajorGrid Enabled="False" />
         <MajorTickMark Enabled="False" />
        </axisy2>
        <axisx2>
         <MajorGrid Enabled="False" />
         <MajorTickMark Enabled="False" />
        </axisx2>
        <area3dstyle PointGapDepth="900" Rotation="162" IsRightAngleAxes="False" WallWidth="25" IsClustered="False" />
        <axisy LineColor="64, 64, 64, 64">
         <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
         <MajorGrid LineColor="64, 64, 64, 64" Enabled="False" />
         <MajorTickMark Enabled="False" />
        </axisy>
        <axisx LineColor="64, 64, 64, 64">
         <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
         <MajorGrid LineColor="64, 64, 64, 64" Enabled="False" />
         <MajorTickMark Enabled="False" />
        </axisx>
       </asp:ChartArea>
      </chartareas>
     </asp:CHART>

Codice nel file .cs
public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                PopulateChart();
        }

        protected void PopulateChart()
        {
            long car1 = 10; long car2 = 20; long car3 = 30;

            DataPoint dp1 = new DataPoint();
            dp1.SetValueY(car1);
            dp1.LegendText = "BMW";

            DataPoint dp2 = new DataPoint();
            dp2.SetValueY(car2);
            dp2.LegendText = "Ford";

            DataPoint dp3 = new DataPoint();
            dp3.SetValueY(car3);
            dp3.LegendText = "Volvo";


            this.Chart1.Series["Series1"].Points.Insert(0, dp1);
            this.Chart1.Series["Series1"].Points.Insert(1, dp2);
            this.Chart1.Series["Series1"].Points.Insert(2, dp3);
        }
    }