Feb 14

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.

Feb 10

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.

Nov 15

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.

Nov 15

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
string name
string _firstName
int sal
5.
Member Variables
Member variables must be prefix with underscore(_) so that they can be identified by other local variables and constants
private IEmployee _employeeService = null
private UserRole userRole
private UserGroup userGroup
private IEmployee empService = null
private UserRole usrRole
private UserGroup usrGrp
6.
Boolean variables
Prefix Boolean variables with “is” or some smaller prefixes
private bool _isDirty
private bool _isFinished
private bool dirty
private bool finished
private bool isFinished
7.
Namespace
The namespace should be logical grouping of classes with specific pattern
<CompanyName>
.<ProductName>
.<ModuleName>
Example:
ABC.SchoolManagement.BusinessLayer
ABC.SchoolManagement.DataAccessLayer
ABC.SchoolManagement.WebUI
Example:
BusinessLayer
DataAccessLayer
WebUI
8.
File Name
Filename should match with class name i.e. Pascal name
public class HelloWorld
{
}
The Filename must be: HelloWorld.cs
public class HelloWorld
{
}
Filename: helloworld.cs

 

Control Prefix Naming Conventions

The best practice generally used while developing web and window application uses prefixes for UI elements. Since ASP.NET and Windows Form have too many controls available to use, hence summarizing them through tabular chart.
Sr.No
Control
Prefix
1
Label
lbl
2
TextBox
txt
3
DataGrid
grd
4
Button
btn
5
ImageButton
imb
6
Hyperlink
hyp
7
DropDownList
ddl
8
ListBox
lst
9
DataList
dtl
10
Repeater
rep
11
Checkbox
chk
12
CheckBoxList
cbl
13
RadioButton
rdo
14
RadioButtonList
rbl
15
Image
img
16
Panel
pnl
17
PlaceHolder
phd
18
Table
tbl
19
Validators
val

Code Indentation and Comments

Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. To achieve this below points would be helpful,
1.       Use default code editor setting provided by Microsoft Visual Studio.
2.       Write only one statement and declaration per line.
3.       Add one blank line space between each method.
4.       Use parentheses to understand the code written.
5.       Use xml commenting to describe functions, class and constructor.
6.       Use Tab for indentation.
7.       Use one blank line to separate logical groups of code.
8.       Use #region and #endregion to group related piece of code as per below
a.     Private Member
b.    Private Properties
c.     Public Properties
d.    Constructors
e.     Event Handlers/Action Methods
f.     Private Methods
g.    Public Methods
9.       Do not write comments for every line of code and every variable declared.
10.   Use // or /// for comments avoid using /* … */
11.   If you have to use some complex for any reason, document it very well with sufficient comments.
12.   If all variables and method names are meaningful, that would make the code very readable and will not need many comments.

Good Programming Practices

1.     Avoid writing of long functions. The typical function should have max 40-50 lines of code. If method has more than 50 line of code, you must consider re factoring into separate private methods.
2.     Avoid writing of long class files. The typical class file should contain 600-700 lines of code. If the class file has more than 700 line of code, you must create partial class. The partial class combines code into single unit after compilation.
3.       Don’t have number of classes in single file. Create separate file for each class.
4.       Avoid the use of var in place of dynamic.
5.       Add a whitespace around operators, like +, -, ==, etc.
6.        Always succeed the keywords if, else, do, while, for and foreach, with opening and closing parentheses, even though the language does not require it.
7.       The method name should have meaningful name so that it cannot mislead names. The meaningful method name doesn’t need code comments.
Good:
private void SaveAddress(Address address)
{
}
Bad:
// This method used to save address
private void Save (Address addr)
{
}
8.     The method or function should have only single responsibility (one job). Don’t try to combine multiple functionality into single function.
Good:
public void UpdateAddress(Address address)
{
}
public void InsertAddress(Address address)
{
}
Bad:
public void SaveAddress(Address address)
{
              if(address.AddressId == 0)
              {
                  // Insert address code
              }
              else
              {
                  // Update address code
              }     
}
9.     Avoid using common type system. Use the language specific aliases
Good:
int age;
string firstName;
object addressInfo;
Bad:
       System.Int32 age;
       String firstName;
    Object addressInfo;
10.   Do not hardcode string or numbers instead of it create separate file for constants and put all constants into that or declare constants on top of file and refer these constants into your code.
11.   You can also put some constants like database connection, logger file name, SMTP information variables etc. in form of key and value pair in config file.
12.   Don’t hardcode strings. Use resource files.
13.   While comparing string, convert string variables into Upper or Lowers case
Good:
if (firstName.ToLower() == “rohit”)
   {
   }
