Display data in chart using jQuery and Highcharts

Display data in chart using jQuery and
Highcharts – Other(Pie, 3D, Donut) Charts
Chart is also called as graph and it is graphical representation of data. The data is represented in the form of bar in bar chart, line in line chart and slices using pie chart. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. If you want to develop dashboard then charting is absolutely necessary for your users especially for management.
In my previous post  Display data in chartusing JavaScript Highcharts we discussed basic elements of charts, JavaScript libraries required, model design and displaying dynamic data using jQuery.Ajax in MVC. In this post article I will show you the another useful charts like Pie and donut charts. I will also show you the how Highcharts are useful to implement drilldown and 3D charting functionality.
Let’s start with Pie Chart.

Pie Chart

 

Step 1 : Lets modify the Chart and Series model as per the required properties to bind pie chart.
usingSystem.Collections.Generic;
namespaceHighchart.WebUI.Models
{
    public class PieChartSeriesModel<T>
    {
        public string name { get; set; }
        public T y { get; set; }
        public bool sliced { get; set; }
        public bool selected { get; set; }
    }
    public class PieChartModel<T>
    {
        public string Title { get; set; }
        public string Tooltip { get; set; }
        public string SeriesName { get; set; }
        public ICollection<PieChartSeriesModel<T>> Series { get; set; }
    }
}
Step 2: Create action method which returns the json result. This json used to bind basic properties and series to Pie Chart.
public JsonResult PieChart()
        {
            var pieChartModel = new PieChartModel<double>
            {
                Title = “Browser market shares January, 2015 to May, 2015”,
                Tooltip = “{series.name}: <b>{point.percentage:.1f}%</b>”,
                SeriesName = “Browser:”,
                Series = new List<PieChartSeriesModel<double>> {
                    new PieChartSeriesModel<double>{name = “Microsoft Internet Explorer”, y= 56.33},
                    new PieChartSeriesModel<double>{name = “Chrome”, y= 24.03, selected=true, sliced=true},
                    new PieChartSeriesModel<double>{name = “Firefox”, y= 10.38},
                    new PieChartSeriesModel<double>{name = “Safari”, y= 4.77},
                    new PieChartSeriesModel<double>{name = “Opera”, y= 0.91},
                    new PieChartSeriesModel<double>{name = “Proprietary or Undetectable”, y= 0.2},
                }
            };
            return Json(pieChartModel, JsonRequestBehavior.AllowGet);
        }
Step 3: Create view container to display Pie chart.
@{
    ViewBag.Title = “Home Page”;
}
@Scripts.Render(“~/bundles/demoChart”)
<table>
   
    <tr>
        <td>
            <div id=”containerPieChart” style=”min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto; border:1px solid black;“></div>
        </td>
    </tr>
   
</table>
Step 4: Create JavaScript to bind json result to pie chart.
$(document).ready(function () {
    drawPieChartAjax();
});
       function drawPieChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/PieChart”,
        data: “{}”,
        dataType: “json”,
        success: function (Result) {
            drawPieChart(Result);
        },
        error: function(Result) {
            alert(“Error”);
        }
    });
}
function drawPieChart(data) {
    $(‘#containerPieChart’).highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: ‘pie’
        },
        title: {
            text: data.Title
        },
        tooltip: {
            pointFormat: data.Tooltip
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: ‘pointer’,
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: data.SeriesName,
            colorByPoint: true,
            data: data.Series
        }]
    });
}
Step 5: Run the application it will display Pie Chart as below. Here Chrome is selected as the default slice.
 
 

Drilldown Bar Chart

 

Step 1 : Lets modify the Chart and Series model as per the required properties to bind drilldown bar chart.
    public class DrilldownBarChartModel<T>
    {
        public string Title { get; set; }
        public string Subtitle { get; set; }
        public string YAxisTitle { get; set; }
        public string TooltipHeaderFormat { get; set; }
        public string TooltipPointFormat { get; set; }
        public DrilldownBarSeries<T> Series { get; set; }
        public ICollection<DrilldownBarSeriesDrilldown<T>> Drilldown { get; set; }
    }
    public class DrilldownBarSeries<T>
    {
        public ICollection<DrilldownBarSeriesData<T>> data { get; set; }
    }
    public class DrilldownBarSeriesData<T>
    {
        public string name { get; set; }
        public T y { get; set; }
        public string drilldown { get; set; }
    }
    public class DrilldownBarSeriesDrilldown<T>
    {
        public string name { get; set; }
        public string id { get; set; }
        public ICollection<DrilldownBarSeriesData<T>> data { get; set; }
    }
