06 February 2012

MS Chart Control: Getting Started

The Main Components of a Chart
The Chart control renders a single "Chart Picture." The Chart Picture may be composed of multiple charts - say, a line chart and a bar chart. Each chart within the Chart Picture is referred to as a Chart Area. (Typically the Chart control will have only one Chart Area.) A chart contains one or more series, which are associated with a particular Chart Area. A series is a collection of data points. How the series is rendered depends on its type. A series configured to display as a line will render its data points as a continuous line. To have multiple lines in the chart you would define one series for each line. If the series is configured to display a bar or column then a bar or column is drawn for each data point.
The data points that make up a series usually have two components - an X value and a Y value - although some series types only require a single data point. For line and column series the X value indicates the position of the data point along the chart area's X axis and the Y value indicates the position of the line or the height of the column along the chart area's Y axis.

This sample chart application demonstrates how to create a basic chart in 2D and 3D that uses a code-behind page with dynamic and datasets.  Here you can find total 7 types of charts.

Using Dynamic Data Creating Charts:
Step 1: .ASPX Page
The chart area(s), series, and data points can be specified declaratively (either by entering the declarative markup by hand or via the Properties window) or programmatically in the code-behind class. Typically the series and chart area(s) are specified declaratively and the data points are populated programmatically by querying a database or some other dynamic data store. Let's start by discussing how to display a chart whose chart area, series, and data points are all specified declaratively.
  1. Column
  2. Bar
  3. Pyramid 
  4. Area
  5. Pie
  6. Line
  7. Funnel charts

<div>
        <table cellpadding="4">
            <tr>
                <td align="center">
                    Chart Type:<asp:DropDownList ID="ChartType" runat="server" Width="120px" AutoPostBack="True"
                        >
                        <asp:ListItem Value="Column">Column</asp:ListItem>
                        <asp:ListItem Value="Bar">Bar</asp:ListItem>
                        <asp:ListItem Value="Pyramid">Pyramid</asp:ListItem>
                        <asp:ListItem Value="Area">Area</asp:ListItem>
                        <asp:ListItem Value="Pie">Pie</asp:ListItem>
                        <asp:ListItem Value="Line">Line</asp:ListItem>
                        <asp:ListItem Value="Funnel">Funnel</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Chart ID="Chart1" runat="server" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)"
                        Palette="BrightPastel" ImageType="Png" BorderDashStyle="Solid" BackSecondaryColor="White"
                        BackGradientStyle="TopBottom" BorderWidth="2" BackColor="#D3DFF0" BorderColor="26, 59, 105"
                        Height="481px" Width="761px">
                        <BorderSkin SkinStyle="Emboss" />
                        <Legends>
                            <asp:Legend Name="Legend1" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"
                                IsTextAutoFit="False">
                            </asp:Legend>
                        </Legends>
                        <Titles>
                            <asp:Title Alignment="TopCenter" BackColor="180, 165, 191, 228" BackGradientStyle="TopBottom"
                                BackHatchStyle="None" Font="Microsoft Sans Serif, 12pt, style=Bold" Name="Role Summary Report"
                                Text="Role Summary Report" ToolTip="Role Summary Report" ForeColor="26, 59, 105">
                            </asp:Title>
                            <asp:Title Alignment="TopCenter" BackColor="Transparent" Font="Microsoft Sans Serif, 10pt, style=Bold "
                                ToolTip="Chart Type">
                            </asp:Title>
                        </Titles>
                        <Series>
                            <asp:Series Name="RolesCount" ChartArea="ChartArea1" Legend="Legend1" CustomProperties="DrawingStyle=Cylinder"
                                BorderColor="64, 0, 0, 0" Color="224, 64, 10" MarkerSize="5">
                                <EmptyPointStyle AxisLabel="0" />
                                <Points>
                                    <asp:DataPoint YValues="6" />
                                    <asp:DataPoint YValues="9" />
                                    <asp:DataPoint YValues="5" />
                                    <asp:DataPoint YValues="7.5" />
                                    <asp:DataPoint YValues="5.69999980926514" />
                                    <asp:DataPoint YValues="3.20000004768372" />
                                    <asp:DataPoint YValues="8.5" />
                                    <asp:DataPoint YValues="7.5" />
                                    <asp:DataPoint YValues="6.5" />
                                </Points>
                            </asp:Series>
                        </Series>
                        <ChartAreas>
                            <asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackSecondaryColor="White"
                                BorderColor="64, 64, 64, 64" ShadowColor="Transparent" BackGradientStyle="TopBottom">
                                <AxisY LineColor="64, 64, 64, 64" IsLabelAutoFit="false" Title="Roles Count" ArrowStyle="Triangle">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisY>
                                <AxisX IsLabelAutoFit="False" LineColor="64, 64, 64, 64" Title="Role Name" ArrowStyle="Triangle"
                                    Interval="1">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" IsEndLabelVisible="False" Angle="-90" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisX>
                            </asp:ChartArea>
                        </ChartAreas>
                    </asp:Chart>
                </td>
            </tr>
        </table>
    </div>

