A day with .Net

My day to day experince in .net

Archive for June, 2013

Custom Form Authentication in MVC 4 with Custom Authorize Attribute and Session Variable.

Posted by vivekcek on June 29, 2013

Good afternoon dears,

Today i am going to write about how you can implement a custom authentication in MVC.

1. Create an Empty MVC 4 project. Why we use Empty Project Template? because we don’t want to add default LoginControllers in MVC.

2. Create a new model class ‘User’. Place the class in Models folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CustomAuthetication.Models
{
    public class User
    {
        public int UserId { get; set; }

        [Required]
        public string UserName { get; set; }

        [Required]
        public string Password { get; set; }

        public bool RememberMe { get; set; }
    }
}

3. Create a class named CustomAuthorize and, place it in solution with out any namespace.

Our custom authorize attribute not only check the form authentication cookie but also check a Session variable named ‘User’.
We save an instance of our User class in this session variable on successful login.So if this session variable is null, that means session has expired

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CustomAuthetication
{
    public class CustomAuthorize : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authroized = base.AuthorizeCore(httpContext);
            if (!authroized)
            {
                // the user is not authenticated or the forms authentication
                // cookie has expired
                return false;
            }

            // Now check the session:
            var myvar = httpContext.Session["User"];
            if (myvar == null)
            {
                // the session has expired
                return false;
            }

            return true;
        }
    }

}

4. Create a Controller named HomeController and decorate it’s actions with [CustomAuthorize]. Also add a view for the Index action.This home page is available only for authorized users.

public class HomeController : Controller
    {
        //
        // GET: /Home/
        [CustomAuthorize]
        public ActionResult Index()
        {
            return View();
        }

    }

5. Now create a controller named LoginController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomAuthetication.Models;
using System.Web.Security;

namespace CustomAuthetication.Controllers
{
    public class LoginController : Controller
    {
        static List<User> Users = null;

        public LoginController()
        {
            Users = new List<User> { new User{ UserId=1,UserName="vivek",Password="vivek"},
            new User{ UserId=1,UserName="chanthu",Password="chanthu"},
            new User{ UserId=1,UserName="ramu",Password="ramu"},
            };
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(User tempUser, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = Users.FirstOrDefault(x => x.UserName == tempUser.UserName & x.Password == tempUser.Password);
                if (user != null)
                {
                    Session["User"] = user;
                    FormsAuthentication.SetAuthCookie(user.UserName, tempUser.RememberMe);
                    return Redirect(ReturnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Log In Failed");
                }
            }
            else
            {
                ModelState.AddModelError("", "Log In Failed");
            }

            return View();
        }

        public ActionResult Logout()
        {
            Session["User"] = null;
            FormsAuthentication.SignOut();
            return View();
        }

    }
}

6. Add View for Login action in LoginController.

@model CustomAuthetication.Models.User
@{
    ViewBag.Title = "Login";
    
}
@using (Html.BeginForm(new { ReturnUrl = Request.QueryString["ReturnUrl"] }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
   
    <div class="Container">
        <div class="login">
            <h1>
                Log In</h1>
            <p>
                @Html.TextBoxFor(m =>m.UserName , new { placeholder = "User Name" })
                @Html.ValidationMessageFor(m => m.UserName)
            </p>
            <p>
                @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                @Html.ValidationMessageFor(m => m.Password)
            </p>
            <p class="rememeber_me">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </p>
            <p class="submit">
            <input type="submit" value="Log in" />
            </p>
        </div>
    </div>
}

7. Now in web config enable form authentication.

<authentication mode="Forms">
      <forms loginUrl="~/Login/Login"></forms>
    </authentication>

8. Solution Structure.

sol

Advertisements

Posted in MVC | 11 Comments »

Value cannot be null.Parameter name: key Exception in StructureMap/Castle Windsor.

Posted by vivekcek on June 11, 2013

If you came across such an error from the below code base, when using structureMap.

 protected override IController GetControllerInstance(System.Web.Routing.RequestContext 

requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as IController;
        }

add the following code in your Global.asax

routes.IgnoreRoute("favicon.ico");

You can analyse the error using ELMAH and see that, the request for favicon.ico cause the

exception.

Posted in MVC | Leave a Comment »

Dependency Injection with Unity and StructureMap in MVC 4

Posted by vivekcek on June 10, 2013

Initial Solution.

1.) Create an MVC 4 Web project.

2.) In the Model folder add a Product class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnityDI.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }
}

3. Create a folder named ‘Repository’ then add an interface ‘IProductRepository’ and its implementation ‘ProductRepository’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityDI.Models;

