ASP.NET Application Performance Tuning and Scalability Improvement (Part – 1)

Every developers and customer wants his/her application performed well. But it is very tricky to improve performance of a web application. It’s actually depends on different parameter like HTML client, HTTP network, Web server, middle-tier components, database components, resource-management components, TCP/IP networks, and database servers. Sometimes performance of the application increases drastically, if you change a single parameter. Sometimes you have to change multiple parameters. Here are the some performance optimization tips for ASP.NET web applications which may help you to increase performance of ASP.NET Application.

Prepare release with release mode
When prepare release for deployment, select release mode instead of debug mode.

How affect in performance?

  • If you choose debug mode instead of release mode, you are creating pdb (program database – uses for debugging) files which creates extra overhead. For this reason you may face timeout problem.

Best Practice

  • Always prepare release in release mode.

Release mode

In Web.Config, Set debug=”false”
Set debug=”false” in web.config as follows after deploying your application. By default debug=”true” when you create a web application. It is necessary to set debug=”true” in development environment.

  
    
  

How affect in performance?

  • If you set debug = “true”, application requires the pdb information to be inserted into the file and that results in a comparatively larger file and hence processing will be slow.

Best Practice

  • In deployment server, set debug = “false” in web.config

Turn off Tracing unless until required
Sometimes developers need to trace the application to monitor the executions of application or a pages. It requires for application diagnostic purposes.

How affect in performance?

  • When trace is enabled it loaded extra information to the pages which degrades performances.

Best Practice

  • Always set trace enabled = “false” unless or until you required to monitor a page’s executions. Set trace enable = “false” as follows in web.config.

    

Carefully manage session state
Session state is a very useful feature of asp.net. Though, ASP.NET manages session state by default, we must pay attention of session memory management.

  • How affect in performance?
  • When you store your data in in-process or on a state server or in a SQL Database, session state, it requires memory.
  • It is also time consuming when you store or retrieve data in-process or state server or SQL server.

Best Practice

  • If your page is static, it is recommended not to use session state. In such cases where you don’t need to use session state, disable it on your web form using the following directive:
    <@%Page EnableSessionState="false"%>
  • In case you use the session state only to retrieve data and not to update, make the session state read-only using the following directive.
    <@%Page EnableSessionState ="ReadOnly"%>
  • If your application session state is out of process then consider carefully whether there is a need of the state server or SQL Server mode.
  • SQL Server session mode provides lower performance than state server mode.
  • Try to avoid keeping object in session. Since it requires serializing then de-serializing which affected in performance.
  • Use client-side state management than server side.

Disable View State of a page if not required

  • It stores data in the generated HTML using hidden field not on the server.
  • View State provides page level state management
  • As long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost
  • View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserialization on each post back

How affect in performance?

  • It increases the total payload of a page when submitted and when serving request.
  • Serialization and deserialization of the data is required when submitting data and gets requested data.
  • View state increases the memory allocations on the server.

Best Practice

  • Pages that do not have any server postback events can have the view state turned off.
  • The default behaviour of the View State property is enabled, but if you don’t need it, you can turn it off at the control or page level.
  • Within a control, simply set the EnableViewState property to false, or set it globally within the page using this setting.

    <%@ Page EnableViewState="false" %>

Use finally block to release resources
We always uses try, catch and finally block for exception handling. Finally block executes whether any exception occurs or not.
How affect in performance?

  • Sometimes application occupy resources where as it doesn’t need it. It is occur due to bad programming.

Best Practice

  • Always use a finally block to release resources like closing database connections, closing files, disposing objects and other resources.

Avoid unnecessary round trips to the server

How affect in performance?

  • Unnecessary round trips significantly effect on web application performance.
  • It increases network latency and downstream server latency.
  • Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.

Best Practice

  • Keep round trips as minimum as possible
  • Use Ajax or partial page load instead of full page reload or refresh.

Choose low cost authentication
Authentication is a main factor for a secured applications. You must take decision which authentication will you use? Keep in mind, passport authentication is slower than form-base authentication which is slower than Windows authentication.

Use paging in grid view
In asp.net web application to show data in tabular format, generally we use grid view. Besides this we also uses DataGrid, JQgrid, Telerik grid, Kendo Grid etc. For huge number of data we cannot think general way because it takes huge time to load.