Step 2: .ASPX.CS
Based on the selected chart type the following code will be executed.  
protected void Page_Load(object sender, EventArgs e)
        {
            if (ChartType.SelectedItem.ToString() == "Bar")
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Bar;
                Chart1.Titles[1].Text = "Bar Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Pie")
            {
                Chart1.Series["RolesCount"]["3DLabelLineSize"] = "100";
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
                Chart1.Series[0]["PieDrawingStyle"] = "SoftEdge";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Pie;
                Chart1.Series["RolesCount"]["PieLabelStyle"] = "Inside";

                //Chart1.Legends["Legend1"].Enabled = true;

                Chart1.Titles[1].Text = "Pie Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Line")
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Line;
                Chart1.Titles[1].Text = "Line Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Funnel")
            {
                //Chart1.Series["RolesCount"]["3DLabelLineSize"] = "100";
                Chart1.Series["RolesCount"]["FunnelStyle"] = "YIsHeight";
                Chart1.Series["RolesCount"]["FunnelLabelStyle"] = "OutsideInColumn";
                Chart1.Series["RolesCount"]["FunnelOutsideLabelPlacement"] = "Right";
                Chart1.Series["RolesCount"]["FunnelPointGap"] = "1";
                Chart1.Series["RolesCount"]["Funnel3DDrawingStyle"] = "SoftEdge";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Funnel;
                Chart1.Series["RolesCount"]["FunnelLabelStyle"] = "Inside";
                // Set 3D angle
                Chart1.Series["RolesCount"]["Funnel3DRotationAngle"] = "5";
                // Set 3D drawing style
                Chart1.Series["RolesCount"]["Funnel3DDrawingStyle"] = "CircularBase";
                // Set minimum point height
                Chart1.Series["RolesCount"]["FunnelMinPointHeight"] = "0";
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
                Chart1.Titles[1].Text = "Funnel Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Area")
            {

                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Area;
                Chart1.Titles[1].Text = "Area Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Pyramid")
            {
                // Set pyramid data point labels style
                Chart1.Series["RolesCount"]["PyramidLabelStyle"] = "OutsideInColumn";
                // Set gap between points
                Chart1.Series["RolesCount"]["PyramidPointGap"] = "1";
                // Set minimum point height
                Chart1.Series["RolesCount"]["PyramidMinPointHeight"] = "0";
                // Set 3D mode
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
                // Set 3D angle
                Chart1.Series["RolesCount"]["Pyramid3DRotationAngle"] = "5";
                // Set 3D drawing style
                Chart1.Series["RolesCount"]["Pyramid3DDrawingStyle"] = "SquareBase";
                // Set pyramid value type
                Chart1.Series["RolesCount"]["PyramidValueType"] = "Linear";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Pyramid;
                Chart1.Titles[1].Text = "Pie Chart";
            }
            else
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Column;
                Chart1.Titles[1].Text = "Column Chart";
            }
        }
Using DataSource Controls Creating Charts:

Programmatically Specifying the Chart Data
The previous demo showed how to declaratively specify the chart's data points. These data points are more commonly specified programmatically. The demo displays the same chart as shown above but adds the data points programmatically in the Page_Load event handler. The Chart control's declarative markup in .aspx does not include the hard-coded <Points> collection, but is otherwise the same in that the markup defines a single chart area named MainChartArea and a single column series named Championships:


