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

How to Create a Custom Action Filter in ASP.NET MVC

Read full article on the Infragistics blog

In ASP.NET MVC, Filters are used to inject logic at different levels of request processing and allow us to share logics across Controllers. For example, let’s say we want to run a security logic or a logging logic across the controller. To do so, we’ll write a filter containing those logics and enable them across all controllers. When we enable a filter across all controllers or actions, the filter enables the upcoming HTTP request.

Let us consider a scenario of Logging: for every incoming request, we need to log some data to the files on the basis of some logic. If we don’t create this logic inside a custom filter, then we will have to write logic for each controller’s action. This mechanism will lead to two problems:

  1. duplication of code; and
  2. violation of the Single Responsibility Principles; actions will now perform additional tasks of logging.

We can mitigate the problems above by putting the logging logics inside a custom action filter and applying the filter at all the controllers’ level.

Have you ever come across source code as shown in the image below? [Authorize] is an Authorization filter, and it gets executed before any HTPP request or Action method execution.  The Authorize filter is part of MVC, but if needed, we can create a custom filter too.

Read full article on the Infragistics blog

Creating a photo album for ASP.NET MVC 5 Users using Azure BLOB storage

In this blog post, we will integrate ASP.NET MVC with Azure BLOB Storage by saving an image for an ASP.NET Identity 2.0 user in Azure BLOB Storage. We’re going to cover a lot of ground in this post, including:

  • Using ASP.NET Identity 2.0 user as reference in other table.
  • Creating a one to many relationship with ASP.NET Identity 2.0 user table
  • Connecting an ASP.NET MVC application to Azure Storage
  • Creating or Uploading a BLOB
  • Deleting a BLOB
  • Downloading a BLOB
  • Uploading a file from MVC form to a Azure BLOB

The final output of the blog post we plan on creating in this post will look more or less like the image below. As you can see, a user can upload a photo to her album, delete a photo, and of course, view photos too.

image

Architecture of the Application

The High-level architecture of the application can be drawn as shown in the image below:

image

Creating tables to save images

When we create an ASP.NET MVC application using the given MVC template in Visual Studio, by default, a basic authentication gets created using the ASP.NET Identity 2.0. In a default MVC project, a template for the authentication and authorization purpose ASP.NET Identity 2.0 creates the tables as shown in the image below:

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

What are ViewData, ViewBag, and TempData in ASP.NET MVC?

I have often seen entry level developers struggle with the differences between and usage of ViewData, ViewBag and TempData in ASP.NET MVC. And while there are many articles and blog posts on this topic out there, I’ll try to explain it simply.

To start with, ViewData, ViewBag, and TempData all three are objects in ASP.NET MVC that are used to carry or pass data in different scenario. You may have a requirement to pass data in the following cases:

  • Pass data from controller to view;
  • Pass data from one controller to another controller;
  • Pass data from one action to another action;
  • Pass data between subsequent HTTP requests

At a higher level, we can depict the use of ViewData, ViewBag, and TempData as shown in the image below:

image

Passing Data from Controller to View

Let us consider a scenario where you’re passing data from controller to view. Usually we pass complex data to the view using the model. Here let’s say we have a strongly typed View which is using the data model List as shown in the listing below:

Read the full article on the Infragistics blog

How to Enable CORS in the ASP.NET Web API

Have you ever come across the following error:

Cross-origin Request Blocked. The same origin policy disallows reading the resource”.

Us to! It turns out, we get this error due to lack of CORS support while sharing resources. When we try to consume the Web API from origin A in a web application residing in origin B, we get the above error. To solve this error, we need to have a good understanding of CORS.

Although the purpose of this article is to learn the practical implementation of enabling CORS in the ASP.NET Web API, we will give a fair amount of weight to the theoretical concept also. CORS stands for Cross-Origin Resource-Sharing. For various security reasons user agents cannot share resources if they are not from the same origin. Various examples of user agents are browsers, HTML documents, scripts, and XMLHttpRequest.

Let us try to understand the concepts of Cross-Origin and Same-Origin. The concept of Origin was described by RF 6454. Two URLs would be called of the same origin, if they have:

  1. Scheme (http)
  2. Host (server)
  3. Port (8888)

The Origin consists of the Scheme, Host, and the Port number.

image

If two resources have the same combination of scheme, host, and port then they are considered of the same origin, else of the cross origin. Let us consider the following two URI

http://abc.com:80 and http://xyz.com:8080 are not of the same origin since their host and port are not the same. For the security reason resource sharing between these two URL may be restricted. Let us try to understand CORS with the example of XMLHttpRequest. We use the XMLHttpRequest to perform the HTTP operation on the server from the HTML document. There are two URLs used in the XMLHttpRequest:

  1. Requested URL or URL of the server
  2. URL of the document which initiated the request

If both URLs have the same scheme, host, and port then XMLHttpRequest object will perform the operation else it will block the HTTP operation for security reasons.

Both the server and the browser must have the support of the CORS. By default all recent browsers have CORS support, but as an API developer we need to enable support of CORS in the Web API.

CORS in ASP.NET Web API

Here we have created a very simple ASP.NET Web API which returns an array of classes as shown in the image below:

As you can see that Web API is running on port 8458. Next we are trying to get the data in a JavaScript application which is running on the URI with the port 5901:

Read the full article on the Infragistics blog

How to work with the Ignite UI Chart in an AngularJS application

In this post we will learn how to work with the Ignite UI chart in an AngularJS application. Although I will use the ASP.NET Web API to pull data from the database, you can use REST service or a Web API created on any stack with the Ignite UI charts in your AngularJS application. This article is divided in two sections:

  1. Section 1 : creating ASP.NET Web API using Code First approach
  2. Section 2 : using Ignite UI in AngularJS application

If you already have or know how to create the Web API REST Service (Note: from here on out in this post, we’ll use the term “Web API” to refer both to REST Service and Web API), you can jump to section 2 of this article. On the other hand if you need help in how to create ASP.NET Web API start from the section 1. Here’s a high level flow of diagram of an application::

image

Read full article on the Infragistics blog

Creating an ASP.NET Web API using the Entity Framework Code First approach and the Repository pattern

In this article, we will learn how to create an ASP.NET Web API using the Repository pattern and the Entity Framework code first approach. Essentially you’ll learn how to:

  1. Create a core project which will contain entity and the repository interface;
  2. Create an Infrastructure project which will contain database operations code using the Entity Framework code first approach;
  3. Create a Web API to perform CRUD operations on the entity;
  4. Consume the Web API in a jQuery application and render the data in the Ignite UI Chart.

What is a Repository pattern?

Let us first understand why we need a Repository pattern. If you do not follow a Repository pattern and directly use the data then the following problems may arise-

  • Duplicate code
  • Difficulty implementing any data related logic or policies such that caching
  • Difficulty in unit testing the business logic without having the data access layer
  • Tightly coupled business logic and database access logic

By implementing a repository pattern we can avoid the above problems and get the following advantages:

Business logic can be unit tested without data access logic

  • Database access code can be reused
  • Database access code is centrally managed so easy to implement any database access policies such that caching
  • Easy to implement domain logics
  • Domain entities or business entities are strongly typed with the annotations.

Now that we’ve listed how great they are, let’s go ahead and start implanting a repository pattern in the ASP.NET Web API.

Create the Core project

In the core project you should keep the entities and the repository interfaces. In this example we are going to work with the City entity. So let us create a class City as shown in the listing below:

Read the full article on the Infragistics blog