Best Practice

  • To load grid view faster take advantages of paging, it shows small subsets of data at a time. JQGrid is faster than asp.net grid view because it does everything in client side.

Minimizes number of web server control

How affect in performance?

  • The uses of web server controls increase the response time.
  • Web server controls go to the server executes all of its life cycle and then rendered on the client side.

Best Practice

  • Don’t use server control unless until required. Use HTML elements where suited.

Generic Repository Pattern with ASP.NET MVC and Entity Framework

Introduction
You may introduce with an Object Oriented Design Principle name DRY – Don’t repeat yourself. It is more important in Multi-tier architecture. We can use generic repository pattern to implement DRY.

What is Repository Pattern?
In most of the business operation we have to perform CRUD (Create, Read, Update and Delete) operation. A repository basically works as a mediator between our business logic layer and our data access layer of the application

Benefits of Repository Pattern

  • Centralizes data logic or service logic.
  • Provides a substitution point for the unit tests for both business logic and data access logic
  • Provides a flexible architecture
  • Can adopt new change easily
  • Domain driven development is easier


What is Generic Repository Pattern?

Generic Repository is a pattern by which we can use single repository for data access of all models. Generally, we used one repository for one model to access data.

Benefits of Generic Repository Pattern

  • Reduce redundancy of code
  • Force developer to work same pattern – Possibility of less error or no error
  • Easy to maintain – Centralize data access logic

Implementation Repository Pattern with ASP.NET MVC and Entity Framework

Let’s consider a project to keep Employee Information. Here I will show CRUD operation on employee information.
Tools and Technology used
I used following tools and technology to develop the project – Implementation of generic repository

  • Visual Studio 2013
  • Visual C#
  • ASP.NET MVC 5
  • Entity Framework 6
  • Razor view engine


Step 1:
Create an ASP.NET MVC 5 application using Visual Studio 2013. I kept the application name “GenericRepo”.
Help: How to create first application using asp.net MVC
Step 2: Configure connection string in web.config

  
    
  

Step 3: Create Model – “Employee”

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string FatherName { get; set; }
        public string MotherName { get; set; }
        public string Designation { get; set; }
        public string Dept { get; set; }
    }

Step 4: Create a DbContext name GenericDbContext in Repository folder.

    public class GenericRepoContext : DbContext
    {
        public GenericRepoContext()
            : base("DefaultConnection")
        {
        }

        public DbSet Employees { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }
    }