<div>
        <table cellpadding="4">
            <tr>
                <td valign="top" align="center">
                    Chart Type:
                    <asp:DropDownList ID="ChartType" runat="server" Width="120px" AutoPostBack="True">
                        <asp:ListItem Value="Column">Column</asp:ListItem>
                        <asp:ListItem Value="Bar">Bar</asp:ListItem>
                        <asp:ListItem Value="Pyramid">Pyramid</asp:ListItem>
                        <asp:ListItem Value="Area">Area</asp:ListItem>
                        <asp:ListItem Value="Pie">Pie</asp:ListItem>
                        <asp:ListItem Value="Line">Line</asp:ListItem>
                        <asp:ListItem Value="Funnel">Funnel</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Chart ID="Chart1" runat="server" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)"
                        Palette="BrightPastel" ImageType="Png" BorderDashStyle="Solid" BackSecondaryColor="White"
                        BackGradientStyle="TopBottom" BorderWidth="2" BackColor="#D3DFF0" BorderColor="26, 59, 105"
                        Height="481px" Width="761px">
                        <BorderSkin SkinStyle="Emboss" />
                        <Legends>
                            <asp:Legend Name="Legend1" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"
                                IsTextAutoFit="False">
                            </asp:Legend>
                        </Legends>
                        <Titles>
                            <asp:Title Alignment="TopCenter" BackColor="180, 165, 191, 228" BackGradientStyle="TopBottom"
                                BackHatchStyle="None" Font="Microsoft Sans Serif, 12pt, style=Bold" Name="Employee Data Dump"
                                Text="Employee Data Dump" ToolTip="Employee Data Dump" ForeColor="26, 59, 105">
                            </asp:Title>
                            <asp:Title Alignment="TopCenter" BackColor="Transparent" Font="Microsoft Sans Serif, 10pt, style=Bold "
                                ToolTip="Chart Type">
                            </asp:Title>
                        </Titles>
                        <Series>
                            <asp:Series Name="EmpCount" ChartArea="ChartArea1" Legend="Legend1" CustomProperties="DrawingStyle=Cylinder"
                                BorderColor="64, 0, 0, 0" Color="224, 64, 10" MarkerSize="5">
                                <EmptyPointStyle AxisLabel="0" />
                            </asp:Series>
                        </Series>
                        <ChartAreas>
                            <asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackSecondaryColor="White"
                                BorderColor="64, 64, 64, 64" ShadowColor="Transparent" BackGradientStyle="TopBottom">
                                <AxisY LineColor="64, 64, 64, 64" IsLabelAutoFit="False" Title="Employee Count" ArrowStyle="Triangle">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisY>
                                <AxisX IsLabelAutoFit="False" LineColor="64, 64, 64, 64" Title="Facility" ArrowStyle="Triangle"
                                    Interval="1">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" IsEndLabelVisible="False" Angle="0" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisX>
                            </asp:ChartArea>
                        </ChartAreas>
                    </asp:Chart>
                </td>
            </tr>
        </table>
    </div>

Code Behind :
Alternatively, you can bind data by using the Chart control's DataSource property. This involves retrieving the data from the database (or from wherever you get the data to display), assigning it to the DataSource property, and calling the Chart's DataBind method. Unlike with the DataBindTable method, when using the DataSource property you need to define a series and specify the name of the properties in the data that are to be displayed in the X and Y values in the series.  

SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
    SqlConnection con = new SqlConnection(new ConnectionString().getConnectionString());
    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
