An application cache helper class

CacheHelper class contains a few methods with generic object parameter.  There are 4 methods, Add, Clear, Exists and Get.

You can pass in value pairs into Add method to add to application cache.

And retrieve it by using Get method by passing the string key.

    public static class CacheHelper
        public static void Add(T o, string key, DateTime expiry) where T : class

        public static void Add(T o, string key) where T : class

        public static void Clear(string key)
            if (Exists(key))

        public static bool Exists(string key)
            if (HttpContext.Current != null)
                return HttpContext.Current.Cache[key] != null;
                return false;

        public static T Get(string key) where T : class
                return (T)HttpContext.Current.Cache[key];
                return null;

An example of using it,

I am reading the contract plans from repository and save into the application cache. Then check if it is in the cache before read the database again.

            const string key = "AllContractPlans";
            if (CacheHelper.Exists(key))
                return CacheHelper.Get<List>(key);
                var plans = _contractRepo.FindAll().ToList();
                CacheHelper.Add<List>(plans, key, DateTime.Now.AddMonths(2));
                return plans;

Application cache can speed up you application, but please be mindful that cache is shared across the whole application. And the data in your database may change as well, in that case, you need to clear your cache when you modify you data against database.

Create a MVC 3 web solution template – Part 3, Create a new solution using template

Create a new project from Visual Studio. Find your template from Visual C# templates.


It will ask you to configure to use IIS express


Because template contains no “packages” folders and the pre-installed nuget packages have no references. Project won’t compile.

Now right click solution and select “Enable Nuget Package Restore”


When you build your solution, packages will be downloaded and your nuget package references will be ok to resolve.


From time being, pre-installed nuget packages will have updates.

Right click Solution, select “Manage Nuget Packages for Solution…”

Select Updates Tab, to update packages



It is almost flawless, but….

You need to add project reference “Business”,”Data” to your “Web” project. And “Data” to your “Business” project.


Download the sample vstemplate from

Create a MVC 3 web solution template – Part 2, Create VS template and grouping projects

From part 1, I have talked about my project template structure. Now I want to talk about how do I create the VS templates and group them into one solution.

Visual Studio only allow you to create a template from one single project. So we need to write some vstemplate scripts to group our projects all together into one solution. And save the below script as “Template.vstemplate”.

<VSTemplate Version="3.0.0" xmlns="" Type="ProjectGroup">
 <Name>Web MVC 3 Template</Name>
 <Description>MVC 3 web application template</Description>
 <ProjectTemplateLink ProjectName="$safeprojectname$.Business">
 <ProjectTemplateLink ProjectName="$safeprojectname$.Web">
 <ProjectTemplateLink ProjectName="$safeprojectname$.Data">


If you use “Export Template” wizard from VS, export all projects from your solution, and unzip them into one folder.


In my example I have three projects, Data, Business and Web. Here is the folder structure.


Now zip all the files and folders into one single package. Put it into your Visual Studio template folder.

{Documents}\Visual Studio 2010\Templates\ProjectTemplates

Or change your template location to your folder. Open VS -> Tools -> Options -> projects and solutions


Now if you open VS and create a new project, you can find the template under C# projects.


Download the sample vstemplate from

Create a MVC 3 web solution template – Part 1, Create template projects

I am implementing a web application visual studio 2010 template at work. So it saves everyone’s time on a fresh start project. I decide to have 3 layers, presentation layer – web mvc3, business layer, and data access layer.

I have created a MVC3.WebTemplate solution with 3 projects, Business.Template , Data.Template and Web.Template. Let’s see what I have included in the three layers solution.


1. Web.Template


1.1 CodeTemplates

This folder contains the t4 templates to generate codes for views and controllers. I have included this in the project and it overrides the MVC default one. For more information, please read this blog

Have done this provides me ability to create my own t4 templates in the future, eg. in this template, I have modified the default template to make all controllers inherit a BaseController. When you create a new controller using the scaffolding template, it will create YourController : BaseController.

In the future I will create some view templates to make use of Twitter.Bootstrap and save you some time on styling the views.

1.2 Nuget Packages