if (firstName.ToUpper() == “ROHIT”)
   {
   }
Bad:
if (firstName == “rohit”)
   {
   }
14.  Use String.Empty instead of “”
Good:
if (firstName == String.Empty)
       {
       }
Bad:
if (firstName == “”)
       {
    }
15.  Avoid using member variables. Declare local variable in function or method itself and pass it to other method whenever required instead of sharing the member variable between two methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.
16.  Don’t make member variables to public or protected. Keep them as private and expose them as public or protected properties
17.   Use enums wherever require. Don’t use numbers or strings to indicate discrete values.
Good:
   public enum LoggerType
       {
              Event,
              File,
              Database
    }
                 public void LogException(string message, LoggerType loggerType)
       {
            switch (loggerType)
            {
                case LoggerType.Event:
                    // Do something
                    break;
                case LoggerType.File:
                    // Do something
                    break;
                case LoggerType.Database:
                    // Do something
                    break;
                default:
                    // Do something
                    break;
            }
     }
Bad:
       public void LogException(string message, LoggerType loggerType)
        {
            switch (loggerType)
            {
                case “Event”:
                    // Do something
                    break;
                case “File”:
                    // Do something
                    break;
                case “Database”:
                    // Do something
                    break;
                default:
                    // Do something
                    break;
            }
        }
18.  The event handler should not contain the code to perform the required action. Instead of call another private or public method from the event handler. Keep event handler or action method clean as possible.
19.  Never hardcode a path or drive name in code. Get the application path programmatically and use relative path. Use input or output classes (System.IO) to achieve this.
20.  Always do null check for objects and complex objects before accessing them.
Good:
 public Contact GetContactDetails(Address address)
        {
            if (address != null && address.Contact != null)
            {
                return address.Contact;
            }
     }
Bad:
 public Contact GetContactDetails(Address address)
        {
            return address.Contact;
     }
21.  Error message to end use should be user friendly and self explanatory but log the actual exception details using logger. Create constants for this and use them in application.
Good:
Error occurred while connecting to database. Please contact administrator.”
Your session has been expired. Please login again.”
Bad:
Error in Application.”
There is an error in application.”
22.   Avoid public methods and properties to expose, unless they really need to be accessed from outside the class. Use “internal” if they are accessed only within the same assembly and use “private” if used in same class.
23.   Avoid passing many parameters to function. If you have more than 4-5 parameters use class or structure to pass it.
Good:
public void UpdateAddress(Address address)
        {
     }
Bad:
public void UpdateAddress(int addressId, string country, string state, string phoneNumber, string pinCode, string address1, string address2)
        {
     }
24.   While working with collection be aware of below points,
a.       While returning collection return empty collection instead of returning null when you have no data to return.
b.      Always check Any() operator instead of checking count i.e. collection.Count > 0 and checking of null
c.       Use foreach instead of for loop while traversing.
d.      Use IList<T>, IEnumrable<T>,  ICollection<T> instead of concrete classes e.g. using List<>
25.   Use object initializers to simplify object creation.
Good:
                var employee = new Employee{
                                    FirstName = “ABC”,
                                    LastName = “PQR”,
                                    Manager = “XYZ”,
                                    Salary = 12346.25
                                };
Bad:
var employee = new Employee();
employee.FirstName = “ABC”;
employee.LastName = “PQR”;
employee.Manager = “XYZ”;
employee.Salary = 12346.25;
26.   Use meaningful names for linq query variables. The following example uses puneCustomers for customers who are located in Pune.
var puneCustomers = from cust in customers
                           where cust.City == “Pune”
                     select cust.Name;                          
27.   Don’t use single character names such as I, j, k instead of use index or counter specific to operation
for (int counter = 0; counter < nameArray.length; counter++)
       {
       }
      
       foreach (var employee in employees)
       {
 }
28.   The using statements should be sort by framework namespaces first and then application +namespaces in ascending order
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Company.Product.BusinessLayer;
29.   Make sure that you have good logging and tracing framework. If you configured to log errors, it should log only errors but if you configure to log traces then is should record all errors, warnings, and error details. You can trace or log errors into windows event log, sql server or to a separate file. User these logging or tracing framework extensively through the application.
30.   If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block.
31.   Simplify your code by using the C# using statement. If you have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using statement instead.
Good:
using (var fileToOpen = new FileInfo(fileName))
{
           // File operation
       }