da = new SqlDataAdapter("exec StoredProcedure", con);
        da.Fill(ds, "EmpDataDump");
        if (ds.Tables["EmpDataDump"].Rows.Count > 0)
        {
Chart1.DataSource = ds.Tables["EmpDataDump"];

        // Set series members names for the X and Y values
        Chart1.Series["EmpCount"].XValueMember = "City";
        Chart1.Series["EmpCount"].YValueMembers = "EmpCount";
        Chart1.Series["EmpCount"].IsValueShownAsLabel = true;


        if (ChartType.SelectedItem.ToString() == "Bar")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Bar;
            Chart1.Titles[1].Text = "Bar Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Pie")
        {
            Chart1.Series["EmpCount"]["3DLabelLineSize"] = "100";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
            Chart1.Series[0]["PieDrawingStyle"] = "SoftEdge";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Pie;
            Chart1.Series["EmpCount"]["PieLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["PieOutsideLabelPlacement"] = "Right";
            Chart1.Titles[1].Text = "Pie Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Line")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Line;
            Chart1.Titles[1].Text = "Line Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Funnel")
        {
            Chart1.Series["EmpCount"]["FunnelStyle"] = "YIsHeight";
            Chart1.Series["EmpCount"]["FunnelLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["FunnelOutsideLabelPlacement"] = "Right";
            Chart1.Series["EmpCount"]["FunnelPointGap"] = "1";
            Chart1.Series["EmpCount"]["Funnel3DDrawingStyle"] = "SoftEdge";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Funnel;
            Chart1.Series["EmpCount"]["Funnel3DRotationAngle"] = "5";
            Chart1.Series["EmpCount"]["Funnel3DDrawingStyle"] = "CircularBase";
            Chart1.Series["EmpCount"]["FunnelMinPointHeight"] = "0";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
            Chart1.Titles[1].Text = "Funnel Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Area")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Area;
            Chart1.Titles[1].Text = "Area Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Pyramid")
        {
            Chart1.Series["EmpCount"]["PyramidLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["PyramidPointGap"] = "1";
            Chart1.Series["EmpCount"]["PyramidMinPointHeight"] = "0";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            Chart1.Series["EmpCount"]["Pyramid3DRotationAngle"] = "5";
            Chart1.Series["EmpCount"]["Pyramid3DDrawingStyle"] = "SquareBase";
            Chart1.Series["EmpCount"]["PyramidValueType"] = "Linear";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Pyramid;
            Chart1.Titles[1].Text = "Pyramid Chart";
        }
        else
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Column;
            Chart1.Titles[1].Text = "Column Chart";
        }
        // Data bind to the selected data source
        Chart1.DataBind();
         }

The resulting chart, when viewed through a browser, is shown below.
Column Chart:

Bar Chart:
Pyramid: (3D Chart)




Area:(3D Chart)

Pie:(3D Chart)

Line:

Funnel:(3D Chart)



03 February 2012

Deploying Microsoft Chart Controls

MSChart.exe setup should be used to deploy Microsoft Chart controls but what exactly need to be done to create a deployment package in Visual Studio? Visual Studio provides an easy way to add the prerequisites using bootstrappers. Now we have a detailed instructions on how to create and use .NET Chart Control bootstrapper.

Adding MS Chart Controls as a prerequisite in your Visual Studio 2008 installation package.
In order to specify a prerequisite to your deployment package something called a bootstrapper is needed. Unfortunately Microsoft do not provide a bootstrapper for the Chart Controls for the .Net Framework. Luckily it is not too difficult to create your own bootstrapper.

Here's how to do it:
Firstly you need to locate the folder in which the bootstrapper files need to be. On my machine this is here: C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\

Follow the instructions below to create the files:
  1. Create a Folder called: Microsoft Chart Controls
  2. In this new folder create a file called product.xml
  3. Use Notepad to edit this file and add the following code:
    <?xml version="1.0" encoding="utf-8" ?> 
    <!-- Bootstrapper for MS Chart Controls. Created by Phil Preen, Feb 2009,
    use at your own risk -->
    <Product xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" 
    ProductCode="Microsoft.ChartControls">
    <RelatedProducts>
    <DependsOnProduct Code="Microsoft.Net.Framework.3.5.SP1" /> 
    </RelatedProducts>
    <PackageFiles CopyAllPackageFiles="false">
    <PackageFile Name="MSChart.exe" HomeSite="MSChart.exe" /> 
    </PackageFiles>
    <InstallChecks /> 
    <Commands>
    <Command PackageFile="MSChart.exe">
    <ExitCodes>
    <DefaultExitCode Result="Success" /> 
    </ExitCodes>
    </Command>
    </Commands>
    </Product>
  4. Copy MSChart.exe (the chart controls installation package) into this folder.
  5. Create a sub-folder called: en
  6. In this new folder create a file called package.xml
  7. Use Notepad to edit this file and add the following code:
    <?xml version="1.0" encoding="utf-8" ?>
    <!-- Bootstrapper for MS Chart Controls. Created by Phil Preen, Feb 2009, 
    use at your own risk -->
    <Package
      xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper"
      Name="DisplayName"
      Culture="Culture"
      LicenseAgreement="eula.rtf"
    >
        <PackageFiles>
            <PackageFile Name="eula.rtf"/>
        </PackageFiles>
        <!-- Defines a localizable string table for error messages-->
        <Strings>
            <String Name="DisplayName">Microsoft Chart Controls for Dotnet 
    Framework 3.5 SP1</String>
            <String Name="Culture">en</String>
            <String Name="AdminRequired">Administrator permissions are 
    required to install
    Microsoft Chart Controls for Dotnet Framework 3.5 SP1. Contact your 
    administrator.</String>
            <String Name="AnotherInstanceRunning">Another instance of setup is
    already running. The running instance must complete before this setup can 
    proceed.</String>
            <String Name="GeneralFailure">A failure occurred attempting to 
    install Microsoft Chart Controls for Dotnet Framework 3.5 SP1.</String>
        </Strings>
    </Package>
  8. Copy eula.rtf (the chart controls license agreement) into this folder. To obtain this file, start the Chart Controls installer and choose the option to Save the license agreement.
 Microsoft Chart Controls will now appear in the list of prerequisites in your Visual Studio deployment settings.

 Note that because Microsoft Chart Controls is dependent upon the .Net Framework 3.5 SP1. It is necessary to have the Framework files available.