I have included the latest packages for Jquery, Modernizr, Elmah, Ninject, Twitter.Bootstrap, etc.

  <package id="elmah" version="" />
  <package id="elmah.corelibrary" version="1.2.1" />
  <package id="Elmah.MVC" version="1.3.2" />
  <package id="EntityFramework" version="4.3.0" />
  <package id="jQuery" version="1.7.1" />
  <package id="jQuery.UI.Combined" version="1.8.17" />
  <package id="jQuery.Validation" version="1.9" />
  <package id="jQuery.vsdoc" version="1.6" />
  <package id="Microsoft.Web.Infrastructure" version="" />
  <package id="Modernizr" version="1.7" />
  <package id="Ninject" version="" />
  <package id="Ninject.MVC3" version="" />
  <package id="Twitter.Bootstrap" version="2.0.0" />
  <package id="WebActivator" version="1.4.4" />

Of course, you know Nuget will download all the packages in a Package folder in your solution folder. You don’t need to include those files into your template. You can easily restore the Nuget packages to a new solution thsi is created from the template.


2. Business.Template


Not much to talk about for this project, really it should contain all your business logics.

3. Business.Template


3.1 DataContext

For data access, I am using EntityFramework 4.3. I have included a empty context edmx file with t4 templates to generate DbContext & POCOs.

If you want do CodeFirst, you can remove my stuff under Data folder and put your POCOs there.

3.2 Repositories

I have included a generic base repository. To help you start building your repositories. It has the default CRUD operation methods which you can inherit from.


This is all about my project template, please refer to blog part 2 for the VS Template Creation.

Download the sample vstemplate from

Using Ninject in MVC 3

Previously I have chatted about how to use Structured Map and Unity for Dependency Injections. Here is the link

Today I am going to discuss how to use Ninject for your DI container.

First of all, let’s add Ninject and Ninject.MVC3 to our web application using Nuget. Here is the command you can use to install them in Package Manager Console in VS2010.

PM> Install-Package Ninject

PM> Install-Package Ninject.MVC3 -Version

Then let’s get started. And modify the Global.asax to use NinjectHttpApplication instead of HttpApplication. It overrides CreateKernel to create a kernel and load all the modules.

public class MvcApplication : NinjectHttpApplication
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
       filters.Add(new HandleErrorAttribute());
   public static void RegisterRoutes(RouteCollection routes)
           "Default", // Route name
           "{controller}/{action}/{id}", // URL with parameters
               controller = "Home",
               action = "Index",
               id = UrlParameter.Optional
   protected override IKernel CreateKernel()
       var kernel = new StandardKernel();
       return kernel;
   protected override void OnApplicationStarted()

The only thing that has to be done is to add dependencies for controller constructor and configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding.

public class HomeController : Controller
    private readonly IWelcomeMessageService welcomeMessageService;
    public HomeController(IWelcomeMessageService welcomeMessageService)
        this.welcomeMessageService = welcomeMessageService;
    public void Index()
        ViewModel.Message = this.welcomeMessageService.TodaysWelcomeMessage;
        return View();
public class WelcomeMessageServiceModule : NinjectModule
    public override void Load()

Ninject provides contextual bindings. It allows you to register more than one binding for a type. There are 3 ways.

1. add condition to the bindings.

interface ICondition {
  bool Matches(T obj);


2. Create Attribute

public class RangeAttribute : Attribute {}

public class Swordsman {
  [Inject] public IWeapon Weapon { get; set; }

public class Ninja {
  [Inject] public IWeapon MeleeWeapon { get; set; }
  [Inject, Range] public IWeapon RangeWeapon { get; set; }

3. Create Tags

public class Ninja {
  [Inject] public IWeapon MeleeWeapon { get; set; }
  [Inject, Tag("range")] public IWeapon RangeWeapon { get; set; }

Bind().To().Only(When.Context.Tag == "range");

Here are some references you can read more about Ninject. ( This blog post shows you how to use Ninject for Attribute bindings.) (Ninject Home)

EntityFramework 4.1 Extensions for batch Delete and Update

A great library that extends the functionality of EF. It provides the features to do batch updates, delete and future queries and audit log.

PM> Install-Package EntityFramework.Extended

Use the Package Manager Console in VS2010 to install it. And you can find the source in Github.

Make sure you import the Extensions namespace. Then you will see the extension methods of batch delete/update. Here are a few lines of code to demonstrate how to delete, update.

using EntityFramework.Extensions;

context.Users.Delete(u => u.FirstName == "firstname");

    t => t.StatusId == 1, 
    t => new Task {StatusId = 2});

For future query usage, you can use an IQueryable as the filter for the update

var users = context.Users
   .Where(u => u.FirstName == "firstname");

   u => new User {FirstName = "newfirstname"})

Pretty cool is it! To read more documentations go to the github site.