Step 5: Create IGenericRepository and GenericRepository in Repository folder


    interface IGenericRepository where T : class
    {
        IEnumerable SelectAll();
        T SelectByID(object id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(object id);
        void Save();
    }

public class GenericRepository : IGenericRepository where T : class
    {
        private GenericRepoContext db = null;
        private DbSet table = null;
        public GenericRepository()
        {
            this.db = new GenericRepoContext();
            table = db.Set();
        }
        public GenericRepository(GenericRepoContext db)
        {
            this.db = db;
            table = db.Set();
        }
        public IEnumerable SelectAll()
        {
            return table.ToList();
        }
        public T SelectByID(object id)
        {
            return table.Find(id);
        }
        public void Insert(T obj)
        {
            table.Add(obj);
        }
        public void Update(T obj)
        {
            table.Attach(obj);
            db.Entry(obj).State = EntityState.Modified;
        }
        public void Delete(object id)
        {
            T existing = table.Find(id);
            table.Remove(existing);
        }
        public void Save()
        {
            db.SaveChanges();
        }
    }

Step 6:
Create a controller name – EmployeeController. Select template “MVC5 Controller with read/write action”

    public class EmployeeController : Controller
    {
        private IGenericRepository repository = null;
        public EmployeeController()
        {
            this.repository = new GenericRepository();
        }


        // GET: Employee
        public ActionResult Index()
        {
            var employee = repository.SelectAll().ToList();
            return View(employee);
        }

        // GET: Employee/Details/5
        public ActionResult Details(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // GET: Employee/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Employee/Create
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.Insert(employee);
                repository.Save();

                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: Employee/Edit/5
        public ActionResult Edit(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // POST: Employee/Edit/5
        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            try
            {
                repository.Update(employee);
                repository.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Employee/Delete/5
        public ActionResult Delete(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // POST: Employee/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                repository.Delete(id);
                repository.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

Step 7: Create List, Edit, Delete and details page against EmployeeController.
Create a list view

1-List

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.FatherName) @Html.DisplayNameFor(model => model.MotherName) @Html.DisplayNameFor(model => model.Designation) @Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.FatherName) @Html.DisplayFor(modelItem => item.MotherName) @Html.DisplayFor(modelItem => item.Designation) @Html.DisplayFor(modelItem => item.Dept) @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Create Edit View
Create edit view as like list view and choose edit template for that.
_CreateOrEdit.cshtml

@model GenericRepo.Models.Employee

    
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.MotherName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.MotherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.MotherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Dept, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Dept, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })


Edit.cshtml

@model GenericRepo.Models.Employee


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    

Employee


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.Partial("_CreateOrEdit", Model)
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Create Delete View
Create delete view as like list view and choose delete template for that.
Delete.cshtml

@model GenericRepo.Models.Employee

Are you sure you want to delete this?

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.MotherName)
@Html.DisplayFor(model => model.MotherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Create Details View
Create details view as like list view and choose details template for that.
Details.cshtml

@model GenericRepo.Models.Employee

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.MotherName)
@Html.DisplayFor(model => model.MotherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)

@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index")

Step 8: Add a link “Employee” to _Layout page like below

         

Step 9: Write following command in package manager console
PM> Enable-Migrations -ContextTypeName GenericRepoContext
PM> Add-Migration initalcreate
PM> Update-Database -Verbose -Force

Now your project is ready. Run application and execute CRUD operation on it. Output of the application like below.
Output:

2

Decorator Design Pattern with C#

You who work on design pattern must familiar with Gang of Four (GoF). Design Patterns: Elements of Reusable Object-Oriented Software is a Software Engineering book. The authors of this book are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The authors of this book are often refers to as Gang of Four (GoF). It’s a parody relating to Mao’s Gang of Four. This book describes the recurring solution of common problem in software design. The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Factory Pattern, Abstract Factory Pattern, Singleton Pattern, Builder e.t.c are creational design pattern. Decorator, Adapter, Bridge, Façade, Proxy, Composite e.t.c are structural design pattern. Command, interpreter, strategy, iterator e.t.c are behavioral design pattern.

Decorator Design Pattern
Decorator Design Pattern is a structural design pattern. It is also known as wrapper. It is used to add additional functionality to a particular object during run time without affecting other objects. Responsibility can be adding or removing at run time. Critics says that it uses lot of little object of similar type.

Let’s consider a scenario in which I am going to implement Decorated Design Pattern. We, Bangladeshi are very much cricket loving. A cricket equipment shop declared some package on the occasion of Cricket World Cup 2011. The base package is with a bat and a ball and its cost is 1500 Taka (Bangladeshi Currency). The smart package is with a bat, a ball and 6 stamps i.e base package plus 6 stamps and its cost is 1500 + 600 = 2100 Taka. The special package is with a bat, a ball, 6 stamps and a pair of gloves i.e smart package plus a pair of gloves. It’s cost is 2100 + 500 = 2600 Taka. It looks like the following figure. Actually, the top one wrapped the inner packages.

BlockDiagramDP

Before going to implement the scenario by decorated design pattern, I would like to show you the class diagram. The class diagram is given below.

DP_Class Diagram

Implementation: Let’s implement decorated design pattern by C#.

Step 1: Create interface ICricketInstrument for all package of cricket instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Interface for Cricket Instrument
/// Developed by: Mahedee
///

public interface ICricketInstrument
{
double Cost { get; }
string Insturments { get; }
}
}

Step 2: Create a base type for Concrete Cricket Instrument Package and Instrument Package Option

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Base type for concrete cricket instrument package and decorator(option).
/// Developed by: Mahedee
///

public abstract class CricketInstrument : ICricketInstrument
{
private double cost = 00;
private string instrument = "Cricket Instruments: ";

#region ICricketInstrument Members

public virtual double Cost
{
get { return cost; }
}

public virtual string Insturments
{
get { return instrument; }
}

#endregion
}
}