namespace UnityDI.Repository
{
    public interface IProductRepository
    {
        IList<Product> GetAll();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnityDI.Repository
{
    public class ProductRepository : IProductRepository
    {
        public IList<Models.Product> GetAll()
        {
            throw new NotImplementedException();
        }
    }
}

4. Now create a HomeController as Given below, also add an index view.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UnityDI.Repository;

namespace UnityDI.Controllers
{
    public class HomeController : Controller
    {
        private IProductRepository pdt = null;
        public HomeController(IProductRepository _pdt)
        {
            pdt = _pdt;
        }

        public ActionResult Index()
        {
            return View();
        }

    }
}

5. If you run now you get a an error says that ‘No parametrized constructor for controller’.

How to Configure Unity

1. Go to Nuget and add Unity.MVC4. Which will add the dependency for Unity (for VS2010 WITH .NET 4.0). If you are working with .NET 4.5 you can install Unity 3.0.

unity1

2. On sucessful installation A BootStrapper.cs file will be added to your solution.Change that file by adding.’ container.RegisterType();‘ in BuildUnityContainer() method. The full code is given below.

using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc4;
using UnityDI.Repository;

namespace UnityDI
{
  public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      container.RegisterType<IProductRepository, ProductRepository>();
      RegisterTypes(container);

      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
    
    }
  }
}

3. Now in global.asax under Application_Start()add this code

Bootstrapper.Initialise();

Configure StructureMap.

1. Install Nuget Packge structuremap not StructureMap.Mvc.

2. Add a BootStrapper class as given below. You need ‘StructureMap’ and StructureMap.Configuration.DSL name spaces.

 public class BootStrapper
    {
        public static void ConfigureDependencies()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<ControllerRegistry>());
        }
        public class ControllerRegistry : Registry
        {
            public ControllerRegistry()
            {
                For<IIProductRepository>().Use<ProductRepository>();
            }
        }
    }

3. Create a custom controller factory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StructureMap;
namespace BlogEngine.Web.Infrastructure
{
    public class ProductEngineControllerFactory:DefaultControllerFactory
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as IController;
        }
    }
}

4. Now add the following code under Application_Start() in Global.asax

 ControllerBuilder.Current.SetControllerFactory(new BlogEngineControllerFactory());
            BootStrapper.ConfigureDependencies();

Posted in MVC | Leave a Comment »

Design an MVC application Using Enity Framework Repository Pattern, Unit Of Work Pattern and Dependency Injection

Posted by vivekcek on June 10, 2013

In this post, I am going to present how to design an MVC application Using Enity Framework Repository Pattern, Unit Of Work Pattern and Dependency Injection.

I hope the reader is aware of the basics of MVC, Entity Framework, Repository Pattern, Unit Of Work Pattern and Dependency Injection. Because in this post, i am only concentrating on practical implementation.

What is Entity Framework?

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects.It eliminates the need for most of the data-access code that developers usually need to write.

The Repository and Unit of Work Patterns?

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store.

Creating a repository class for each entity type could result in a lot of redundant code, and it could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail. One way to minimize redundant code is to use a generic repository, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.

The unit of work class coordinates the work of multiple repositories by creating a single database context class shared by all of them.

2

Why Need to Inject Controller Dependency?

In real life application development, you will see almost all ASP.NET MVC applications are needed to inject its dependent component. You can create component directly inside the controller instead of inject them. In that case the controller will be strongly coupled on those components. If any component’s implementation is changed or new version of that component is released then you must change controller class itself.

End Of Theory

The example i am using is a small Blog Engine concept, Which include 3 domain objects ‘Blog’, ‘Post’ and ‘Comment’.

Look at the solution structure. Please note the Class library names.

1

1. Create 3 domain classes ‘Blog’, ‘Post’, ‘Comment’ in ‘BlogEngine.Model’ Library. Don’t forgot to install Entity Framework Nuget Package. Also do look at the namespaces.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
namespace BlogEngine.Model
{
    public class Blog
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int BlogId { set; get; }

        [Required,StringLength(500)]
        public string BlogName { set; get; }