Bad:
     var fileInfo = new FileInfo(fileName);
            try
            {
                // File operation
            }
            finally
            {
                if (fileInfo != null)
                {
                    fileInfo.Delete();
                }
     }
32.   Always catch only the specific exception instead of catching generic exception.
Good:
                   void ReadFile(string fileName)
        {
            try
            {
                // read from file.
            }
            catch (System.IO.IOException fileException)
            {
                // log the error. Re-throw exception
                throw fileException;
            }
            finally
            {
                // close file connection
            }
  }
Bad:
 void ReadFile(string fileName)
        {
            try
            {
                // read from file.
            }
            catch (Exception ex)
            {
                // catching general exception
            }
            finally
            {
                // close file connection
            }
  }
33.  Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations.
34.  Do the brainstorming session within team to make reusable components.

Architecture Design Level Guidelines

1.     Always use multi tier (N-Tier) Architecture.
2.     Implement loosely coupled architecture using interfaces and abstract class.
3.     Use of generics would help you to make reusable classes and functions.
public class MyClass<T> where T : SomeOtherClass
    {
        public void SomeMethod(T t)
        {
            SomeOtherClass obj = t;
        }
}
4.     Separate your application into multiple assemblies. Create separate assemblies for UI, Business Layer, Data Access Layer, Framework, Exception handling and Logging components.
5.     Do not access database from UI pages. Use data access layer to perform all task which are related to database.
6.     Always use stored procedure instead of writing inline queries in C# code.
7.     Always use transaction in database operation like Create, Update, and Delete. This would be helpful to rollback old data again in case of any exception occurred while execution of Sql statement.
8.     Don’t put complex logic inside stored procedure instead of it put it into the business layer.
9.     Don’t use prefix as “sp” or “sp_” to the user defined stored procedure similarly don’t use prefix as “fn” or “fn_” as the all system level procedure start with “sp” and functions start with “fn” which triggers overload for search of procedures.
10.  For installing database on client machine user installer sql scripts.
11.  Try to use design pattern, practices and SOLID principles.
12.  For same code, create separate utility file or move it to base class.
13.  Use try-catch-finally in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown to caller layer so that the application can catch it and show the user specific message on UI.
14.  Don’t store large objects into Session. Storing large or complex object into session may consume server memory. Destroy or Dispose such session variable after use.
15.  Don’t store large object into view state, this will increase the page load time.
16.  Always use style sheet classes to defile style. Avoid use of inline style in html instead create separate class and refer it to html UI.
17.  Always refer third party dll, javascripts and css framework through NuGet package so that you can update with latest version whenever required.
18.  Always refer minified version of javascript or css files, this will reduce unnecessary overhead to the server.

Recommended tools for Software Development

1.     Microsoft Enterprise Library
It is a collection of reusable component provided by Microsoft which can be useful for logging, validation, data access, exception handling, cashing, cryptography, security etc.
2.     Apply Code Analysis provided by visual studio
Code analysis tool of visual studio provides developers to identify design, interoperability, performance, security problems according to Microsoft’s rules which mainly focus on best practices to write code. The set of rules categorized into specific coding issues like security, design, Interoperability, globalizations.
Running code analysis tool in regular interval during development of software enhancing the quality of software.
3.     StyleCop
It is open source static code analysis tool that checks C# code with coding styles and set of rules defined by Microsoft. StyleCop analyzes the source code and allows it to enforce set of rules from Fxcop. StyleCop differentiated into documentation, maintainability, naming conventions, ordering, readability, spacing etc. categories.
4.     FxCop
It is open source static code analysis tool that checks .NET managed code assemblies for conformance to Microsoft .NET design guidelines. It only analyzes the compiled code not the source code. It is useful for finding coding standard violation in Design, localization, Naming conventions, performance, security, maintainability, portability and readability defined by Microsoft.
5.     Log4Net.dll
It is Apache provide tool used for logging of exceptions occurred in an application. The main future of log4net is its speed and flexibility. Using this you can log, Off (nothing will get logged), Fatal, Error, Warnings, Information Error, Debug, and All (Everything will gets logged)
6.     Resharper
It is an intelligent code inspection tool that automatically highlight the any code doesn’t match rule for naming conventions , detect the unused namespaces and variables used, object initializes and gives suggestion to modify LINQ queries.
7.     GhostDoc
 Using this you can generate XML comments for constructor, property, functions that closely follow the MSDN style of documentation.

Feedback and Contact            

You can download Pdf version of document by clicking here.

I do appreciate your valuable comments and suggestion to improve this document. You can reach me out using consultant.rohitn@gmail.com