Step 2: Create action method which returns the json result. This json used to bind basic properties and series to drilldown bar chart.
public JsonResult DrilldownBarChart()
        {
            var drilldownBarChartModel = new DrilldownBarChartModel<double>
            {
                Title = “Browser market shares. January, 2015 to May, 2015”,
                Subtitle = “Click the columns to view versions. Source: <a href=’http://netmarketshare.com’>netmarketshare.com</a>.”,
                YAxisTitle = “Total percent market share”,
                TooltipHeaderFormat = “<span style=’font-size:11px’>{series.name}</span><br>”,
                TooltipPointFormat = “<span style=’color:{point.color}’>{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>”,
                Series = new DrilldownBarSeries<double>
                {
                    data = new List<DrilldownBarSeriesData<double>>
                    {
                        new DrilldownBarSeriesData<double>{name = “Microsoft Internet Explorer”, y= 56.33,drilldown = “Microsoft Internet Explorer”},
                        new DrilldownBarSeriesData<double>{name = “Chrome”,y= 24.03,drilldown = “Chrome”},
                        new DrilldownBarSeriesData<double>{name = “Firefox”,y= 10.38,drilldown = “Firefox”},
                        new DrilldownBarSeriesData<double>{name = “Safari”,y= 4.77,drilldown = “Safari”},
                        new DrilldownBarSeriesData<double>{name = “Opera”,y= 0.91,drilldown = “Opera”},
                        new DrilldownBarSeriesData<double>{name = “Proprietary or Undetectable”,y= 0.2,drilldown = string.Empty}
                    }
                },
                Drilldown = new List<DrilldownBarSeriesDrilldown<double>>
                {
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Microsoft Internet Explorer”,
                        id= “Microsoft Internet Explorer”,
                        data= new List<DrilldownBarSeriesData<double>> {
                                               new DrilldownBarSeriesData<double>{name = “v11.0”, y=24.13},
                                               new DrilldownBarSeriesData<double>{name = “v8.0”, y=17.2},
                                               new DrilldownBarSeriesData<double>{name = “v9.0”,y= 8.11},
                                               new DrilldownBarSeriesData<double>{name = “v10.0”,y= 5.33},
                                               new DrilldownBarSeriesData<double>{name = “v6.0”, y=1.06},
                                               new DrilldownBarSeriesData<double>{name = “v7.0”,y= 0.5}
                                              }
                    },
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Chrome”,
                        id= “Chrome”,
                        data= new List<DrilldownBarSeriesData<double>> {
                                                new DrilldownBarSeriesData<double>{name = “v40.0”,y= 5},
                                                new DrilldownBarSeriesData<double>{name = “v41.0”,y= 4.32},
                                                new DrilldownBarSeriesData<double>{name = “v42.0”,y= 3.68},
                                                new DrilldownBarSeriesData<double>{name = “v39.0”,y= 2.96},
                                                new DrilldownBarSeriesData<double>{name = “v36.0”,y= 2.53},
                                                new DrilldownBarSeriesData<double>{name = “v43.0.0”, y=1.45},
                                                new DrilldownBarSeriesData<double>{name = “v31.0”, y=1.24},
                                                new DrilldownBarSeriesData<double>{name = “v35.0”,y= 0.85},
                                                new DrilldownBarSeriesData<double>{name = “v38.0”, y=0.6},
                                                new DrilldownBarSeriesData<double>{name = “v32.0”,y= 0.55},
                                                new DrilldownBarSeriesData<double>{name = “v37.0”,y= 0.38},
                                                new DrilldownBarSeriesData<double>{name = “v33.0”,y= 0.19},
                                                new DrilldownBarSeriesData<double>{name = “v34.0”,y= 0.14},
                                                new DrilldownBarSeriesData<double>{name = “v30.0”,y= 0.14}
                                           }
                    },
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Firefox”,
                        id= “Firefox”,
                        data= new List<DrilldownBarSeriesData<double>> {
                                               new DrilldownBarSeriesData<double>{name = “v35”,y= 2.76},
                                               new DrilldownBarSeriesData<double> {name = “v36”, y=2.32},
                                               new DrilldownBarSeriesData<double>{name =“v37”,y= 2.31},
                                               new DrilldownBarSeriesData<double>{name = “v34”,y= 1.27},
                                               new DrilldownBarSeriesData<double> {name = “v38”, y=1.02},
                                               new DrilldownBarSeriesData<double>{name = “v31”,y= 0.33},
                                               new DrilldownBarSeriesData<double>{name = “v33”,y= 0.22},
                                               new DrilldownBarSeriesData<double>{name = “v32”,y= 0.15}
                                           }
                    },
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Safari”,
                        id= “Safari”,
                        data= new List<DrilldownBarSeriesData<double>> {
                                              new DrilldownBarSeriesData<double> {name = “v8.0”,y= 2.56},
                                              new DrilldownBarSeriesData<double>{name = “v7.1”, y=0.77},
                                              new DrilldownBarSeriesData<double>{name =“v5.1”,y=0.42},
                                              new DrilldownBarSeriesData<double>{name = “v5.0”,y= 0.3},
                                              new DrilldownBarSeriesData<double>{name = “v6.1”,y= 0.29},
                                              new DrilldownBarSeriesData<double> {name = “v7.0”,y= 0.26},
                                              new DrilldownBarSeriesData<double>{name = “v6.2”,y= 0.17}
                                           }
                    },
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Opera”,
                        id= “Opera”,
                        data= new List<DrilldownBarSeriesData<double>> {
                                               new DrilldownBarSeriesData<double>{name = “v12.x”,y= 0.34},
                                               new DrilldownBarSeriesData<double>{name = “v28”,y= 0.24},
                                               new DrilldownBarSeriesData<double>{name = “v27”,y= 0.17},
                                               new DrilldownBarSeriesData<double>{name = “v29”,y= 0.16}
                                           }
                    },
                    new DrilldownBarSeriesDrilldown<double>
                    {
                        name = “Proprietary or Undetectable”,
                        id= “Proprietary or Undetectable”,
                        data= null
                    }
                }
            };
            return Json(drilldownBarChartModel, JsonRequestBehavior.AllowGet);
        }
Step 3: Create view container to display drilldown bar chart.
@{
    ViewBag.Title = “Home Page”;
}
@Scripts.Render(“~/bundles/demoChart”)
<table>
   
    <tr>
        <td>
            <div id=”containerDrilldownBarChart” style=”min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto; border:1px solid black;“></div>
        </td>
    </tr>
   
</table>
Step 4: Create JavaScript to bind json result to drilldown bar chart.
$(document).ready(function () {
    drawDrilldownBarChartAjax();
});
functiondrawDrilldownBarChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/DrilldownBarChart”,
        data: “{}”,
        dataType: “json”,
        success: function (jsonResult) {
            drawDrilldownBarChart(jsonResult);
        },
        error: function(jsonResult) {
            alert(“Error”);
        }
    });
}
functiondrawDrilldownBarChart(jsonResult) {
    $(‘#containerDrilldownBarChart’).highcharts({
        chart: {
            type: ‘column’
        },
        title: {
            text: jsonResult.Title
        },
        subtitle: {
            text: jsonResult.Subtitle
        },
        xAxis: {
            type: ‘category’
        },
        yAxis: {
            title: {
                text: jsonResult.YAxisTitle
            }
        },
        legend: {
            enabled: false
        },
        plotOptions: {
            series: {
                borderWidth: 0,
                dataLabels: {
                    enabled: true,
                    format: ‘{point.y:.1f}%’
                }
            }
        },
        tooltip: {
            headerFormat: jsonResult.TooltipHeaderFormat,
            pointFormat: jsonResult.TooltipPointFormat
        },
        series: [{
            name: ‘Brands’,
            colorByPoint: true,
            data: jsonResult.Series.data
        }]
        ,drilldown: {
            series: jsonResult.Drilldown
        }
    });
}
Step 5: Run the application it will display Drilldown Bar Chart as below.
 
 
Once you click on any bar it will show you further drilldown with Back button on it, shown as below
 
 

Drilldown Pie Chart

 

 

Step 1 : Create model required
                In this case I will use same models as discussed in above example i.e. Drilldown Bar Chart
Step 2: Create action method which returns the json result. This json used to bind basic properties and series to drilldown bar chart.
                Here just renaming the action method with DrilldownPieChart () and copy and pasting what code I written for DrilldownBarChart() action method.
Step 3: Create view container to display drilldown pie chart.
                Replace container name with containerDrilldownPieChart
