How to Implement the Repository Pattern in ASP.NET MVC Application

Read full article on the Infragistics blog

The Repository Pattern is one of the most popular patterns to create an enterprise level application. It restricts us to work directly with the data in the application and creates new layers for database operations, business logic and the application’s UI. If an application does not follow the Repository Pattern, it may have the following problems:

  • Duplicate database operations codes
  • Need of UI to unit test database operations and business logic
  • Need of External dependencies to unit test business logic
  • Difficult to implement database caching, etc.

Using the Repository Pattern has many advantages:

  • Your business logic can be unit tested without data access logic;
  • The database access code can be reused;
  • Your database access code is centrally managed so easy to implement any database access policies, like caching;
  • It’s easy to implement domain logics;
  • Your domain entities or business entities are strongly typed with annotations; and more.

On the internet, there are millions of articles written around Repository Pattern, but in this one we’re going to focus on how to implement it in an ASP.NET MVC Application. So let’s get started!

Project Structure

Let us start with creating the Project structure for the application. We are going to create four projects:

  1. Core Project
  2. Infrastructure Project
  3. Test Project
  4. MVC Project

Each project has its own purpose. You can probably guess by the projects’ names what they’ll contain: Core and Infrastructure projects are Class Libraries, Web project is a MVC project, and Test project is a Unit Test project. Eventually, the projects in the solution explorer will look as shown in the image below:

As we progress in this post, we will learn in detail about the purpose of each project, however, to start we can summarize the main objective of each project as the following:

So far our understanding for different projects is clear. Now let us go ahead and implement each project one by one. During the implementations, we will explore the responsibilities of each project in detail.

Core Project

In the core project, we keep the entities and the repository interfaces or the database operation interfaces. The core project contains information about the domain entities and the database operations required on the domain entities. In an ideal scenario, the core project should not have any dependencies on external libraries. It must not have any business logic, database operation codes etc.

In short, the core project should contain:

  • Domain entities
  • Repository interfaces or database operations interfaces on domain entities
  • Domain specific data annotations

The core project can NOT contain:

  • Any external libraries for database operations
  • Business logic
  • Database operations code

While creating the domain entities, we also need to make a decision on the restrictions on the domain entities properties, for example:

  • Whether a particular property is required or not. For instance, for a Product entity, the name of the product should be required property.
  • Whether a value of a particular property is in given range or not. For instance, for a Product entity, the price property should be in given range.
  • Whether the maximum length of a particular property should not be given value. For instance, for a Product entity, the name property value should be less than the maximum length.

here could be many such data annotations on the domain entities properties. There are two ways we can think about these data annotations:

  1. As part of the domain entities
  2. As part of the database operations logic

It is purely up to us how we see data annotations. If we consider them part of database operation then we can apply restrictions using database operation libraries API. We are going to use the Entity Framework for database operations in the Infrastructure project, so we can use Entity Framework Fluent API to annotate data.

If we consider them part of domain, then we can use System.ComponentModel.DataAnnotationslibrary to annotate the data. To use this, right click on the Core project’s Reference folder and click on Add Reference. From the Framework tab, selectSystem.ComponentModel.DataAnnotations and add to the project.

Read full article on the Infragistics blog

Creating Unit Tests for ASP.NET MVC Controllers

In this blog post, we will learn to write unit tests for various MVC controller’s behaviors, such as view’s return types, redirecting to different actions etc. Specifically, we’ll cover writing Unit Tests for:

  1. ViewData of the Controller
  2. TempData of the Controller
  3. ViewBag of the Controller
  4. View of the Controller

Let’s get started!

Creating the MVC Project under Test

Let us go ahead and create a MVC project under Test. To keep things simpler, I have selected ”No Authentication” for the project. In this example we are going to write unit tests for the HomeController. The HomeController contains two action methods:

  1. Index
  2. Details

We are going to write tests for these actions. The HomeController contains code as shown here:

Read full article on the Infragistics Blog

How to work with Enums in ASP.NET MVC

Recently I got a question from one of the readers that how to work with Enums in ASP.NET MVC? Before we move ahead in this post, let me tell you that it is very simple to work with Enums in ASP.NET MVC 5.1 and later. In MVC 5.1, HTML helper class EnumDropDownListFor has been introduced which is used to display the Enum in a dropdown as shown in the image below:

image