Reference Link : View

01 February 2012

ASP.NET 3.5 Chart Control

Microsoft recently released a cool new ASP.NET server control - <asp:chart /> - that can be used for free with ASP.NET 3.5 to enable rich browser-based charting scenarios:

Important download links:
Samples to get your development started are available on MSDN (http://code.msdn.microsoft.com/mschart).  Furthermore, if you have questions or suggestions, or just want to share your excitement, please visit our newly created MSDN forum for Windows Forms and ASP.NET Chart Controls.

<asp:chart /> supports a rich assortment of chart options - including pie, area, range, point, circular, accumulation, data distribution, ajax interactive, doughnut, and more. You can statically declare chart data within the control declaration, or alternatively use data-binding to populate it dynamically. At runtime the server control generates an image (for example a .PNG file) that is referenced from the client HTML of the page using a <img/> element output by the <asp:chart/> control. The server control supports the ability to cache the chart image, as well as save it on disk for persistent scenarios. It does not require any other server software to be installed, and will work with any standard ASP.NET page.

Implement the Control Into Your Page
Once installed the <asp:chart/> control shows up under the "Data" tab on the Toolbox, and can be easily declared on any ASP.NET page as a standard server control: but if you are using Visual Web Developer Express, you will need to add it manually. This can be done by right-clicking on the Data section header, and choosing Add Items. as show below.
From there, select the System.Web.UI.DataVisualization.Charting flavour of Chart, and click OK.
That's it. The Chart icon should appear in your toolbox, ready to be dragged onto the Forms Designer. Once you do, you are presented with a default vertical bar chart.

If you drag the chart control into the design-surface, Visual Studio adds some settings to the web.config. This will be done automatically so the following is just an explanation of the changes:

Web.config Changes
 

1)  ChartImage Settings
At the node <appSettings>, the following entry will be created:

<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
This is the configuration of the temporary storage, where the generated files should be placed at. Please be aware of the fact that the storage will use a large amount of space, depending on how many charts
will be generated.
2)  ChartImage.axd Handler
At <system.web><httpHandlers>, the following entry will be added:

<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" />

The chartimage.axd is the main-component of the chart-control. The handler will be called for each generated image.
3)  Control-definition
In the node <system.web><pages><controls>, the tag-definition will be added:

<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture:neutral, PublicKeyToken=31bf3856ad364e35" />

This will add the tag-support, that we can use a <asp:chart /> tag in our aspx pages.
4)  Reference to the DataVisualization Assembly
At the end, a reference to the DataVisualization assembly will be added at <system.web><compilation><assemblies>:
<add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture:neutral, PublicKeyToken=31bf3856ad364e35"/>

Default Chart-element in aspx Page
In the aspx page, where you dragged the control in, Visual Studio will add the default chart-control to the code:
<asp:Chart ID="Chart1" runat="server"> 
         <Series> 
                  <asp:Series Name="Series1"></asp:Series> 
         </Series>
         <ChartAreas>
                 <asp:ChartArea Name="ChartArea1"> </asp:ChartArea> 
         </ChartAreas> 