Step 3: Create a base type for Concrete Cricket Instrument Package Option. It is actually decorator – to decorate Instrument package.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace DecoratorPattern
{
    /// 
    /// Decorator for concrete package option
    /// 
    public abstract class PackageOption : CricketInstrument
    {
        double cost = 00;
        string instruments = "Abstract Package Option";

        public override double Cost
        {
            get { return cost; }
        }


        public override string Insturments
        {
            get { return instruments; }
        }

    }
}

Step 4: Create base package of Cricket Instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Base Cricket Insturment Package
///

public class BasePackage : CricketInstrument
{
double cost = 1500;
string instruments = "Ball and Bat";

public override double Cost
{
get { return cost; }
}

public override string Insturments
{
get { return base.Insturments + instruments; }
}

}
}

Step 5: Decorate Smart package for Cricket Instrument

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Smart Package = Base Package (Bat, Ball) + 6 Stamps
/// Developed by: Mahedee
///

public class SmartPackage : PackageOption
{
double cost = 600;
string instruments = "6 Stamps";
CricketInstrument objCricketInstrument;

public SmartPackage(CricketInstrument objPCricketInstrument)
{
objCricketInstrument = objPCricketInstrument;
}

public override double Cost
{
get { return objCricketInstrument.Cost + cost; }
}

public override string Insturments
{
get { return objCricketInstrument.Insturments + ", " + instruments; }
}
}
}

Step 6: Decorate Special Package for Cricket Instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Special Package = Base Package (Bat, Ball) + 6 Stamps + 1 Pair - Gloves
/// Developed by: Mahedee
///

public class SpecialPackage : PackageOption
{
double cost = 500;
string instruments = "Gloves - 1 Pair";
CricketInstrument objCricketInstrument;

public SpecialPackage(CricketInstrument objPCricketInstrument)
{
objCricketInstrument = objPCricketInstrument;
}

public override double Cost
{
get { return objCricketInstrument.Cost + cost; }
}

public override string Insturments
{
get { return objCricketInstrument.Insturments + ", " + instruments; }
}

}
}

Step 7: Program class to create base package and decorate other package with option.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
public class Program
{
static void Main(string[] args)
{
//Base Insturment class

CricketInstrument objCricketInstruments = new BasePackage();
Console.WriteLine("::Base Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.WriteLine();

//Smart Package
objCricketInstruments = new SmartPackage(objCricketInstruments);
Console.WriteLine("::Smart Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.WriteLine();

//Special Package
objCricketInstruments = new SpecialPackage(objCricketInstruments);
Console.WriteLine("::Special Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.ReadLine();

}
}
}

Singleton Design Pattern with C#

Design Pattern

Design pattern is a solution of known problems. These are strategies of solving commonly occurring problems. A design pattern is not a finish design. It is like a template to solve a problem.

Singleton Design Pattern

Singleton is a software design pattern. It is restrict to create object more than once. This is actually needed when one object can perform its action in whole system. We frequently use a database connection object to connect with database. We don’t need multiple objects to create connection with database and close it. We can use singleton in this scenario.

Implementation of Singleton by C#

Step 1: Create EmployeeInfo class

This class is to hold employee information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
public class EmployeeInfo
{
public string EmpName { get; set; }
public string EmpDesignation { get; set; }
public int MonthlySalary { get; set; }
}
}

Step 2: Create a singleton class

Here EmployeeService is a singleton class. Constructor of this class is private so that nobody can create its instance from outside.  Instance() is a static method which creates instance of the singleton class. It actually forces that only one instance of the object will be created. Lock() is used to create instance of the singleton pattern in thread safe manner in multi threaded environment. The other two methods are used to add employee information in list and get employee salary. These two are as usual method.Don’t mix up Singleton class and Static class. Keep in mind; in static class everything must be static like Method, constructor, properties. But in singleton class it is not required. Hope, you will be clear after the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
///
/// EmployeeService is a singleton class
///

public class EmployeeService
{

//Static object of singleton class
private static EmployeeService instance;

private List lstEmployeeInfo = null;

///
/// Restrict to create object of Singleton class
///

private EmployeeService()
{
if (lstEmployeeInfo == null)
{
lstEmployeeInfo = new List();
}
}

///
/// The static method to provide global access to the singleton object.
///

/// Singleton object of EmployeeService class
public static EmployeeService Instance()
{

if (instance == null)
{
//Thread safe singleton

lock (typeof(EmployeeService))
{
instance = new EmployeeService();
}
}

return instance;
}

///
/// Add employee information to the Employee information list
///

///

public void AddEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
lstEmployeeInfo.Add(objEmployeeInfo);
}

///
/// Get Salary by Name
///

////// Salary of Employee

public int GetEmployeeSalaryByName(string name)
{
int monthlySalary = 0;
foreach (EmployeeInfo objEmployeeInfo in lstEmployeeInfo)
{
if (objEmployeeInfo.EmpName.Contains(name))
monthlySalary = objEmployeeInfo.MonthlySalary;
}
return monthlySalary;
}

}
}