        public virtual ICollection<Post> Posts { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace BlogEngine.Model
{
    public class Post
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int PostId { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Content { get; set; }

       
        public int BlogId { get; set; }

        [ForeignKey("BlogId")]
        public Blog Blog { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace BlogEngine.Model
{
    public class Comment
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CommentId { get; set; }

        [Required]
        public string Content { get; set; }
    }
}

2. Create a Generic Repository Interface ‘IRepository’ in ‘BlogEngine.Data.Contract’ Library.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace BlogEngine.Data.Contract
{
    public interface IRepository<T> where T : class
    {
        IQueryable<T> GetAll();
        IQueryable<T> Find(Expression<Func<T, bool>> predicate);
        T GetById(int id);
        void Remove(T entity);
        void Add(T newEntity);
    }
}

3. Implement this ‘IRepository’ interface in ‘BlogEngine.Data’ Library as ‘BlogEngineRepository’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlogEngine.Data.Contract;
using System.Data.Entity;

namespace BlogEngine.Data
{
    public class BlogEngineRepository<T> : IRepository<T> where T : class
    {
        protected DbContext DbContext { get; set; }
        protected DbSet<T> DbSet { get; set; }

        public BlogEngineRepository(DbContext dbContext)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException("dbContext");
            }
            else
            {
                DbContext = dbContext;
                DbSet = DbContext.Set<T>();
            }
        }

        public IQueryable<T> GetAll()
        {
            return DbSet;
        }

        public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return DbSet.Where(predicate);
        }

        public T GetById(int id)
        {
            return DbSet.Find(id);
        }

        public void Remove(T entity)
        {
            DbSet.Remove(entity);
        }

        public void Add(T newEntity)
        {
            DbSet.Add(newEntity);
        }
    }
}

4. Create a DbContext class named ‘BlogEngineDbContext’ in ‘BlogEngine.Data’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using BlogEngine.Model;

namespace BlogEngine.Data
{
    public class BlogEngineDbContext:DbContext
    {

        public BlogEngineDbContext()
            : base("name=BlogEngineDbContext")
        {

        }
        public DbSet<Blog> Blogs { get; set; }
    }
}

5. Create a Unit Of Work Interface named ‘IBlogEngineUnitOfWork’ under ‘BlogEngine.Data.Contract’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlogEngine.Model;

namespace BlogEngine.Data.Contract
{
    public interface IBlogEngineUnitOfWork
    {
        void Commit();
        IRepository<Blog> Blogs { get; }
    }
}

6. Implement ‘IBlogEngineUnitOfWork’ in ‘BlogEngine.Data’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlogEngine.Data.Contract;
using BlogEngine.Model;

namespace BlogEngine.Data
{
    public class BlogEngineUnitOfWork : IBlogEngineUnitOfWork, IDisposable
    {
        private BlogEngineDbContext DbContext = null;

        public BlogEngineUnitOfWork()
        {
            DbContext = new BlogEngineDbContext();
        }
        
        public void Commit()
        {
            DbContext.SaveChanges();
        }

        public IRepository<Model.Blog> Blogs
        {
            get { return new BlogEngineRepository<Blog>(DbContext); }
        }

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

7. Now in our MVC 4 Web Project ‘BlogEngine.Web’ add a Nuget Package named ‘StructureMap’

3

8. Now in Web project, create a folder named Infrastructure and add 2 classes ‘BlogEngineControllerFactory’ and ‘BootStrapper’

4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StructureMap;
namespace BlogEngine.Web.Infrastructure
{
    public class BlogEngineControllerFactory:DefaultControllerFactory
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as IController;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMap;
using BlogEngine.Data.Contract;
using BlogEngine.Data;
using StructureMap.Configuration.DSL;

namespace BlogEngine.Web.Infrastructure
{
    public class BootStrapper
    {
        public static void ConfigureDependencies()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<ControllerRegistry>());
        }
        public class ControllerRegistry : Registry
        {
            public ControllerRegistry()
            {
                For<IBlogEngineUnitOfWork>().Use<BlogEngineUnitOfWork>();
            }
        }
    }
}

9. Now in Global.asax under Application_Start() add the below code.

ControllerBuilder.Current.SetControllerFactory(new BlogEngineControllerFactory());
BootStrapper.ConfigureDependencies();

10. Now add a HomeController and View. The controller code is given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogEngine.Data.Contract;
using BlogEngine.Model;

namespace BlogEngine.UI.Web.Controllers
{
    public class HomeController : Controller
    {
        private IBlogEngineUnitOfWork UoW = null;

        public HomeController(IBlogEngineUnitOfWork _UoW)
        {
            UoW = _UoW;
        }
        
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Blog blog)
        {
            UoW.Blogs.Add(blog);
            UoW.Commit();
            return RedirectToAction("Index");    
        }

        public ActionResult List()
        {
            return View(UoW.Blogs.GetAll());
        }

    }
}

11. A complete Solution Structure Is Given below.

5

Posted in Entity Framework, MVC | 1 Comment »