Step 4: Create JavaScript to bind json result to drilldown pie chart. You can observe that the code for both bar and pie chart is same, only difference is “type” is “pie” J
$(document).ready(function () {
    drawDrilldownPieChartAjax();
});
functiondrawDrilldownPieChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/DrilldownPieChart”,
        data: “{}”,
        dataType: “json”,
        success: function (jsonResult) {
            drawDrilldownPieChart(jsonResult);
        },
        error: function(Result) {
            alert(“Error”);
        }
    });
}
functiondrawDrilldownPieChart(jsonResult) {
    $(‘#containerDrilldownPieChart’).highcharts({
        chart: {
            type: ‘pie’
        },
        title: {
            text: jsonResult.Title
        },
        subtitle: {
            text: jsonResult.Subtitle
        },
        plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    format: ‘{point.name}: {point.y:.1f}%’
                }
            }
        },
        tooltip: {
            headerFormat: jsonResult.TooltipHeaderFormat,
            pointFormat: jsonResult.TooltipPointFormat
        },
        series: [{
            name: ‘Brands’,
            colorByPoint: true,
            data: jsonResult.Series.data
        }],
        drilldown: {
            series: jsonResult.Drilldown
        }
    });
}
Step 5: Run the application it will display Drilldown Pie Chart as below.
 
Once you click on any bar it will show you further drilldown with Back button on it, shown as below
 
 

3-D Donut Chart

 

Step 1 : Lets modify the Chart and Series model as per the required properties to bind 2D donut chart.
    public class PlotOptions3D
    {
        public bool Enabled { get; set; }
        public int Alpha { get; set; }
        public int Beta { get; set; }
        public int InnerSize { get; set; }
        public int Depth { get; set; }
        public int ViewDistance { get; set; }
        public int MarginTop { get; set; }
        public int MarginRight { get; set; }
    }
    public class DonutPieSeriesData<T>
    {
        public string name { get; set; }
        public T y { get; set; }
    }
    public class DonutPieChartSeriesModel<T>
    {
        public string Name { get; set; }
        public ICollection<DonutPieSeriesData<T>> Data { get; set; }
    }
    public class DonutPieChartModel<T>
    {
        public string Title { get; set; }
        public string Subtitle { get; set; }
        public PlotOptions3D PlotOptions { get; set; }
        public DonutPieChartSeriesModel<T> Series { get; set; }
    }
Step 2: Create action method which returns the json result. This json used to bind basic properties and series to donut chart.
public JsonResult DonutChart3D()
        {
            var donutChart3DModel = new DonutPieChartModel<int>
            {
                Title = “Contents of Highsoft’s weekly fruit delivery”,
                Subtitle = “3D donut in Highcharts”,
                PlotOptions = new PlotOptions3D
               {
                   Alpha = 45,
                   Enabled = true,
                   InnerSize = 100,
                   Depth = 45
               },
                Series = new DonutPieChartSeriesModel<int>
                {
                    Name = “Delivered amount”,
                    Data = new List<DonutPieSeriesData<int>>
                    {
                        new DonutPieSeriesData<int>{name = “Bananas”, y= 8},
                        new DonutPieSeriesData<int>{name = “Kiwi”, y= 3},
                        new DonutPieSeriesData<int>{name = “Mixed nuts”, y= 1},
                        new DonutPieSeriesData<int>{name = “Oranges”, y= 6},
                        new DonutPieSeriesData<int>{name = “Apples”, y= 8},
                        new DonutPieSeriesData<int>{name = “Pears”, y= 4},
                        new DonutPieSeriesData<int>{name = “Clementines”, y=4 },
                        new DonutPieSeriesData<int>{name = “Reddish (bag)”, y= 1},
                        new DonutPieSeriesData<int>{name = “Grapes (bunch)”, y= 1}
                    }
                }
            };
            return Json(donutChart3DModel, JsonRequestBehavior.AllowGet);
        }
Step 3: Create view container to display donut chart.
@{
    ViewBag.Title = “Home Page”;
}
@Scripts.Render(“~/bundles/demoChart”)
<table>
    <tr>
        <td>
            <div id=”container3dDonutPieChart” style=”min-width: 600px; height: 400px; margin: 0 auto; border:1px solid black;“></div>
        </td>
    </tr>
</table>
Step 4: Create JavaScript to bind json result to drilldown bar chart.
$(document).ready(function () {
   
draw3D_DonutChartAjax();
});
functiondraw3D_DonutChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/DonutChart3D”,
        data: “{}”,
        dataType: “json”,
        success: function (jsonResult) {
            draw3D_DonutChart(jsonResult);
        },
        error: function(jsonResult) {
            alert(“Error”);
        }
    });
}
functiondraw3D_DonutChart(jsonResult) {
    $(‘#container3dDonutPieChart’).highcharts({
        chart: {
            type: ‘pie’,
            options3d: {
                enabled: jsonResult.PlotOptions.Enabled,
                alpha: jsonResult.PlotOptions.Alpha
            }
        },
        title: {
            text: jsonResult.Title
        },
        subtitle: {
            text: jsonResult.Subtitle
        },
        plotOptions: {
            pie: {
                innerSize: jsonResult.PlotOptions.InnerSize,
                depth: jsonResult.PlotOptions.Depth
            }
        },
        series: [{
            name: jsonResult.Series.Name,
            data: jsonResult.Series.Data
        }]
    });
}
Step 5: Run the application it will display 3D Donut Chart as below.
 

3-D Bar Chart

 

 

Step 1 : Lets modify the Chart and Series model as per the required properties to bind drilldown bar chart.
Step 2: Create action method which returns the json result. This json used to bind basic properties and series to 3D bar chart.
    public class DonutBarChartSeriesModel<T>
    {
        public string name { get; set; }
        public T[] data { get; set; }
        public string stack { get; set; }
    }
    public class DonutBarChartModel<T>
    {
        public string Title { get; set; }
        public PlotOptions3D PlotOptions { get; set; }
        public string[] XAxisCategories { get; set; }
        public string YAxisTitle { get; set; }
        public string TooltipHeaderFormat { get; set; }
        public string TooltipPointFormat { get; set; }
        public ICollection<DonutBarChartSeriesModel<T>> Series { get; set; }
    }
Step 3: Create view container to display 3D bar chart.
@{
    ViewBag.Title = “Home Page”;
}
@Scripts.Render(“~/bundles/demoChart”)
<table>
    <tr>
        <td>
            <div id=”container3dDonutBarChart” style=”min-width: 600px; height: 400px; margin: 0 auto; border:1px solid black;“></div>
        </td>
    </tr>