Step 3: Access singleton class

This class creates an instance of singleton class by EmployeeService objEmployeeService = EmployeeService.Instance(); and access singleton class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
class Program
{
static void Main(string[] args)
{
EmployeeInfo objEmpInfo1 = new EmployeeInfo() { EmpName = "Mahedee", EmpDesignation = "Senior Software Engineer", MonthlySalary = 00000 };
EmployeeInfo objEmpInfo2 = new EmployeeInfo() { EmpName = "Kamal", EmpDesignation = "Software Engineer", MonthlySalary = 30000 };

//Create a singleton object
EmployeeService objEmployeeService = EmployeeService.Instance();

objEmployeeService.AddEmployeeInfo(objEmpInfo1);
objEmployeeService.AddEmployeeInfo(objEmpInfo2);

Console.WriteLine(objEmpInfo2.EmpName + " : " + objEmployeeService.GetEmployeeSalaryByName("Kamal"));

Console.ReadLine();

}
}
}

Iterator Design Pattern with C#

Iterator pattern is a design pattern which is used to traverse aggregate object often called container and access container’s object without exposing it’s underlying representation. Iterator pattern decoupled algorithm from aggregate object or container. In some cases, algorithms are container specific. We often use collection in C# and then we traverse the collection without knowing it’s internal details. Collection is grouping of some object. Objects can be same type or different type. Collection in fact actively used iterator pattern.

UML_Iterator

The above figure is UML class diagram for Iterator Pattern. The main idea behind the iterator pattern is to take the responsibility of traversing container and put it to the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and track for the next item to iterate.

Benefits:

  1. Access element of container without exposing it’s internal details.
  2. Provides a uniform interface for traversing different collection (aggregate object).
  3. Provides multiple simultaneous traversals in a collection.

Implementation:

Let’s come to the point. We are going to implement iterator design pattern. I am using here a collection for fruits item. The main actor in here:

IIterator – Interface to define Iterator (Concrete iterator class)

Iterator – Concrete iterator class which is used to iterate elements.

ICollection – Interface to define aggregate.

Collection – Concrete aggregate class.

I used FruitItem class as item class here.

Step 1: Create Item class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Item class
///

public class FruitItem
{
public string Id { get; set; }
public string Name { get; set; }
}

}

Step 2: Create IIterator Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Interface for Iterator
///

public interface IIterator
{
FruitItem First();
FruitItem Next();
FruitItem CurrentItem { get; }
bool IsDone { get; }
}
}

Step 3: Create concrete Iterator class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Concrete Iterator Class
///

public class Iterator : IIterator
{

private Collection collection;
private int current = 0;
private int step = 1;

public Iterator(Collection vCollection)
{

this.collection = vCollection;

}

public FruitItem First()
{
current = 0;
return (FruitItem)collection[current];
}

public FruitItem Next()
{
current ++;

if (!IsDone)
return (FruitItem)collection[current];
else
return null;
}

public bool IsDone
{
get { return current >= collection.Count; }
}

public FruitItem CurrentItem
{
get { return (FruitItem) collection[current]; }
}

// Gets or sets stepsize
public int Step
{
get { return step; }
set { step = value; }

}

}
}

Step 4: Create collection interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Interface for Aggregate class
///

public interface ICollection
{
Iterator CreateIterator();
}
}

