Seed the database with initial Users in MVC 5

 

Read full article on Falafel blog

In MVC 5 applications you may want to seed the database with initial users for various reasons. You may want default users and roles added as part of the application. In this post, we will take a look at how to  seed the database with default users.
The MVC 5 application uses ASP.Net Identity 2.0 to manage users, roles and identities. ASP.Net Identity 2.0 uses the Entity framework code first approach to create a database. To seed the database, first you need to enable migration on the database. To enable migration, in the package manager console run the command enable-migrations as shown below:

After successfully enabling migration you should find a Migrations folder in the solution explorer.

 

Read full article on Falafel blog

Custom Action Filter in ASP.NET MVC 5

Read full article on Falafel blog here

ASP.NET MVC 5 provides five different kinds of Filters. They are as follows:

  1. Authentication [Introduced in MVC5]
  2. Authorization
  3. Action
  4. Result
  5. Exception

Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied.

  • Authentication filter runs before any other filter or action method
  • Authorization filter runs after Authentication filter and before any other filter or action method
  • Action filter runs before and after any action method
  • Result filter runs before and after execution of any action result
  • Exception filter runs only if action methods, filters or action results throw an exception

Read full article on Falafel blog here

What is Azure DocumentDB

Read full article on Falafel blog here

Recently I attended Cloud Camp by Microsoft India in Delhi. I had good time learning at the event. Besides other Microsoft Azure services like Azure Websites, Azure Mobile Services and Azure DocumentDB impressed me lot. In this post, I am sharing first level learning on Azure DocumentDB.

Azure DocumentDB is a NoSQL document database service offering on cloud from Microsoft. It allows us to work with schema free JSON documents using JavaScript and the HTTP protocol. It is a fully managed JSON document database service.

Some of the important points about the DocumentDB is as follows:

  • It is a schema free database
  • It has support of rich query and transaction processing
  • It uses JavaScript for the query
  • It works with JSON based data model
  • It works on HTTP protocol

Read full article on Falafel blog here

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.

How to get current user in ASP.Net MVC 5

There are two simple ways to get current user in MVC 5. If you are inside the controller class current user can be fetched as follows,


string userId = User.Identity.GetUserId();

Do not forget to add namespace,

 


using Microsoft.AspNet.Identity;

Other scenario could be that you are not inside the controller class and want to fetch the user information. You can fetch that using HttpContext class.

HttpContext.Current.User.Identity.GetUserId();

I hope it helps. Happy Coding.

RedirectToAction or View as ActionResult in ASP .Net MVC5 ?

We have often seen action returns a View method. Optionally we can also pass the view name and the other parameters in the View method. Most of the time we return a view as ActionResult to navigate.



public ActionResult About()
        {
                    
            ViewBag.Message = "Your application description page.";
            return View();
        }

Now I have a requirement to navigate to Login view or return Login view on the basis of some authorization check. There are various ways you can do this however the approach I selected required me to override the OnActionExecuting() method in the controller class.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = View("Account/Login");
            }
            base.OnActionExecuting(filterContext);
        }

Type of the filter context result is ActionResult, so its value can be set to a View. To navigate I set the value of the filterContext.Result as View with view name as parameter.

Simple ? but it did not work, and I got the exception as follows:

imageKeep in mind that I am trying to navigate to the Login view which is part of the Account controller from Home controller. However If you are navigating to view from same controller, you won’t get the above exception. Essentially we are trying cross controller view navigation. To get rid of above exception, I had to use RedirectToAction().

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var result = _authorizeService.CanSeeTheAboutView(userId);   
            if(!result)
            {
                filterContext.Result = RedirectToAction("Login", "Account");
            }
            base.OnActionExecuting(filterContext);
        }


Another difference is RedirectToRoute make another request and View returns HTML to render and it does not make new request. Conclusion is use RedirectToAction if you are doing cross controller navigation. Any other thought?

Happy coding.

Decorator Pattern in C#

Read full article on Falafel blog

Decorator pattern attach additional functionalities or responsibilities to an existing object at the runtime”. It adds new behaviour to an individual object without affecting other objects of the same class. New behaviour or functionalities can be either added dynamically at the run time or statically.

image

The decorator pattern:

  • · Adds new functionality or behaviour
  • · Either at run time or statically
  • · Without affecting other objects of the class
  • Why do we need this pattern?

    To understand, let us consider a Student object with the basic responsibility to handle and print information like name, age, and grade etc.

    Now you have a requirement to add functionality to maintain lab reports for Science students. How will you do this? Maybe extend the Student class to create a ScienceStudent subclass for this responsibility. Good enough.

Read full article on Falafel blog

Fetching Image from database in ASP.NET MVC 5 application

In this post we will learn to fetch image from a database. I have taken Northwind database as an example. Employee table of the Notrhwind database stores a Photo using the Image type. We will fetch data from the Photo column (type: Image) in the MVC application.

image

Let us start with the Controller. In the Index action all the Employees are fetched using the EmployeeRepository.


public ActionResult Index()
        {
            return View(_employeeRepository.List);
        }

Note: I am using repository pattern and the Entity framework. However you can fetch data directly using the Entity framework without the repository pattern.

In the View, you should convert fetched photo in a byte array as shown below. For normal photo you don’t need to subtract 78 from the length. However OLE photos it is required.


<td>
            @{ byte[] photo = item.Photo;
             string imageSrc = null;
             if (photo != null)
             {
                 MemoryStream ms = new MemoryStream();
                 ms.Write(photo, 78, photo.Length - 78);
                 string imageBase64 = Convert.ToBase64String(ms.ToArray());
                 imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
             }
            }           

            <img src="@imageSrc" alt="Image" />
        </td>

In above code snippet manually we are creating Memory Stream and then converting that to byte array. However in MVC library is available to do this task for you.

image

You can use Convert.ToBase64String() method to convert the fetched image into an encode string. This function is overloaded with four different set of parameters. I am passing byte array, offset value, length and format option to create the encoded string from the image byte array. So this approach can be replaced as follows:


  <td>

            <img src="data:image/png;base64,@Convert.ToBase64String(item.Photo,78,item.Photo.Length-78 ,
            Base64FormattingOptions.None)"
                 alt="Image" /> 

        </td>

You should able to view fetched images in the application. 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.