Dependency Injection using Ninject in ASP.NET MVC

What is Dependency Injection?
In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. – Wikipedia. It makes software components are loosely coupled.

Advantages of Dependency Injection
• Flexibility to use alternative implementation of service.
• Configurable & easy to use
• Make system loosely couple
• Code becomes more reusable, testable, readable and manageable.
• Reduction of boilerplate code in the application objects

What is Ninject?
• Open Source Inversion of Control (IOC)
• It is a Dependency Injector for .NET created by Nate Kohari
• It’s very easy to use.
• Easily add from nuget.
• For more information visit Ninject.org
Let’s come to the implementation of DI using Ninject in ASP.NET MVC

Tools and Technology used
I used following tools and technology to develop the project –

1. Visual Studio 2013
2. Visual C#
3. ASP.NET MVC 5
4. Entity Framework 6
5. Razor view engine
6. Ninject for MVC5

Step 1: Create a ASP.net MVC Project
From Visual studio 2013, choose File->Project as below

01

Select MVC Template and click OK

02

Step 2: Create a model name Employee

Create a Model name Employee in model folder

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

Step 3: Change or Add Connection String
Change or Add connection string in Web.config


 
     
  

Step 4: Create a Context class


Create HRMContext Class in Repository folder.

    public class HRMContext : DbContext
    {
        public HRMContext()
            : base("DefaultConnection")
        {
        }
        public DbSet < Employee > Employees { get; set; }
    }

Step 5: Create Repository Interface and Concrete Class
Create IEmployeeRepository Interface and EmployeeRepository class in Repository folder

    public interface IEmployeeRepository : IDisposable
    {
        IQueryable  All { get; }
        Employee Find(int? id);
        void InsertOrUpdate(Employee employee);
        void Delete(int id);
        void Save();
    }


    public class EmployeeRepository : IEmployeeRepository
    {

        HRMContext context;
        public EmployeeRepository(HRMContext context)
        {
            this.context = context;
        }

        public IQueryable  All
        {
            get { return context.Employees; }
        }

        public Employee Find(int? id)
        {
            Employee objEmployee = new Employee();
            objEmployee = context.Employees.Where(p => p.Id == id).FirstOrDefault();
            return objEmployee;
        }

        public void InsertOrUpdate(Employee employee)
        {
            if (employee.Id == default(int))
            {
                // New entity
                context.Employees.Add(employee);
            }
            else
            {
                // Existing entity
                context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var employee = context.Employees.Find(id);
            context.Employees.Remove(employee);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }

Step 6: Install Ninject from nuget

03


Step 7: Map Interface and Concrete class in Ninject

Go to NinjectWebCommon file in App_Start folder. Add the following line for IEmployee Interface and Employee concrete class.

public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// 
        /// Starts the application
        /// 
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }
        
        /// 
        /// Stops the application.
        /// 
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        
        /// 
        /// Creates the kernel that will manage your application.
        /// 
        /// The created kernel.
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind().To();

                kernel.Bind().To();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// 
        /// Load your modules or register your services here!
        /// 
        /// The kernel.
        private static void RegisterServices(IKernel kernel)
        {
        }        
    }

Step 8: Create Controller and Views
Click Right button on Controller Folder->Add Controller. Choose its name as EmployeeController. Now choose scaffolding template for the controller as follows.

04

After clicking Add button, Employee Controller and Corresponding actions and views will be created automatically.

Step 9: Modify the controller

Modify the controller – use repository instead of context directly.

    public class EmployeesController : Controller
    {
        private readonly IEmployeeRepository repository;

        public EmployeesController(IEmployeeRepository objIrepository)
        {
            repository = objIrepository;
        }

        // GET: Employees
        public ActionResult Index()
        {
            return View(repository.All.ToList());
        }

        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

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

        // POST: Employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Designation,Dept,BloodGroup")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.InsertOrUpdate(employee);
                repository.Save();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: Employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Designation,Dept,BloodGroup")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.InsertOrUpdate(employee);
                repository.Save();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: Employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            repository.Delete(id);
            repository.Save();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                repository.Dispose();
            }
            base.Dispose(disposing);
        }
    }

Step 10: Run command in Package Manager Console

To find Package manager console go to

Tool->NuGet Package Manager -> Package Manager Console

Now, build the application and run the following command one by one in Package Manager Console.

PM> Enable-Migrations -ContextTypeName HRMContext
PM> Add-Migration initialmigration
PM> Update-Database -Verbose

Step 11: Add a menu
Add a menu name employee in _Layout.cshtml page to create a menu.

                

Run the application and click “Employee” menu. Now you can create, delete, read update employee information.

05

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();

}
}
}