Step 5: Create concrete collection class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace IteratorPattern
{
///
/// Concrete aggregate class
///

public class Collection : ICollection
{
private ArrayList lstFoodItem = new ArrayList();

public Iterator CreateIterator()
{
return new Iterator(this);
}

// Get counted items
public int Count
{
get
{
return lstFoodItem.Count;
}

}

// Indexer

public object this[int index]
{

get { return lstFoodItem[index]; }

set { lstFoodItem.Add(value); }

}
}
}

Step 6: Create client class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
class Program
{
public static void Main(string[] args)
{
Collection collection = new Collection();

collection[0] = new FruitItem() { Id = "1", Name = "Mango" };
collection[1] = new FruitItem() { Id = "2", Name = "Orange" };
collection[2] = new FruitItem() { Id = "3", Name = "Banana" };
collection[3] = new FruitItem() { Id = "4", Name = "Apple" };
collection[4] = new FruitItem() { Id = "5", Name = "Lichi" };
collection[5] = new FruitItem() { Id = "7", Name = "Tamarind" };

// Create iterator
Iterator iterator = new Iterator(collection);
Console.WriteLine("Items by iterating over collection");

for (FruitItem item = iterator.First(); !iterator.IsDone; item = iterator.Next())
{
Console.WriteLine(item.Name);
}

Console.ReadLine();
}
}
}

Output:

output

Strategy Design Pattern with C#

Strategy design pattern is a behavioral design pattern. It is a particular software design pattern where algorithms are selected at runtime.

According to the book of Design Pattern (Gang of Four) – “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. “

The key phrases of definition are “Family of algorithms”, “encapsulate”, and “interchangeable”. Actually, Strategy Pattern encapsulates a collection of functions that do similar yet not identical jobs. Client is not bound to call fixed methods; rather it can change its strategy dynamically at run time. Client don’t call any methods directly by instantiating concrete classes. It sets its strategy via context class.

There are three main parts in strategy pattern:

  1. Strategy – An interface that defines how the algorithm will be called.
  2. Concrete Strategy – The implementation of the strategy.
  3. Context – It holds the concrete strategy.

StrategyPattern

Implementation:

Suppose you have two lists of items. Item here integer numbers. Now, if you want to search an item from either of the lists. You can use either one of the algorithms from Linear Search or Binary search. Since binary search algorithm cannot search data without sorted list, we take here a sorted list. Now the strategy of client to use which one – Binary search or linear search. Let’s implement the problem by strategy pattern using c#.

Step 1: Create an Interface for Strategy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Strategy defines how algorithm will be called
///

public interface ISearchStrategy
{
int Search(int[] list, int item);
}
}

Step 2: Create concrete strategy (Linear Search)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 3: Create concrete strategy (Binary Search)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Binary Search Algorithm)
///

public class BinarySearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Binary Search");

int beg = 0;
int end = list.Count() - 1;
int mid = (int)((beg + end)/2);
int position = 0;

while (beg <= end && list[mid] != item)
{
if(item < list[mid])
end = mid - 1;
else
beg = mid + 1;

mid = (int)((beg + end)/2);
}

if (list[mid] == item)
position = mid;
else
position = 0;

return position;
}

#endregion
}
}

Step 4: Create a context class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 5: Client class to demonstrate strategy pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Client class
///

class Program
{
static void Main(string[] args)
{

int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

//Instance of context to follow different strategies
SearchList objSearchList = new SearchList();

objSearchList.SetSearchStrategy(new BinarySearch());
objSearchList.Search(sortedList, 4);

objSearchList.SetSearchStrategy(new LinearSearch());
objSearchList.Search(sortedList, 7);

Console.ReadLine();
}
}
}

Output:
output_strategyPattern

Abstract Factory Pattern with C#

Abstract factory pattern is a creational design pattern. Creational design pattern is deals with object creation mechanism. Object creation mechanism is changed on the basis of problem. Abstract factory pattern provides an interface to create families of related or dependent objects without specifying their concrete class. It is identified on the basis of problem complexity. It is encapsulated the process of instantiation of family of classes. Abstract factory pattern is widely used in framework and libraries to encapsulate the family of classes.