To start with let us consider that we have created an Enum TypeOfStudent as shown in the listing below. This Enum holds information about the type of a particular student.


public enum TypeOfStudent
    {
        [Display(Name = "Science Student.")]
        SS,
        [Display(Name = "Arts Student.")]
        AS,
        [Display(Name = "Economics Student.")]
        ES,

    }

We are going to use TypeOfStudent enum in the Student class which is created as shown in the listing below:


  public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public TypeOfStudent StudentType { get; set;}
    }

Right click on the Controller folder and create a controller using the scaffolding. We need to select MVC 5 controller using the Entity Framework as shown in the image below:

image

In the Model class select Student and create a Data context class (perhaps select an existing one) to add a controller.

image

We just added a controller which is using Student class as model and the Student class has Enum TypeOfStudent as a property. Let us go ahead and run the application, we will find Enum property is rendered in the dropdown as shown in the image below:

image

As we see that Enum values has been populated in the StudentType dropdown. In the Create and Edit views of the controller, a control EnumDropDownListFor has been added as shown in the listing below:


  <div class="form-group">;
            @Html.LabelFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            &lt;div class="col-md-10"&gt;
                @Html.EnumDropDownListFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model =&gt; model.StudentType, "", new { @class = "text-danger" })
            </div>;
        </div>;

When we create View using the scaffolding, MVC 5.1 and later use HTML Helper class EnumDropDownListFor to create dropdown from the Enum.

Using RadiButtons for the Enum

In MVC 5.1 onwards we do have support of EnumDropDownListFor which renders Enum values to a drop down. We may have a requirement to render the Enum values to RadioButton. There is no simple way to do it. For this we have to create HTML Helper class. Let us go ahead and create a HTML helper class. To create HTML Helper class

  1. Add a static class to the project
  2. Add HTML Helper method as static method to the class