</table>
Step 4: Create JavaScript to bind json result to drilldown bar chart.
$(document).ready(function () {
   
draw3D_BarChartAjax();
});
functiondraw3D_BarChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/DonutBarChart3D”,
        data: “{}”,
        dataType: “json”,
        success: function (jsonResult) {
            draw3D_BarChart(jsonResult);
        },
        error: function(jsonResult) {
            alert(“Error”);
        }
    });
}
functiondraw3D_BarChart(jsonResult) {
    $(‘#container3dDonutBarChart’).highcharts({
        chart: {
            type: ‘column’,
            options3d: {
                enabled: jsonResult.PlotOptions.Enabled,
                alpha: jsonResult.PlotOptions.Alpha,
                beta: jsonResult.PlotOptions.Beta,
                viewDistance: jsonResult.PlotOptions.ViewDistance,
                depth: jsonResult.PlotOptions.Depth
            },
            marginTop: jsonResult.PlotOptions.MarginTop,
            marginRight: jsonResult.PlotOptions.MarginRight
        },
        title: {
            text: jsonResult.Title
        },
        xAxis: {
            categories: jsonResult.XAxisCategories
        },
        yAxis: {
            allowDecimals: false,
            min: 0,
            title: {
                text: jsonResult.YAxisTitle
            }
        },
        tooltip: {
            headerFormat: jsonResult.TooltipHeaderFormat,
            pointFormat: jsonResult.TooltipPointFormat
        },
        plotOptions: {
            column: {
                stacking: ‘normal’,
                depth: jsonResult.PlotOptions.Depth
            }
        },
        series: jsonResult.Series
    });
}
Step 5: Run the application it will display 2D Bar Chart as below.

 

Conclusion: 

In this article we learned how Highcharts are useful to display data in drilldown and 3D charts. We learned to create model objects depending upon the chart selected. I would recommend you to use these models and modify the code as your wish to achieve desired output. You can use same functionality not only using MVC but ASP.NET, and Java also.

 

Display data in chart using JavaScript Highcharts

1.    Introduction

Chart is also called as graph and it is graphical representation of data. The data is represented in the form of bar in bar chart, line in line chart and slices using pie chart. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. If you want to develop dashboard then charting is absolutely necessary for your users especially for management.
In my previous post Display data in chart using ASP.NET MVC we discussed how MVC Chart helper used to display the charts in web application. The advantage of using ASP.NET MVC Chart helper is it’s free and very easy to implement it; however if your web sites primary purpose is charts or dashboard and if you want more advanced options like drilldown, tooltip, zooming options, better look and feel and clean plot area, animations then MVC Chart helper would not the option for you. In such situation you need to find another option. After searching on web, I came across third party vendors like Kendo Charts and Highcharts but I falls in love with Highcharts. Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange, bubble, box plot, error bars, funnel, waterfall and polar chart types. The Highchart is free for non-commercial and non-profit organization/entity. Please refer their licensing and terms of condition before using it.  The Highcharts have good API(Application Programming Interface) provide on their site with sample code to achieve your expected functionality.
Today, I’m going to explain how to use charts using JavaScript and Highcharts. In this post I will explain basic and more frequently used charting options like Bar, Pie chart, Donut chart.

2.    Overview

To get to grasp with how Highcharts works it is important to understand the various parts or concepts of a chart. Below is an image and a description of the main concepts in a chart.
 
Chart Elements
Description
Title
Is the text that will be presented at the top of a chart.
Series
Is one or more series of data presented on a chart.
Tooltip
When hovering over a series or a point on the chart you can get a tooltip that describes the values on that particular part of the chart.
Legend
The legend show the data series in the graph and allows for enabling and disabling one or more series.
Axes
The x and y-axis of the chart, can also use multiple axes for different data series. Most chart types, like the typical Cartesian types line and column, have axes. Polar charts have an X axis that spans around the perimeter of the chart, and even gauges have a single value axis. Pie charts don’t have axes.

3.    Practical Implementation

There are many ways to achieve chart functionality in Highcharts. You can create chart using array manipulation, static array binding or converting xml data in compatible with Highcharts required data. In this post I’m showing how to bind data to Highcharts in ASP.NET MVC using Ajax Request and JavaScript functions.
To achieve this functionality in MVC you need to create Model(or View Model), Controller Action which returns json result and Razor view to display it on client side.
There are multiple JavaScript libraries are required so listing them serially. These JavaScript library are available to download on Highcharts Website Documentation
highcharts.js
data.js
exporting.js
To show drilldown functionality in your chart use below JavaScript file
drilldown.js
To show 3D charts use below JavaScript file.
highcharts-3d.js

Bar Charts:

Let’s create a sample application for displaying bar chart
Step 1: Create JavaScript Bundle an refer to your razor page.
Download above mentioned file to your solutions Scripts folder and create bundle to render it on your mvc razor page.
 
 
bundles.Add(new ScriptBundle(“~/bundles/highcharts”).Include(
                        “~/Scripts/highcharts/highcharts.js”
                       , “~/Scripts/highcharts/data.js”
                       , “~/Scripts/highcharts/exporting.js”
                       , “~/Scripts/highcharts/drilldown.js”
                       , “~/Scripts/highcharts/highcharts-3d.js”));
I have created my separate script library DemoChart.js to render charts.
bundles.Add(new ScriptBundle(“~/bundles/demoChart”).Include(
                        “~/Scripts/DemoChart.js”));
Use below code to render Highcharts and jQuery JavaScript library to your razor page.
@Scripts.Render(“~/bundles/jquery”)
@Scripts.Render(“~/bundles/highcharts”)
@Scripts.Render(“~/bundles/demoChart”)
Step 2: Model Creation
To show charts basic properties(Title, Subtitle, X and Y axis title etc.) and series elements we need to create two different models with any kind of data it support in their array either integer or string array.
SeriesModel is responsible for binding series elements like name and data, hence I renamed them in small letters to avoid unnecessary json to JavaScript conversion.
public class SeriesModel<T>
{
     public string name { get; set; }
     public ICollection<T> data { get; set; }
}
ChartModel is responsible for binding chart basic properties.
public class ChartModel<T>
{
     public string Title { get; set; }
     public string Subtitle { get; set; }
     public string[] XAxisCategories { get; set; }
     public string XAxisTitle { get; set; }
     public string YAxisTitle { get; set; }
     public string YAxisTooltipValueSuffix { get; set; }
     public ICollection<SeriesModel<T>> Series { get; set; }
 }