</asp:Chart>

Charting Quickstart
Before we begin using the chart control, I would like to explain the properties "Series" and "ChartAreas":

Series :
The Series collection contains the data-points for one or more data-series. Basically for each line in the chart (consisting of multiple data-points), one series of data is required.
Each series can have its own ChartType. Additionally, each series can be assigned to any ChartArea where each series can also have its own rendering-properties (for example colors, labels, etc.).

ChartAreas :
The ChartArea collection can have one or more configurations which controls the rendering of a chart.
Important: There must be at least one ChartArea definition that the rendering will be executed!

Now we know that we have to add a <asp:Series> in the property <series><asp:ChartArea> at the <ChartAreas> defined, otherwise we would get just a white picture. which contains our datapoints. Also we have to be sure that there is at least one
After changing the chart-control code to the following:

<asp:Chart ID="cTestChart" runat="server">
         <Series>
                 <asp:Series Name="Testing" YValueType="Int32">
                           <Points> 
                                  <asp:DataPoint AxisLabel="Test 1" YValues="10" /> 
                                  <asp:DataPoint AxisLabel="Test 2" YValues="20" /> 
                                 <asp:DataPoint AxisLabel="Test 3" YValues="30" />
                                 <asp:DataPoint AxisLabel="Test 4" YValues="40" /> 
                         </Points> 
               </asp:Series>
          </Series>
         <ChartAreas> 
               <asp:ChartArea Name="ChartArea1">  </asp:ChartArea> 
        </ChartAreas> 
</asp:Chart>

We will get this output in the rendered output page:

So we successfully created our first chart!


Deploying MS Chart Controls:(Production Server)
"MSChart.exe" setup should be used to deploy Microsoft Chart controls and
Changes needed  in the web.config as shown below.

From

<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
To
<add key="ChartImageHandler" value="storage=file;timeout=20;" />

Reference Links : http://www.4guysfromrolla.com/articles/072209-1.aspx



19 January 2012

reCAPTCHA : Free Captcha service for ASP.NET

What is reCaptcha?
  1. reCAPTCHA is a free CAPTCHA service that helps to digitize books, newspapers and old time radio shows.
  2. It’s Free! Yep, reCAPTCHA is free.
  3. It’s Easy. reCAPTCHA is a Web service. As such, adopting it is as simple as adding
    a few lines of code on your site.
  4. It’s Accessible. reCAPTCHA has an audio test that allows blind people to freely
    navigate your site.
  5. It’s Secure. Most other CAPTCHA implementations can be easily broken.
  6. It’s Popular. Over 100,000 sites use reCAPTCHA, including household names like Facebook, Ticketmaster, and Craigslist.
  7. Whenever uses input data in reCaptcha control, they actually help digitizing books.
Moreover is very easy to integrate reCaptcha in our websites. Below are the steps
which are required to integrate it into a ASP.NET page.
Steps to Integrate reCaptcha in ASP.NET 

Step1:  Register for a reCaptcha key : As a first step we need to register for recaptcha keys. Navigate to Get reCaptcha URL to signup for the keys. After we register for the keys, we get a public and private keys which we need to use in our asp.net page. By default all keys work on localhost as well. 

Step2:  Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project. 
Step3:  Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:
Step4:  At the top of the aspx page, insert this: 
      <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

Step5:  Then insert the reCAPTCHA control inside of the form tag and Enter your Publickey and PrivateKey
 <recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="Red" PublicKey="" PrivateKey="" Height="30px" />
Step6:  Make sure you use ASP.NET validation to validate your form (you should check Page.IsValid on submission)
As an example I created a ASP.NET page whose markup and code behind code looks as given below:
Markup: (.aspx)


<asp:Label  Visible="true" ID="lblResult" runat="server" />
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="Red" PublicKey="" PrivateKey="" Height="30px" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

Code-behind(.aspx.cs)


protected void  btnSubmit_Click(object sender, EventArgs e)
    {
        recaptcha.Validate();
        if (recaptcha.IsValid)
        {
              if (Page.IsValid)
             {
                   lblResult.Text = "Captcha sucessfull!";
                   lblResult.ForeColor = System.Drawing.Color.Green;
             }
             else
            {
                 lblResult.Text = "Incorrect";
                 lblResult.ForeColor = System.Drawing.Color.Red;
             }
         }
    }