I have created a folder named Helper and inside that created a class EnumRadioButtonHelper. Inside the static class, we have created static method EnumRadioButton to render Enums in the RadioButtons.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVCEnum.Helper
{
   public static class EnumRadioButtonHelper
    {
        public static MvcHtmlString EnumRadioButton<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            var listOfValues = Enum.GetNames(metaData.ModelType);

            var sb = new StringBuilder();

            if (listOfValues != null)
            {
                sb = sb.AppendFormat("<ul>");

                
                foreach (var name in listOfValues)
                {
                    var label = name;

                    var memInfo = metaData.ModelType.GetMember(name);

                    if (memInfo != null)
                    {
                        var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

                        if (attributes != null && attributes.Length > 0)
                            label = ((DisplayAttribute)attributes[0]).Name;
                    }

                    var id = string.Format(
                        "{0}_{1}_{2}",
                        htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                        metaData.PropertyName,
                        name
                    );

                    var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();

                    sb.AppendFormat("<li>{0}{1}</li>", radio, HttpUtility.HtmlEncode(label));
                }

                sb = sb.AppendFormat("</ul>");
            }

            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

We can use the EnumRadioButton helper method on the view directly. We also need to make sure that, we have added the namespace of the helper class on the view. I have added the namespace as shown in the listing below:

@using MVCEnum.Helper
@model MVCEnum.Models.Student

Once namespace is added, EnumRadioButton can be used to render Enum in RadioButton as shown in the listing below:

  <div class="form-group">
            @Html.LabelFor(model => model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">            
                @Html.EnumRadioButton(m => m.StudentType)
            </div>
        </div>

On running the application, we will find StuentType is rendered in RadioButton also as shown in the image below:

image

We learnt how to work with Enums in MVC 5.1 and later. In MVC 5.1 EnumDropDownListFor has been introduced to render Enums in DropDown. We can also create HTML helper class to render Enums in RadioButtons. I hope you find this post useful. Thanks for reading.

Areas in ASP.NET MVC

Areas are some of the most important components of ASP.NET MVC projects. The main use of Areas are to physically partition web project in separate units.  If you look into an ASP.NET MVC project, logical components like Model, Controller, and the View are kept physically in different folders, and ASP.NET MVC uses naming conventions to create the relationship between these components. Problems start when you have a relatively big application to implement. For instance, if you are implementing an E-Commerce application with multiple business units, such as Checkout, Billing, and Search etc. Each of these units have their own logical components views, controllers, and models. In this scenario, you can use ASP.NET MVC Areas to physically partition the business components in the same project.

In short, an area can be defined as: Smaller functional units in an ASP.NET MVC project with its own set of controllers, views, and models.

image

Read full article on the Infragistics blog

How to use AngularJS in ASP.NET MVC and Entity Framework

Read full article on the Infragistics blog

These days, it seems like everyone is talking about AngularJS and ASP.NET MVC. So in this post we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC by demonstrating how to use AngularJS in an ASP.NET MVC application. Later in the post, we will see how to access data using the Entity Framework database as a first approach, then we’ll explore how to access the data in AngularJS and then pass to the view using the controller. In short, this post will touch upon:

  • adding an AngularJS library in ASP.NET MVC;
  • · reference of AngularJS, bundling and minification;
  • · fetching data using the Entity Framework database;
  • · returning JSON data from an ASP.NET controller;
  • · consuming JSON data in an AngularJS service;
  • · using AngularJS service in AngularJS controller to pass data to the view; and
  • · rendering data on an AngularJS View

To start, let’s create ASP.NET MVC application and right click on the MVC project. From the context menu, click on Manage Nuget Package. Search for the AngularJS package and install into the project.

Read full article on the Infragistics blog

Step by Step implementing Onion architecture in ASP.NET MVC Application

Source Code on the GitHub

Learn Creating N-Tier Applications in C#, Part 1 by Steve Smith here – I learnt lot from this course hence sharing
Recently I gave a talk on Onion Architecture in MVC application to the audience of 300 at the C-Sharpcorner conference 2015. Talk was well received and I had a many request to write a step by step blog post on the same. So here I am writing that. In this blog post is written in simplest words and will help you in implementing onion architecture in ASP.NET MVC application. Even though theme of this post is ASP.NET MVC, you can use the core, infrastructure and the test project with other kind of applications as well like WCF or WPF.

You may want to read: Refactoring the ASP.NET MVC Application to the Onion Architecture

Source Code on the GitHub

What is onion architecture

Onion Architecture is the preferred way of architecting application for better testability, maintainability and dependability on the infrastructures like databases and services. This term was first coined by Jeffery Palermo in his blog back in 2008.

image

Advantages of Onion architecture
  • In the Onion Architecture layers talk to each other using the Interfaces. Any concrete implantation would be provided to application at the run time.
  • Any external dependency like database access and the web service call are part of the external layers
  • UI is part of the external layers
  • Objects representing domain are part of the internal layers or they are the centers
  • External layers can depend on the layers internal to it or central to it
  • Internal layer should not depend on the external layers.
  • Domain object which is at the core or centre can have access to the both the UI and the database layers.
  • All the coupling are towards the centre
  • Codes which may change often should be part of the external layers

Project structure

Let us start with creating the solution structure. We are going to work with the four projects.

  1. Core project (Class library )
  2. Infrastructure project (Class library)
  3. Test project (Unit Test project)
  4. Web project (MVC project)

Core project will contain the domain entities and the repositories interfaces. Infrastructure project will contain the classes (in this case EF data context) which will work with the database. The Test project will have the tests and the MVC project will contain the MVC controllers and the view.

Solution structure should look like as listed in the below image.

image

Core project

The core project is the inner most layer of the architecture. All the external layers like infrastructure, web etc. will use and depend on the core layer. However core project does not depend on any other layers.

Usually the core project should contain,

  • Domain entities
  • Repositories interfaces

It should not have any external dependencies. For example we must not have the following references in the core project,

  • Reference of the ORM like LINQ to SQL or EF
  • Reference of ADO.NET libraries
  • Reference of Entity Framework etc.
Create Entity

Let us go ahead and create BloodDonor entity class.


public class BloodDonor
    {
       public string BloodDonorID { get; set; }
       public string Name { get; set; }

       public DateTime Dob { get; set; }

       public string BloodGroup { get; set; }

       public string City { get; set; }

       public string Country { get; set; }

       public int PinCode { get; set; }

       public string PhoneNumber { get; set; }

       public string Email { get; set; }

       public bool IsActive { get; set; }

       public bool IsPrivate { get; set; }

       public bool IsVerified { get; set; }

    }

We may have a requirement to have some restrictions on the entity properties. For example maximum length, required etc. We do have two choices to achieve this,

  1. Using System.ComponentModel.DataAnnotations
  2. Use Entity Framework fluent API.

Both above approaches have their own advantages. However to keep core project without having any external dependencies like EntityFramework, I prefer to use DataAnnotations. To use DataAnnotations add System.ComponentModel.DataAnnotations reference in the core project. We can modify the entity class as shown in listing below,

using System;
using System.ComponentModel.DataAnnotations;

namespace LifeLine.Core
{
   public class BloodDonor
    {
       [Required]
       public string BloodDonorID { get; set; }
       [Required]
       [MaxLength(50)]
       public string Name { get; set; }
       [Required]
       public string BloodGroup { get; set; }
       [Required]
       public string City { get; set; }

       public string Country { get; set; }
       [Required]
       public int PinCode { get; set; }
       [Required]
       public string PhoneNumber { get; set; }

       public string Email { get; set; }

       public bool IsActive { get; set; }

       public bool IsPrivate { get; set; }

       public bool IsVerified { get; set; }

    }
}

As of now we have created the BloodDonor entity class with the data annotations. Next we need to add the repository interface.

Create Repository interface

We are going to follow the repository pattern. Roughly repository pattern allows us to replace the database access codes (class) without affecting the other layers. In the repository interface we will put definition of all the database operations need to perform.


using System.Collections.Generic;

namespace LifeLine.Core.Interfaces
{
    public interface IBloodDonorRepository
    {
        void Add(BloodDonor b);
        void Edit(BloodDonor b);
        void Remove(string BloodDonorID);
        IEnumerable<BloodDonor> GetBloodDonors();
        BloodDonor FindById(string BloodDonorID);

    }
}

As of now we have created the domain entity and the repository interface. Next let us go ahead and create the infrastructure project.

Infrastructure project

In the infrastructure project we perform operations related to outside the application. For example,

  • Database operation
  • Accessing outside service
  • Accessing File systems

Above operations should be part of the infrastructure project. We are going to use the Entity Framework to perform the database operations. We are working with the Entity Framework code first approach, so we need to perform the following steps,

  1. Create the data context class
  2. Implement the repository class
  3. Create the data base initializer class

Before we go ahead and create the data context class, let us go ahead and add reference of the Entity Framework. To add the reference right click on the infrastructure project and select manage Nuget package. From Nuget package manager select the Entity framework package to install in the project.

DataContext class

Let us create the data context class. In the EF code first approach, we create the data context class which will represent the database. Since we have only one business entity, so we will create one table BloodDonors.


using System.Data.Entity;
using LifeLine.Core;

namespace LifeLine.Infrastructure
{
   public class BloodDonorContext : DbContext
    {
       public BloodDonorContext()
           : base("name=BloodDonorContextConnectionString")
       {
           var a = Database.Connection.ConnectionString;
       }

       public DbSet<BloodDonor> BloodDonors { get; set; }
    }
}

Connection string

Optionally either you can pass the connection string or rely on the Entity Framework to create the database. We will set up the connection string in app.config of the infrastructure project. Let us go ahead and set the connection string as shown in the below listing,


  <connectionStrings>
    <add name="BloodDonorContextConnectionString" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=BloodDonors;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Database initialize class

We want database to initialize with some initial values. It can be done as shown in the below listing,

using System;
using System.Data.Entity;
using LifeLine.Core;

namespace LifeLine.Infrastructure
{
   public class BloodDonorInitalizeDb : DropCreateDatabaseIfModelChanges<BloodDonorContext>
    {

       protected override void Seed(BloodDonorContext context)
       {
           context.BloodDonors.Add(
           new BloodDonor
           {
               Name = "Rahul Kapoor",
               City = "Gurgaon",
               BloodGroup = "A+",
               BloodDonorID = "BD1",
               Country = "India",
               IsActive = true,
               IsPrivate = false,
               IsVerified = true,
               PhoneNumber = "91+7378388383",
               PinCode = 122002,
               Email = "Rahul@abc.com"

           });
           context.BloodDonors.Add(
               new BloodDonor
               {
               Name = "Salman Khan",
               City = "Mumbai",
               BloodGroup = "A-",
               BloodDonorID = "BD2",
               Country = "India",
               IsActive = true,
               IsPrivate = false,
               IsVerified = true,
               PhoneNumber = "91+84848484",
               PinCode = 25678,
               Email = "Salman@abc.com"
               }
       );
            base.Seed(context);
       }
    }
}

We are setting the value that if the model changes recreate the database. We can explore the other options of the entity framework also.

Repository class implementation

Next we need to implement the repository class. Repository class will access the database using the LINQ to Entity. To create the BloodDonorRepository class let us go ahead and create a class which will implement the IBloodDonorRepository interface.


using System.Collections.Generic;
using System.Linq;
using LifeLine.Core;
using LifeLine.Core.Interfaces;

namespace LifeLine.Infrastructure
{
   public class BloodDonorRepository : IBloodDonorRepository
    {
       BloodDonorContext context = new BloodDonorContext();
        public void Add(BloodDonor b)
        {
            context.BloodDonors.Add(b);
            context.SaveChanges();
        }

        public void Edit(BloodDonor b)
        {
            context.Entry(b).State = System.Data.Entity.EntityState.Modified;
        }

        public void Remove(string BloodDonorID)
        {
            BloodDonor b = context.BloodDonors.Find(BloodDonorID);
            context.BloodDonors.Remove(b);
            context.SaveChanges();
        }

        public IEnumerable<BloodDonor> GetBloodDonors()
        {
            return context.BloodDonors;
        }

        public BloodDonor FindById(string BloodDonorID)
        {
            var bloodDonor = (from r in context.BloodDonors where r.BloodDonorID == BloodDonorID select r).FirstOrDefault();
            return bloodDonor;
        }
    }
}

To implement the repository class, we are using the LINQ to Entity for the database operations. For example to add a blood donor,

  1. Create object of context class
  2. Use context.entiy.Add(entity)
  3. Use context.SaveChnages()

As of now we have implemented the infrastructure project. Make sure to build the project to confirm everything is fine.

Directly MVC project or should we write test?

After creation of core project and the infrastructure project, we need to take a decision that whether we want to directly create the MVC project or write the unit test for the repository class. Better approach would be to write the Unit tests for the repository class such that we would be sure that database related code has been implemented correctly.

Test Project

We have created a test project by selection Unit Test project template from the Test project tab. To start writing test, very first in the unit test project we need to add following references

  1. Reference of the core project
  2. Reference of the infrastructure project
  3. Entity framework package
  4. Reference of the System.LINQ

In the test project, I have created a class called BloodDonorRepositoryTest. Inside the unit test class initialize the test as shown in listing below,

 


BloodDonorRepository repo;
        [TestInitialize]
        public void TestSetUp()
        {

            BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();
            System.Data.Entity.Database.SetInitializer(db);
            repo = new BloodDonorRepository();
        }

In the test setup, we are creating instance of BloodDonorInitalizeDb class and then setting up the database with the initial values. Also in the test setup, instance of repository class is created. Next let us create test to validate whether data base is initialized with the right number of data or not.

[TestMethod]
        public void IsRepositoryInitalizeWithValidNumberOfData()
        {
            var result = repo.GetBloodDonors();
            Assert.IsNotNull(result);
            var numberOfRecords = result.ToList().Count;
            Assert.AreEqual(2, numberOfRecords);
        }

In the test above we are calling the GetBloodDonors method of the repository class and then verifying the number of records. In ideal condition above test should be passed. You can verify the test result in Test-Window-Test Explorer

clip_image002

We can right tests for add, edit, and delete also. As of now we have written test to verify that database is getting created along with the initialized data. We can be sure about the implementation of the repository class after passing the test. Now let us go ahead and implement the web project.

Web Project

We are going to create MVC project which will use the core project and the infrastructure project. Add following reference in the MVC project

  1. Reference of infrastructure project
  2. Reference of core project
  3. Entity framework package

After adding all the references build the web project. If everything is find we should get successful build. Next let us write click on the Controller folder and add a new controller. Select create controller with Entity Framework with view option. Give name of the controller as BloodDonorsController.

Also we need to select the following options,

  1. BloodDonor class from the core project as the Model class
  2. BloodDonorContext class as the data context class from the Infrastructure project

image

We have created the controller along with the view using the scaffolding. At this point if we notice the web project, we will find BloodDonors controller and a BloodControllers subfolder in the view folder.

image

 

As of now we have created the controller using the model and data context class. Next we need to create instance of BloodDonorInitalizeDb class and set the database. We need to write this code inside the global.asax .


BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();
            System.Data.Entity.Database.SetInitializer(db);

Last we need to copy the connection string from the app.config of infrastructure project to web.config of the web project. So let us go ahead copy the connection string in the web.config


<connectionStrings>
    <add name="BloodDonorContextConnectionString" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=BloodDonors;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>

At this point if we run the application we should able to perform the CRUD operations.

image

 

Dependency Injection using Unity

We have a running application but there is a problem. On noticing the controller class closely, we will find that object of the data context class is directly created inside the controller. We used scaffolding to create the controller using the entity framework and it causes creation of data context object inside the controller. Right now the controller and the data context class are tightly coupled to each other and if we change database access program then controller will be affected also.

We should not have the BloodDonorContext object inside the controller.

clip_image002[6]

We have already created the repository class inside the infrastructure project. We should use the repository class inside the controller class. We have two options to use the repository class

  1. Directly create the object of repository class in the controller class
  2. Use dependency injection to resolve repository interface to the concrete repository class object at the run time using the unity container.

We are going to use the second approach. To use the unity container add Unity.Mvc5 package in the web project using the manage Nuget package.

image

After installing the unity package, we need to register the type. To register the type open the UnityConfig class inside the App_Start folder. As highlighted in in the below image add the register.

clip_image002[8]

 

And inside the global.asax register all the components of the UnityConfig as shown in below image.

clip_image002[10]

So far we have added the unity container reference and register the type. Now let us go ahead and refactor the controller class to use the repository class. To start with

  1. Create a global variable of the type IBloodDonorRepository
  2. Create controller class constructor with a parameter as shown in below image

image

Once this is done we need to refactor the controller class to use functions of repository class instead of the data context class. For example Index method can be refactored as shown below,

image

After refactoring the BloodDonorController class will look like as shown in below listing,

 


using System.Linq;
using System.Net;
using System.Web.Mvc;
using LifeLine.Core;
using LifeLine.Core.Interfaces;
namespace LifeLine.Web.Controllers
{
    public class BloodDonorsController : Controller
    {
        IBloodDonorRepository db; 

        public BloodDonorsController(IBloodDonorRepository db)
        {
            this.db = db;
        }

        // GET: BloodDonors
        public ActionResult Index()
        {
            return View(db.GetBloodDonors().ToList());
        }

        // GET: BloodDonors/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

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

        // POST: BloodDonors/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 = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)
        {
            if (ModelState.IsValid)
            {
                db.Add(bloodDonor);
                return RedirectToAction("Index");
            }

            return View(bloodDonor);
        }

        // GET: BloodDonors/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

        // POST: BloodDonors/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 = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)
        {
            if (ModelState.IsValid)
            {
                db.Edit(bloodDonor);
                return RedirectToAction("Index");
            }
            return View(bloodDonor);
        }

        // GET: BloodDonors/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

        // POST: BloodDonors/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            BloodDonor bloodDonor = db.FindById(id);
            db.Remove(bloodDonor.BloodDonorID);
            return RedirectToAction("Index");
        }

    }
}

 

Conclusion

This is it. These are the steps we need to follow to create a MVC application following to onion architecture.

Source Code on the GitHub

Have something to add? Please add in the comment section.

How to create a Container in Azure Storage from MVC application

I am working on a MVC application in which I need to work with Microsoft Azure storage .I had a requirement to create An Azure storage container from the MVC application. In this post I will share my learning that how I created a container programmatically.

I created the view as shown in below image. User has to enter the azure storage account name, azure storage key and the name of the container to be created.

image

Above View is MVC razor view, and it is created using the cshtml as shown below:

 


@{
    ViewBag.Title = "BLOB Manager";
}
<div class="jumbotron">
    <div class="row">
        <div class="col-md-8">
            <section id="loginForm">
                @using (Html.BeginForm("AzureInfo", "Manage", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    <h2> Manage BLOB Container</h2>
                    <hr />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountName", "", new { @class = "form-control", @placeholder = "Account Name" })
                            @Html.ValidationMessage("AccountName", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountKey", "", new { @class = "form-control", @placeholder = "Account Key" })
                            @Html.ValidationMessage("AccountKey", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("ContainerName", "", new { @class = "form-control", @placeholder = "Container Name" })
                            @Html.ValidationMessage("containername", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group input-group input-group-lg">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create Container" class="btn btn-lg btn-success" />
                        </div>
                    </div>

                }
            </section>
        </div>
    </div>
</div>

Above I am creating,

  • Three text boxes with the placeholder and the class set to bootstrap form-control
  • A submit button with the class set to bootstrap btn-lg and btn-success
  • All the controls are inside the form.
  • On form post operation, AzureInfo action of the Manage controller will be called.

Once the View is ready, let us go ahead and create an azure utility class. In this class we will put all the operations related to the azure storage. But before that you need to add Azure storage library to the project. Either you can use NuGet package manager or console to add the library. I am using console to install Azure storage library. I have taken the 4.3 version because at the time of writing this post, this was the latest stable version available.

image

Once package is successfully installed, add following namespaces.

 


using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;

To create the container in the Azure storage, I have created a function CreateContainer. This function takes three input parameters, account name, account key and the container name.

 


public static class AzureUtility
    {
        public static string  CreateContainer(string AccountName, string AccountKey, string ContainerName)
        {

            string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(UserConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
            if (container.CreateIfNotExists())
            {
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                return container.Name;
            }
            else
            {
                return string.Empty;
            }
        }
    }

Now let us examine the above code line by line.

  • In first line I created the connection string for the azure storage. It takes two parameters, account name and the account key. These values are passed as input parameter to the function. I am using these two parameter to create connection string.
  • Using CloudStorageAccount to parse the connection string from the constructed string.
  • Creating the CloudBlobClient
  • Getting the container reference of the BLOB.
  • If container reference does not exist, creating new container.
  • On successful creation of the container function returns name of the container else empty string.

 


[HttpPost]
        public ActionResult AzureInfo(string AccountName, string AccountKey, string ContainerName)
        {

           var result= AzureUtility.CreateContainer(AccountName, AccountKey, ContainerName);

           if (result != string.Empty)
             {

                 return RedirectToAction("Index", "Home");
             }
             else
             {
                 return RedirectToAction("Index");
             }
        }

In the action we are using the utility class to create the container. In this way an azure container can be created from the MVC application.

I hope it is useful. Thanks for reading. Happy Coding.

Convert User to ApplicationUser in ASP.Net MVC

In the last post I talked about How to get current user in ASP.Net MVC 5 . Type of the current user is IPrincipal which is shown as follows:

image

You may come across requirement to work with ApplicationUser which is created as follows:

image

You can covert returned User to ApplicationUser as follows:


ApplicationDbContext db = new ApplicationDbContext();
            ApplicationUser appUser = db.Users.FirstOrDefault(x => x.Id == userId);
            return appUser ;

To convert create instance of the ApplicationDBContext and then fetch user using LINQ to Entity. Returned user from context is of type ApplicationUser.

Hope it helps. Happy coding.

Attribute Routing in ASP.NET MVC 5

ASP.NET MVC 5 introduced Attribute Routing. It allows you to apply a route directly on the controller class. Before we use the Attribute Routing, let’s relook how the convention based routing works.

We create a route as follows:

clip_image002

Index action of Home controller can be accessed on two different URLs. Either using the base URL (default value is set) or using baseurl/Home/Index as shown below:

clip_image004

In convention based routing action is accessed using the baseurl/controllername/actionname. Using the Attribute Routing this behaviour can be overridden. To use attribute routing you need to enable it in RouteConfig. To enable it, in the RoutConfig.cs call routes.MapMvcRouteAttribute() method.

clip_image006

Once it is enabled you can apply attribute routing on action using Route attribute and passing a value in this.

clip_image008

Now Index action can be access on the URL: baseurl/Test

clip_image010

You can also pass parameters in the attribute route. Parameters name and variables in route value must be the same.

clip_image012

Index action can be access with parameter values as shown below- I am passing 40 as value of age and steve as value of name.

clip_image014

You may want to use the attribute routing in your project as per the requirement. Keep in mind that attribute routing and the convention based routing can be used together.

Happy coding.

Work with ASP.NET MVC 5 Areas from different projects

Read full article on Falafel blog

While working on an ASP.NET MVC 5 application, I came across a requirement to use an Area from one project in another project. For example: I have a project A and a project B. I need to use an Area which is part of project B inside of project A. In this post I will discuss how this can be achieved.

To start with, let us say I have an MVC project AreaDemo with the structure as follows:

clip_image002

Read full article on Falafel blog