Elements of Abstract Factory Pattern:

  1. Abstract Factory – An Interface to create families of related or dependent item object.
  2. Concrete Factory – Implement the interface to create families of related item object.
  3. Abstract Item – An interface to create concrete item object.
  4. Concrete Item – Implement the interface to create concrete item object.
  5. Client – Uses Interface (abstract Item) provided by abstract factory and access concrete object by this interface.

Implementation:

Here I implemented abstract factory pattern in International Cricket Team by C#. The UML diagram is given below.

AFP-1

Step 1: Create interface for Item class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// Interface for Item class
///

public interface ICricketer
{
string BattingStrength();
string BowlingStrength();
string AllroundingStrength();
string IconPlayer();
}
}

Step 2: Create Factory Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// A Factory interface
///

public interface ICricketerFactory
{
ICricketer GetCricketer(CricketerBase cricketerBase);
}
}

Step 3: Define the type of Base object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Define the type of Base Object
///

public enum CricketerBase
{
AustralianCricketer,
BangladeshiCricketer,
EnglishCricketer,
IndianCricketer,
PakistaniCricketer
}

}

Step 4: Create Concrete factory class for Asian Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Concrete factory class for Asian Cricketer
///

public class AsianCricketerFactory : ICricketerFactory
{

#region ICricketerFactory Members

public ICricketer GetCricketer(CricketerBase cricketerBase)
{
ICricketer objICricketer = null;

switch (cricketerBase)
{
case CricketerBase.BangladeshiCricketer:
objICricketer = new BangladeshiCricketer();
break;
case CricketerBase.IndianCricketer:
objICricketer = new IndianCricketer();
break;
default:
break;
}
return objICricketer;
}

#endregion
}
}

Step 5: Create Concrete factory class for European Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// Concrete factory class for European Cricketer
///

public class EuropeanCricketerFactory : ICricketerFactory
{

#region ICricketerFactory Members

public ICricketer GetCricketer(CricketerBase cricketerBase)
{
ICricketer objICricketer = null;

switch (cricketerBase)
{
case CricketerBase.EnglishCricketer:
objICricketer = new EnglishCricketer();
break;
default:
break;
}
return objICricketer;
}

#endregion
}
}

Step 6: Create Item class for Bangladeshi Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Bangladeshi Cricketer
///

public class BangladeshiCricketer : ICricketer
{
#region ICricketer Members

public string BattingStrength()
{
return "60%";
}

public string BowlingStrength()
{
return "70%";
}

public string AllroundingStrength()
{
return "85%";
}

public string IconPlayer()
{
return "Shakib Al Hasan";
}

#endregion
}
}

Step 7: Create Item Class for Indian Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Indian Cricketer
///

public class IndianCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "85%";
}

public string BowlingStrength()
{
return "60%";
}

public string AllroundingStrength()
{
return "70%";
}

public string IconPlayer()
{
return "Shachin Tendulkar.";
}

#endregion
}
}

Step 8: Create Item class for Pakistani Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Pakistani Cricketer
///

public class PakistaniCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "75%";
}

public string BowlingStrength()
{
return "85%";
}

public string AllroundingStrength()
{
return "75%";
}

public string IconPlayer()
{
return "Shahid Afridi.";
}

#endregion
}
}

Step 9: Create Item class for English Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for English Cricketer
///

public class EnglishCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "75%";
}

public string BowlingStrength()
{
return "80%";
}

public string AllroundingStrength()
{
return "70%";
}

public string IconPlayer()
{
return "Kavin Pietersen";
}

#endregion
}
}

Step 10: Create a client class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Client Class
///

class Program
{
static void Main(string[] args)
{
AsianCricketerFactory objAsianFactory = new AsianCricketerFactory();
ICricketer objIAsianCricketer = objAsianFactory.GetCricketer(CricketerBase.BangladeshiCricketer);
Console.WriteLine("Bangladesh Cricket Team\nBatting Strength:" + objIAsianCricketer.BattingStrength());
Console.WriteLine("Bowling Strength:" + objIAsianCricketer.BowlingStrength());
Console.WriteLine("Allrounding Strength:" + objIAsianCricketer.AllroundingStrength());
Console.WriteLine("Icon Player:" + objIAsianCricketer.IconPlayer());

Console.WriteLine();

EuropeanCricketerFactory objEuropeanFactory = new EuropeanCricketerFactory();
ICricketer objIEuropeanCricketer = objEuropeanFactory.GetCricketer(CricketerBase.EnglishCricketer);
Console.WriteLine("England Cricket Team\nBatting Strength:" + objIEuropeanCricketer.BattingStrength());

Console.WriteLine("Bowling Strength:" + objIEuropeanCricketer.BowlingStrength());
Console.WriteLine("Allrounding Strength:" + objIEuropeanCricketer.AllroundingStrength());
Console.WriteLine("Icon Player:" + objIEuropeanCricketer.IconPlayer());

Console.ReadLine();

}
}
}