Step 3: Create Controller and Actions Required
In ChartController.cs file add Index() action method to view your charting page and BarChart() action method to return Json Result. This Json result will be used to manipulate and convert to JavaScript array.
In this example I referred the data to render from Highcharts website, just modified it to get result from action method(This is what they not documented on their site for MVC developers J).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Highchart.WebUI.Models;
namespace Highchart.WebUI.Controllers
{
    public class ChartController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult BarChart()
        {
            var barChartModel = new ChartModel<int>
            {
                Title = “Historic World Population by Region”,
                Subtitle = “Source: <a href=’https://en.wikipedia.org/wiki/World_population’>Wikipedia.org</a>”,
                XAxisCategories = new string[] { “Africa”, “America”, “Asia”, “Europe”, “Oceania” },
                XAxisTitle = “”,
                YAxisTitle = “Population (millions)”,
                YAxisTooltipValueSuffix = ” millions”,
                Series = new List<SeriesModel<int>> {
                    new SeriesModel<int>{ name = “Year 1800”, data = new int[]{ 107, 31, 635, 203, 2 }},
                    new SeriesModel<int>{ name = “Year 1900”, data = new int[]{ 133, 156, 947, 408, 6 }},
                    new SeriesModel<int>{ name = “Year 2012”, data = new int[]{ 1052, 954, 4250, 740, 38 }}
                }
            };
            return Json(barChartModel, JsonRequestBehavior.AllowGet);
        }
    }
}
Step 4: Create razor view
Add below source code into your Index.cshtml page to render the bar chart
@{
    ViewBag.Title = “Home Page”;
}
@Scripts.Render(“~/bundles/demoChart”)
<table>
    <tr>
        <td>
            <div id=”containerBarChart” style=”min-width: 800px; max-width: 900px; height: 400px; margin: 0 auto; border:1px solid black;“></div>
        </td>
    </tr>
</table>
Step 5: Create JavaScript file for showing chart using JavaScript and Highcharts
$(document).ready(function () {
    drawBarChartAjax();
});
function drawBarChartAjax() {
    $.ajax({
        type: “POST”,
        contentType: “application/json; charset=utf-8”,
        url: “Chart/BarChart”,
        data: “{}”,
        dataType: “json”,
        cache:true,
        success: function (Result) {
            drawBarChart(Result);
        },
        error: function (Result) {
            alert(“Error”);
        }
    });
}
function drawBarChart(data)
{
    $(‘#containerBarChart’).highcharts({
        chart: {
            type: ‘bar’
        },
        title: {
            text: data.Title
        },
        subtitle: {
            text: data.Subtitle
        },
        xAxis: {
            categories: data.XAxisCategories,
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: data.YAxisTitle,
                align: ‘high’
            },
            labels: {
                overflow: ‘justify’
            }
        },
        tooltip: {
            valueSuffix: data.YAxisTooltipValueSuffix
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        legend: {
            layout: ‘vertical’,
            align: ‘right’,
            verticalAlign: ‘top’,
            x: -40,
            y: 80,
            floating: true,
            borderWidth: 1,
            backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || ‘#FFFFFF’),
            shadow: true
        },
        credits: {
            enabled: false
        },
        series: data.Series
    });
    }
Step 6: Final output
Run the application and see the chart rendered.
 
 

4.    Other Chart Available

4.1   ASP.NET MVC Chart Helper
4.2   Chart.js
4.3   Kendo Charts
4.4   Component Art
4.5   Infragistic Chart

5.    Summary

Using Highcharts, it is very easy to bind dynamic json result to your chart container using ASP.NET MVC. In this article, I showed  you how to create a chart in ASP.NET MVC using Highcharts. I also showed you how to bind dynamic json result using jQuery.ajax method. Hopefully you would enjoy this article too.  In my next blog post article I will explain how Chart.js JavaScript library are useful to display charts in advanced fashion.

Display data in chart using ASP.NET MVC

1.    Introduction

Chart is also called as graph and it is graphical representation of data. The data is represented in the form of bar in bar chart, line in line chart and slices using pie chart. Chart can usually be read more quickly than the row data. Chart is the greatest and simplest way to express data to user or management persons. Charts are very common in all type of business requirement. If you want to develop dashboard then charting is absolutely necessary for your users especially for management.
Today, I came across the situation in my current ongoing assignment where graphical dashboard is required. So I did Google for it and come across different approaches to implement it. Last two three days I explored different approaches by making smaller proof of concepts. In today’s post I am going to explain how we can create the chart using Chart Helper provided my Microsoft ASP.NET MVC.

2.    Overview

In my careers starting days with ASP.NET, I remember we used different type of third party control to implement chart functionality in applications. But now using Microsoft ASP.NET MVC provides inbuilt support for Chart in a very simpler fashion. The “System.Web.Helpers” namespace used to implement the chart functionality.
2.1   Chart Helper:
Using chart helper you can create chart images of different types with many formatting options and labels. It can be used to create area chart, bar chart, column chart, line chart and pie charts along with more specialized types of charts like stock charts. The chart helper can render more than 30 types of chats. The data you display in chart can be in the form of array, for database or using data in the file.
2.2   Chart Elements:
The chart shows the actual data and additional elements like axis, legends, series, axis title, chat title and plotting area. The following picture shows the chart elements that you  can customize as per your need using chart helper.
 

2.3   Chart types:

The chart control defines different type of charts. Each chart defines unique set of requirements based on features. ASP.NET MVC Chart Helper provides below type of charts. SeriesChartType enumeration defines below charts.
Chart Type
Description
Bar Chart
Illustrates comparisons among individual items.
Column Chart
Uses a sequence of columns to compare values across categories.
Doughnut Chart
Similar to the Pie chart type, except that it has a hole in the center.
Line Chart
Illustrates trends in data with the passing of time.
Pie Chart
Shows how proportions of data, shown as pie-shaped pieces, contribute to the data as a whole.
I haven’t tried all of them but only required to my project assignment, hence given description to used specific only. You can find complete set of types by clicking here
2.4   Styling:
The chart helper support number of option to customize it’s look and feel. You can set color, fonts, border etc. The “theme” is used to customize the charts look and feel. The themes are collection of information the specifies the rendering option using fonts, color, label, palettes, and effects. The following table shows in build option supported in chart helper.
Theme Name
Description
Vanilla
Displays red columns on a white background.
Blue
Displays blue columns on a blue gradient background.
Green
Displays blue columns on a green gradient background.
Yellow
Displays orange columns on a yellow gradient background.
Vanilla3D
Displays 3-D red columns on a white background.
2.5   Methods or Functions:
Below are the functions and properties used to set while using chart helper.
Function
Description
new Chart()
It creates a new chart object and sets its width and height
AddTitle()
This method adds the tile to the chart
AddLegend()
Adds the legend to the chart
Addseries()
It is used for providing data points and series of attributes for the chart.
SetXAxis()
It sets the value for the horizontal axis (X-Axis).
SetYAxis()
It sets the value for the vertical  axis (Y-Axis).
Save()
By using this method we can save the chart image to the specified file.
SaveToCache()
It saves the chart image in the system cache.
Write()
The method displays the chart.
DataBindTable()
This method binds the data source to the chart
chartType
This parameter defines the type of chart
xValue
This parameter defines x-axis names
yValues
This parameter defines the y-axis values
2.6   Saving:
The charts recreates the chart from scratch every time you loads the page. If you do the complex operation using database or LINQ query like grouping  then it may hamper performance of your website page. So to avoid or reduce this you can create chart at first time and save it and whenever required fetch the saved version and render it. Below are the options you can save the chart.
1. Cache the chart on server memory
2. Save chart as image on server
3. Save chat as xml file
2.7   Caching
Once you create chart you can save it. So no need of recreate it. You can clear cache on demand also or it automatically clear whenever your application restarts.