When I entered correct captcha text and pressed submit button following was the output:
 When I entered incorrect captcha text and pressed submit button following was the output:







  1. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:










  2. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:













  3. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  4. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:










  5. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  6. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:










  7. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  8. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:










  9. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  10. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:












  11. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  12. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:







  13. Read more: http://www.techartifact.com/blogs/2011/01/recaptcha-free-captcha-service-for-asp-net.html#ixzz1jsTc1Pwi




  14. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.









  15. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:






  16. 18 January 2012

    Steps for Session InProc Mode to Session StateServer

    Many articles are discussing about advantages of using Session StateServer or SQLServer over InProc Mode.  One basic reason why I choose StateServer Mode is when your website is running on Third Party Hosting than you will notice that Session Timeout can occur anytime depends on load of traffic on your server.

    If your website has large number of visitors and session timeout can cause problem, It is better to change Session Mode Session="InProc" to Session="StateServer".

    Main Advantage of Session StateServer (Best to choose while hosting on third party server)
    1.  Session is persistent and reliable.
    2. Avoid Session Timeout due to Memory shortage on server (IIS Setting).

    Main Disadvantage
    1. Poor Performance compare to Session="InProc"
    2. Session_End Event would not fire.

    Now lets understand 
    Steps for changing Session InProc Mode to Session StateServer Mode.

    Step 1:  Start Asp.net State Servcie
    1. Go to Control Panel > Administrative Tools > Services 
    2. Select Asp.Net State Service.
    3. Right Click on Asp.net State Service and choose start from popup menu.
     
    If you forget to Start Service you will receive following error.

    Server Error in '/' Application.

    Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.



    Step 2:  Change Session Mode in Web.Config File
    <sessionState mode="StateServer"
                stateConnectionString="tcpip=127.0.0.1:42424"
                cookieless="false"
                timeout="120"/>
    Note: You can adjust timeout minutes based on your requirement.  Let the tcpip server to be localhost i.e. 127.0.0.1.  Most webhosting company uses these settings unless you have different IP for StateServer and  You are not required to change Port Number.


    Step 3: Make All Object Serializable
    You should make all object in your website to serializable.
    Note: To take advantage of Session StateServer or SQLServer or Custom Mode, object needs to be serialized.

    Example:  If your project contains class files for creating DAL (Data Access Layer), you should append Serializable to every class definition in order to make class Serializable.
     
    [Serializable]
    Class Department
    {
            long   _deptId;
            string _deptName;
            
            public long DeptId
            {
                   get {   return _deptId; }
                   set {  _deptId = value; }                  
             }

            public string DeptName
            {
                   get {   return _deptName; }
                   set {  _deptName = value; }                  
             }
    }

    IMPORTANT While doing Serialization
    Remember SQLConnection cannot be serialized.

    You might receive following error if you don't handle this situation.

    Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.


    So to handle this situation you need to do following thing.

    1. Mark SQLConnection Object as NonSerialized
    [NonSerialized] protected SqlConnection _mainConnection;

    2. Mark your Class as Serializable and derive from IDeserializationCallback
    Example:
    [Serializable]
    Class Department: IDeserializationCallback
    {
            long   _deptId;
            string _deptName;
            
            public long DeptId
            {
                   get {   return _deptId; }
                   set {  _deptId = value; }                  
             }

            public string DeptName
            {
                   get {   return _deptName; }
                   set {  _deptName = value; }                  
             }

            //Create this Method Inside your Class
           void IDeserializationCallback.OnDeserialization(object sender)
            {
                //Recreate your connection here
                _mainConnection = new SqlConnection();
                _mainConnection.ConnectionString =
                        ConfigurationSettings.AppSettings["connStr"].ToString();           
            }
    }
     
    Reference Link: Click Here

    DataView.Table - Problem to Persist Sort or Filter View

    I was trying to Sort data with DataView and was trying to convert Dataview to table. I have notice even though view is sorted, when you try to convert it to table it would return only default sort.

    Example:
    //I was trying to perform something as following
    DataTable dtGrid = GetData();
    DataView dvSort = new DataView(dtGrid);
    dvSort.Sort = "CreationDate DESC";
    dtGrid = dvSort.Table; //Will Not Persist Sort Order

    In above example even though view is in sorted order, when i tried to convert it to table it would return only default view. In order to get Sorted view (Persist Sort order) instead of using DataView.Table you should use DataView.ToTable() method

    So if you changed above code with following it would start working as expected.

    DataTable dtGrid = GetData();
    DataView dvSort = new DataView(dtGrid);
    dvSort.Sort = "CreationDate DESC";
    dtGrid = dvSort.ToTable(); //Persist Sort Order

    Copy of Session Object

    Many times we try to make copy of session object, but in case when we are modifying copied object we might noticed that session object gets updated automatically, the reason is both copied object and session object are pointing to same location, even if you tried to use "new" operator while creating object.

    Scenario
    Let say you have Member Class as mentioned under
    public class Member
    {
            public string FirstName { get; set; }
            public string LastName { get; set; }
    }


    Problem:
    Member objMember = new Member();
    objMember.FirstName = "Sachin";
    objMember.LastName = "Tendulkar";

    Then try to save object in Session
    Session["MemberObj"] = objMember;

    This method will work good till we are just accessing object from session, but in case if we try to update object created from session it will update value of session also. That is,

    Member newMember = new Member(); //Even though object is created using "new" keyword.
    newMember = (Member) Session["MemberObj"];
    newMember.FirstName = "Kapil"; //This will update session FirstName also.

    Solution:
    To make copies of session you need to create a clone method in class. In above class create a method clone, to support copy of session.

    public class Member
    {
    public string FirstName { get; set; }
            public string LastName { get; set; }

    public Member clone()
         {
                Member cloneMember = new Member();
                 cloneMember.FirstName = this.FirstName;
                cloneMember.LastName = this.LastName;
    }
    }

    Now, while accessing session object, you can call clone method to make copy of session.

    Member newMember = new Member();
    newMember = ((Member) Session["MemberObj"]).clone();

    now if you try to modify object copied from session, will not update session object.
    newMember.FirstName = "Kapil"; //Will not update session FirstName

    Reference Link: Clickhere

    13 January 2012

    Extension Methods in C-Sharp

    You want to improve the syntax for calling common methods in your C# program, so that function names are shorter and easier to type. Extension methods provide a way to easily represent static methods as instance methods in the syntax of the C# language, which can be more intuitive and recallable for developers. Here we look at extension methods.


    Example

    Here is a custom extension method defined in a program written in the C# programming language. Generally, you will want to store your extension method class in a separate source file, such as "ExtensionMethods.cs" in your project. The file should store a static class with public static extension methods. In the rest of your source code, you can invoke these extension methods in the same way as you can call instance methods.
    Program that uses extension method on string [C#]
    
    using System;
    
    public static class ExtensionMethods
    {
        public static string UppercaseFirstLetter(this string value)
        {
     //
     // Uppercase the first letter in the string this extension is called on.
     //
     if (value.Length > 0)
     {
         char[] array = value.ToCharArray();
         array[0] = char.ToUpper(array[0]);
         return new string(array);
     }
     return value;
        }
    }
    
    class Program
    {
        static void Main()
        {
     //
     // Use the string extension method on this value.
     //
     string value = "dot net perls";
     value = value.UppercaseFirstLetter(); // Called like an instance method.
     Console.WriteLine(value);
        }
    }
    
    Output
    
    Dot net perls
     
    Description. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
    The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.

    This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.
    Calling extension method. You can call an extension method in the same way you call an instance method. In Visual Studio, an extension method in IntelliSense is represented by a different icon that has a downward arrow on it. You can use this icon to differentiate between instance and extension methods before calling them. Also the text "(extension)" is used in IntelliSense.
     

    What’s the Specification of an Extension Method?

    An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types. The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.

    How to Create my Extension Method?

    Simply, you create your own static method in your class and put this keyword in front of the first parameter in this method (the type that will be extended).

    General Tips in Extension Methods Usage

    This section is optional reading section for understanding the core idea of extension methods:
    1. This keyword has to be the first parameter in the extension method parameter list.
    2. Extension methods are used extensively in C# 3.0 and further version specially for LINQ extensions in C#, for example:
    3. It is important to note that extension methods can't access the private methods in the extended type.
    4. If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
    5. If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.