Output:
AFP-Output

Factory Design Pattern with C#

Factory design pattern implements the concept of real world factories. Factory pattern is a creational design pattern. It deals with creating object without specifying exact class. In general, actors of factory patterns are a client, a factory and a product. Client is an object that requires another object for some purposes. Rather than creating the product instance directly, the client delegates this responsibility to the factory. The factory then creates a new instance of the product, passing it back to the client. Figure shows the whole process.

FP-1

Application

For an example, a banking application works with accounts. In this application there are different types of account like saving account and checking account. All accounts are derived from an abstract account name IAccount. The IAccount defines the withdraw, deposit and interest rate which must be implemented by the concrete accounts (saving account, checking account). If clients want to know the interest rate of the Saving Account. It just invoke the factory to create an instance of Saving account.  Being invoked factory, it creates an instance of the saving account and then client just get the interest rate by invoking interest method. The client uses the object as casted to the abstract class without being aware of the concrete object type. Over all implementation of this scenario is given below.

The advantage is in here that new account can be added without changing a single line of code in the client code. Here an object is created without exposing instantiation logic to the client. The object generation is centralized here.

Benefits:

  • Factory Pattern is the mostly used pattern.
  •  Decoupled the classes i.e eliminates the need to bind application specific class
  • The code only deals with the Interface.
  •  Factory Pattern provides the way to create multiple instances of classes.
  •  This provides a hook so that we can derive a sub-class to create different controls to display the data.
  •   Factory method connects the class hierarchies with minimum coupling.
  •  Product implementation may change over time but client remains unchanged.

Implementation

Step 1: Create an Interface – IAccount

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
public interface IAccount
{
string Withdraw(int amount);
string Deposit(int amount);

double InterestRate();
}
}

Step 2: Create concrete classes

Saving account

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
///
/// Concrete class SavingsAccount
///

public class SavingsAccount : IAccount
{
#region IAccount Members

public string Withdraw(int amount)
{
throw new NotImplementedException();
}

public string Deposit(int amount)
{
throw new NotImplementedException();
}

public double InterestRate()
{
return 12.5;
}

#endregion
}
}

Checking Account

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{

///
/// Concrete class CheckingAccount
///

public class CheckingAccount : IAccount
{
#region IAccount Members

public string Withdraw(int amount)
{
throw new NotImplementedException();
}

public string Deposit(int amount)
{
throw new NotImplementedException();
}

public double InterestRate()
{
return 10.24;
}

#endregion
}
}

Step 3: Create a Factory Object Enum

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
///
/// FactoryObject Enum to configure object
///

public enum FactoryObject
{
SavingAccount,
CheckingAccount
}
}

Step 4: Create a factory class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
///
/// Factory class to create object
///

public static class Factory
{
public static IAccount CreateObject(FactoryObject factoryObject)
{
IAccount objIAccount = null;

switch (factoryObject)
{
case FactoryObject.SavingAccount:
objIAccount = new SavingsAccount();
break;

case FactoryObject.CheckingAccount:
objIAccount = new CheckingAccount();
break;

default:
break;
}

return objIAccount;
}
}
}


Step 5: Access from client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
public class Program
{
public static void Main(string[] args)
{
//Create object by factory pattern
IAccount objSavingAccount = Factory.CreateObject(FactoryObject.SavingAccount);
IAccount objCheckingAccount = Factory.CreateObject(FactoryObject.CheckingAccount);

//Access object
Console.WriteLine("Saving Account Interest Rate: " + objSavingAccount.InterestRate());
Console.WriteLine("Checking Account Interest Rate: " + objCheckingAccount.InterestRate());

Console.ReadLine();

}
}
}