3.    Practical Implementation

There are multiple ways to achieve charting functionality. You can create chart using arrays, database query or using xml data. Below example explains how to create chart using arrays.
Step 1:
Create a MVC razor page(Index.cshtml) and add below code in it. This action will display the Bar chart.
<table>
    <tr>
        <th colspan=”2″ style=”height:100px; text-align:center”><b>GDP Dashboard of top Countries</b></th>
    </tr>
    <tr>
        <td rowspan=”2″>
            <img src=”@Url.Action(“CreateCountryGDPBar”) />
        </td>
    </tr>
</table>
Step 2:
Create Controller with default Index action and give implementation of CreateCountryGDPBar acton as below code sample. TO run this example you need to import System.Web.Helpers namespace In your controller.
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult CreateCountryGDPBar()
        {
            var chart = new System.Web.Helpers.Chart(width: 300, height: 200, theme: ChartTheme.Blue)
             .AddTitle(“GDP Current Prices in Billion($)”)
            .AddSeries(
                    chartType: “column”,
                    name: “StudyType”,
                    xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “UK”, “France”, “India” },
                        yValues: new[] { “17968”, “11385”, “4116”, “3371”, “2865”, “2423”, “2183” })
             .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
Step 3:
This will display the bar chart
 
This code is very self-explanatory. You just need to set height, width and default skin in Chart constructor. Give the title to display on top of chart. xValues and yValues are the properties to display actual data, chartType is used to display the type of data  and  use GetByte method to return image in png format. Return the file as return data of action and in output you will see the chart as above.
Below sample describes the how to display another bar and pie charts using different themes.
Place below code into your view and controller.
        <td>
            <img src=”@Url.Action(“ComparisonBar”)“/>
        </td>
        public ActionResult ComparisonBar()
        {
            var chart = new System.Web.Helpers.Chart(width: 500, height: 300)
            .AddTitle(“GDP Ranking (USDA) in Billions($)”)
            .AddSeries(
                chartType: “column”,
                xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “France”, “UK”, “India” },
                yValues: new[] { 16656, 8774, 5704, 3668, 2762, 2637, 2366 },
                name: “2015”)
            .AddSeries(
                chartType: “column”,
                xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “France”, “UK”, “India” },
                yValues: new[] { 23857, 18829, 6535, 4308, 3476, 3815, 7269 },
                name: “2030”)
            .AddLegend()
            .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
This will display below bar chart result.
        <td>
            <img src=”@Url.Action(“CreateCountryGDPPie”)“/>
        </td>
        public ActionResult CreateCountryGDPPie()
        {
            var chart = new System.Web.Helpers.Chart(width: 300, height: 200, theme: ChartTheme.Vanilla)
            .AddTitle(“GDP Current Prices in Billion($)”)
            .AddLegend()
            .AddSeries(chartType: “pie”,
                        xValue: new[] { “USA”, “China”, “Japan”, “Germany”, “UK”, “France”, “India”},
                        yValues: new[] { “17968”, “11385”, “4116”, “3371”, “2865”, “2423”, “2183” })
            .GetBytes(“png”);
            return File(chart, “image/bytes”);
        }
This will display below pie chart result.
 
 
Suppose you want to customize your chat the you need to add customize code for that. Below example shows hot to customize bar chart using C# code. To customize cod you need to import using System.Web.UI.DataVisualization.Charting namespace in your application.Add below code sample in your view and controller
        <td rowspan=”2″>
            <img src=”@Url.Action(“CreateGDPRankingBar”) />
        </td>
  public class StatusNumber
  {
        public string Status { get; set; }
        public string Number { get; set; }
  }
        public ActionResult CreateGDPRankingBar()
        {
            var statusNumbers = new List<StatusNumber>
            {
                new StatusNumber{Number=“17968”, Status=“USA”},
                new StatusNumber{Number=“11385”, Status=“China”},
                new StatusNumber{Number=“4116”, Status=“Japan”},
                new StatusNumber{Number=“3371”, Status=“Germany”},
                new StatusNumber{Number=“2865”, Status=“UK”},
                new StatusNumber{Number=“2423”, Status=“France”},
                new StatusNumber{Number=“2183”, Status=“India”},
            };
            var chart = new System.Web.UI.DataVisualization.Charting.Chart();
            chart.Width = 350;
            chart.Height = 400;
            chart.BackColor = Color.FromArgb(211, 223, 240);
            chart.BorderlineDashStyle = ChartDashStyle.Solid;
            chart.BackSecondaryColor = Color.White;
            chart.BackGradientStyle = GradientStyle.TopBottom;
            chart.BorderlineWidth = 1;
            chart.Palette = ChartColorPalette.BrightPastel;
            chart.BorderlineColor = Color.FromArgb(26, 59, 105);
            chart.RenderType = RenderType.BinaryStreaming;
            chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
            chart.AntiAliasing = AntiAliasingStyles.All;
            chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
            chart.Titles.Add(CreateTitle());
            chart.Legends.Add(CreateLegend());
            chart.Series.Add(CreateSeries(SeriesChartType.Bar, statusNumbers));
            chart.ChartAreas.Add(CreateChartArea());
            MemoryStream ms = new MemoryStream();
            chart.SaveImage(ms);
            return File(ms.GetBuffer(), @”image/png”);
        }
       
        public Title CreateTitle()
        {
            Title title = new Title
            {
                Text = “GDP Current Prices in Billion($)”,
                ShadowColor = Color.FromArgb(32, 0, 0, 0),
                Font = new Font(“Trebuchet MS”, 14F, FontStyle.Bold),
                ShadowOffset = 3,
                ForeColor = Color.FromArgb(26, 59, 105)
            };
            return title;
        }
        public Series CreateSeries(SeriesChartType chartType, ICollection<StatusNumber> list)
        {
            var series = new Series
            {
                Name = “GDP Current Prices in Billion($)”,
                IsValueShownAsLabel = true,
                Color = Color.FromArgb(198, 99, 99),
                ChartType = chartType,
                BorderWidth = 2
            };
            foreach (var item in list)
            {
                var point = new DataPoint
                {
                    AxisLabel = item.Status,
                    YValues = new double[] { double.Parse(item.Number) }
                };
                series.Points.Add(point);
            }
            return series;
        }
        public ChartArea CreateChartArea()
        {
            var chartArea = new ChartArea();
            chartArea.Name = “GDP Current Prices in Billion($)”;
            chartArea.BackColor = Color.Transparent;
            chartArea.AxisX.IsLabelAutoFit = false;
            chartArea.AxisY.IsLabelAutoFit = false;
            chartArea.AxisX.LabelStyle.Font = new Font(“Verdana,Arial,Helvetica,sans-serif”, 8F, FontStyle.Regular);
            chartArea.AxisY.LabelStyle.Font = new Font(“Verdana,Arial,Helvetica,sans-serif”, 8F, FontStyle.Regular);
            chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.Interval = 1;
            return chartArea;
        }
        public Legend CreateLegend()
        {
            var legend = new Legend
            {
                Name = “GDP Current Prices in Billion($)”,
                Docking = Docking.Bottom,
                Alignment = StringAlignment.Center,
                BackColor = Color.Transparent,
                Font = new Font(new FontFamily(“Trebuchet MS”), 9),
                LegendStyle = LegendStyle.Row
            };
            return legend;
        }
This will display bar chart as below
If you integrate all above action methods and view code it will display chart as below.

I hope you enjoyed the sample code that I provided. I would suggest you to play something around the code and theme.

4.    Other Chart Available

4.1   High Chart
4.2   Chart.js
4.3   Kendo Charts
4.4   Component Art
4.5   Infragistic Chart

5.    Summary

Using MVC Chart helper, it is very easy to show chart in your ASP.NET MVC application. In this article, I showed  you how to create a chart in ASP.NET MVC. I also showed you how to style a chart and how to change the background color of a chart. Hopefully you will enjoy this article too.  In my next blog post article I will explain how Chart.js and Highcharts JavaScript library are useful to display charts in advanced fashion.

How to Send Email using C#

Introduction

In this post, we will create a simple mail helper class for sending emails using C#. Now a day’s email functionality is widely used in software application. The email notification is required to notify the end user. Microsoft .NET provides inbuilt classes for sending emails under System.Net and System.Net.Mail namespaces.

Description

                To send email you need the host, port and one email address of that host. Without this you cannot send emails. It’s not necessary to buy host, even you can use your private email address on Gmail, Yahoo for those want to learn as personal or academics purpose only. Obviously for commercial and non commercial, I will not recommend to use personal Gmail or Yahoo account Smile.
       The EmailAccount class is used to specify required properties to send email. This class will acts as the default settings for sending email.
    /// <summary>
    /// Class is used to set basic properties required for sending email.
    /// </summary>
    public class EmailAccount
    {
        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        /// <value>
        /// The email.
        /// </value>
        public string Email { get; set; }
        /// <summary>
        /// Gets or sets the display name.
        /// </summary>
        /// <value>
        /// The display name.
        /// </value>
        public string DisplayName { get; set; }
        /// <summary>
        /// Gets or sets the host.
        /// </summary>
        /// <value>
        /// The host.
        /// </value>
        public string Host { get; set; }
        /// <summary>
        /// Gets or sets an email port
        /// </summary>
        /// <value>
        /// The port.
        /// </value>
        public int Port { get; set; }
        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        /// <value>
        /// The username.
        /// </value>
        public string Username { get; set; }
        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>
        /// The password.
        /// </value>
        public string Password { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether Secure Sockets Layer (SSL) to encrypt the connection.
        /// </summary>
        /// <value>
        ///   <c>true</c> if [enable SSL]; otherwise, <c>false</c>.
        /// </value>
        public bool EnableSsl { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether [use default credentials].
        /// </summary>
        /// <value>
        /// <c>true</c> if [use default credentials]; otherwise, <c>false</c>.
        /// </value>
        public bool UseDefaultCredentials { get; set; }
}
Use the following app settings in our config file under configuration section of your application. Here you need to change values as per your need. I have given the sample settings.
  <system.net>
    <!– Mail settings –>
    <mailSettings>
      <smtp deliveryMethod=Network from=abc@xxx.com>
        <network defaultCredentials=true host=webmail.xxx.com port=“587” />
      </smtp>
    </mailSettings>
  </system.net>
To send email you should be aware of below classes and its usage.
  • EmailAddress: Represents the address of an electronic mail sender or recipient.
  • EmailMessage: Represents an e-mail message that can be sent using the System.Net.Mail.SmtpClient. This class contains information of actual message i.e. To, From, Cc, Bcc, Attachments, Body and Subject.
  • SmtpClient: Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). This class contains information regarding SMTP Server like Credentials, Host, Port, EnablingSSL, Certificate and  delivery formats.
  • NetworkCredential: Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
Create _DefaultAccount   static readonly property which can be set from static constructor only. In this way you can hide the internal implementation.
private static readonly EmailAccount _DefaultAccount;
Set _DefaultAccount property in static constructor. You can also configure these values in app settings of config file.
static EmailHelper()
{
      _DefaultAccount = new EmailAccount
      {
           DisplayName = “abc”,
           Email = “abc@xxx.com”,
           EnableSsl = true,
           UseDefaultCredentials = false,
           Password = “password”,
           Username = “abc@xxx.com”,
           Host = “smtp.xxx.com”,
           Port = 587
       };
 }
Create a public static function SendEmail which accepts required parameters. You can also make different type of overloaded functions as per your requirements.
public static void SendEmail(string subject, string body, IEnumerable<string> toAddress, string replyTo, IEnumerable<string> cc = null, IEnumerable<string> bcc = null)
{
       // Logic to call private method.
}
Create private static function for sending email with additional EmailAccount as parameter. This is how we hided our internal implementation.
private static void Send(EmailAccount emailAccount, string subject, string body, MailAddress from, MailAddress replyTo, IEnumerable<string> to = null, IEnumerable<string> cc = null, IEnumerable<string> bcc = null)
{
       // Logic to send email.
}
Below is the complete implementation of EmailHelper utility class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
namespace EmailHelper
{
    /// <summary>
    /// Utility to send emails.
    /// </summary>
    public static class EmailHelper
    {
        #region Members
        private static readonly EmailAccount _DefaultAccount;
        #endregion
        #region  Constructor
        /// <summary>
        /// Initializes the <see cref=”EmailHelper”/> class.
        /// </summary>
        static EmailHelper()
        {
            _DefaultAccount = new EmailAccount
            {
                DisplayName = “abc”,
                Email = “abc@xxx.com”,
                EnableSsl = true,
                UseDefaultCredentials = false,
                Password = “password”,
                Username = “abc@xxx.com”,
                Host = “smtp.xxx.com”,
                Port = 587
            };
        }
        #endregion
        #region Public Methods
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name=”subject”>The subject.</param>
        /// <param name=”body”>The body.</param>
        /// <param name=”toAddress”>To address.</param>
        /// <param name=”replyTo”>The reply to.</param>
        /// <param name=”cc”>The cc.</param>
        /// <param name=”bcc”>The BCC.</param>
        public static void SendEmail(string subject, string body, IEnumerable<string> toAddress, string replyTo, IEnumerable<string> cc = null, IEnumerable<string> bcc = null)
        {
            try
            {
                Send(_DefaultAccount, subject, body, new MailAddress(_DefaultAccount.Email, _DefaultAccount.DisplayName), new MailAddress(replyTo), toAddress, cc, bcc);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
        #region Private Methods
        /// <summary>
        /// Sends the specified email account.
        /// </summary>
        /// <param name=”emailAccount”>The email account.</param>
        /// <param name=”subject”>The subject.</param>
        /// <param name=”body”>The body.</param>
        /// <param name=”from”>From.</param>
        /// <param name=”replyTo”>The reply to.</param>
        /// <param name=”to”>To.</param>
        /// <param name=”cc”>The cc.</param>
        /// <param name=”bcc”>The BCC.</param>
        private static void Send(EmailAccount emailAccount, string subject, string body, MailAddress from, MailAddress replyTo, IEnumerable<string> to = null, IEnumerable<string> cc = null, IEnumerable<string> bcc = null)
        {
            var message = new MailMessage();
            message.From = from;
            if (!string.IsNullOrEmpty(replyTo.Address))
                message.ReplyToList.Add(new MailAddress(replyTo.Address));
            if (null != to)
            {
                foreach (var address in to.Where(toValue => !String.IsNullOrWhiteSpace(toValue)))
                {
                    message.To.Add(address.Trim());
                }
            }
            if (null != cc)
            {
                foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }
            if (null != bcc)
            {
                foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                else
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);
                try
                {
                    smtpClient.Send(message);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
        #endregion
    }
}
You can test this be creating small console based application. The console based client code given below.
Private static void Main(string[] args)
{
            var subject = “This is test subject”;
            var body = “Body of email”;
            var toList = new List<string> { “abc@xxx.com”, “pqr@xxx.com”, “xyz@xxx.com” };
            try
            {
                EmailHelper.SendEmail(subject, body, toList, “abc@xxx.com”, null, null);
                Console.WriteLine(“Email sent successfully.”);
            }
            catch (Exception ex)
            {
                Console.WriteLine(“Error occurred while sending email: “ + ex.Message);
            }
            Console.ReadKey();
 }

Conclusion

In this way by using EmailAddress, EmailMessage, SmtpClient, NetworkCredential clsses of System.Net and System.Net.Mail namespaces we can send email.

C# Coding standards and Best Practices

In this post i am describing the rule and recommendations for developing software application and class libraries in .NET using C# as a language. The main purpose is to define the general guidelines to enforce consistent coding styles and formatting that can be useful for developers to avoid common mistakes they do while development of software applications using C#. This post covers naming conventions, coding styles and some architecture level suggestions. To understand better I have colored C# keywords in BLUE.
The information provided in this document is compiled from the coding standard and best practices published in various blogs, articles and my previous 8+ Years extensive experience in .NET technology. I have also referred to the C# Coding Conventions provided by Microsoft.

Purpose of coding standard and best practices to do it

Coding standards are a set of guidelines used for programming language that recommends programming style and best practices to achieve it. The coding standards generally covers indentation, comments, naming conventions, programming practices, file structure within project, architectural best practices etc. Software developers are highly recommended to follow these guidelines. The coding guidelines have following advantages.
1.       Increases the readability of source code written.
2.       Will contain less bugs and works more efficiently.
3.       Requires less maintenance.
4.       Easier for old and new developers to maintain and modify the code.
5.       Leads to increase in productivity of developers.
6.       Reduces the overall cost for software development.
7.       Make the difference between a successful project and a project that is, at worst, dead on delivery.

How to follow coding standards in your teams

1.       Make your own coding standard document as per industry standards by sitting together in a team and share across the team.
2.       Look at the existing code and decide what you want in yours.
3.       Assign someone to do the frequent code review and peers reviews.
4.       Involve seniors and get some inspiration from their previous experience.
5.       Whenever new fresh guy arrives, introduce projects or products codebase to him or her. Educate that guy to follow coding standards.

Naming Conventions

       There are three type of naming conventions generally used while doing C# programming
        1.       Pascal Convention – First character of all word are in upper case and other characters are in lower case.
Example: HelloWorld
2.       Camel Case Convention – The first character of all words, except the first word, is upper case and other characters are lower case.
Example: helloWorld
3.  Hungarian Case Convention – The data type as prefix is used to define the variable by developers long ago. This convention is not used anywhere now a day’s except local variable declaration.
Example:
string m_sName;
string strName;
int iAge;
Let’s generalize the module with correct and incorrect naming conventions.
Sr. No
Module
Description
Correct
Wrong
1.
Class
Use Pascal conventions for defining class name
public class HelloWorld
{
}
public class helloWorld
{
}
2.
Method
Use Pascal conventions for defining class name
public void AddNumbers(int first, int second)
{
}
public void addNumbers(int first, int second)
{
}
3.
Interface
Use Prefix “I” with Camel Casing to define interface
public interface IEmployee
{
}
public interface Iemployee
{
}
4.
Local Variables
Use Hungarian Meaningful, descriptive words to name variables. Do not use abbreviations
string firstName
int salary
string fName