Tuesday 10 May 2016

Remove Assigned Users from Role in Asp.Net MVC


Before proceeding to this tutorial please go to  Assigned Role to user in Asp.Net MVC
In previous tutorial we learned how to assign role to user , here we will learn how to remove Role from assigned user.
For this purpose we need to add a action method in account controller class. In previous tutorial we created a model class name is “AllroleWithAllUser. same class we will use here to pass this class in controller.
Following code is for “RemoveRoleForUser” in controller class.
  [HttpGet]
        public ActionResult RemoveRoleAddedToUser()
        {
            AssignRole objvm = new AssignRole();
            objvm.UserRolesList = GetAll_UserRoles();
            objvm.Userlist = GetAll_Users();
            return View(objvm);
        }

After creating action method for [HttpGet], now we need to add another action method for the [httpPost] .  So the following is code for the “RemoveRoleForUser” action method for[httpPost] method.
      [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RemoveRoleAddedToUser(AssignRole _assignRole)
        {
            if (_assignRole.UserRoleName == "0")
            {
                ModelState.AddModelError("RoleName", "select proper RoleName");
            }
            if (_assignRole.UserID == "0")
            {
                ModelState.AddModelError("UserName", "select proper Username");
            }
            if (ModelState.IsValid)
            {
                int currentUserId = CheckUserWithUserRole(Convert.ToInt32(_assignRole.UserID));
                if (currentUserId == Convert.ToInt16(_assignRole.UserRoleName))
                {
                    var UserName = GetUserName_BY_UserID(Convert.ToInt32(_assignRole.UserID));
                    var UserRoleName = GetRoleNameByRoleID(Convert.ToInt32(_assignRole.UserRoleName));
                    Roles.RemoveUserFromRole(UserName, UserRoleName);
                    ViewBag.ResultMessage = "User Role is removed successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This current user doesn't belong to selected user role.";
                }
                _assignRole.UserRolesList = GetAll_UserRoles();
                _assignRole.Userlist = GetAll_Users();
            }
            else
            {
                _assignRole.UserRolesList = GetAll_UserRoles();
                _assignRole.Userlist = GetAll_Users();
            }
            return View(_assignRole);
        }

Following is the code for the remove the role for the respective user.
Following is the code for checking that selected user is belong to the respective RolId.
  public int CheckUserWithUserRole(int UserId)
        {
            using (UsersRoleContext context = new UsersRoleContext())
            {
                int RoleId = context.webpages_UsersInRole.Where(c => c.UserId == UserId).Select(c => c.RoleId).SingleOrDefault();
                return RoleId;

            }
        }

Now right click on the” RemoveRoleAddedToUser” controller and add the view to this controller ,this view contain the scaffold template as “Create” model class and model class as “assignRole”. 

After click add write the following code to this view
@model MvcMembershipProvider.Models.AssignRole

@{
    ViewBag.Title = "RemoveRoleAddedToUser";
}

<h2>RemoveRoleAddedToUser</h2>
<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrap/js/bootstrap.min.js"></script>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>AssignRole</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserRoleName)
        </div>
        <div class="editor-field">
            @*@Html.EditorFor(model => model.UserRoleName)*@
            @Html.DropDownListFor(m => m.UserRoleName, new SelectList(Model.UserRolesList, "Value", "Text"),
new { style = "width:200px", @class = "form-control" })
            @Html.ValidationMessageFor(model => model.UserRoleName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserID)
        </div>
        <div class="editor-field">
            @*@Html.EditorFor(model => model.UserID)*@
            @Html.DropDownListFor(m => m.UserID, new SelectList(Model.Userlist, "Value", "Text"),
new { style = "width:200px", @class = "form-control" })
            @Html.ValidationMessageFor(model => model.UserID)
        </div>

        <p>
            <input type="submit" value="Remove User Role" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Now run your application and go to the following URL
http://localhost:50526/Account/RemoveRoleAddedToUser

Now select user and role type from dropdown list and then check this work.


Authorize attribute in controller
We can authorize or we can give permission to the controller using attribute.
There is a attribute  [Authorize] to authorize. Following is the code for the give the permission code to the controller.
If you want to give permission to the “admin” to full controller , if user have the permission for admin then it will redirect to this page other wise it will redirect to login page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMembershipProvider.Controllers
{
[Authorize(Roles="Admin")]
public class Authonticate1Controller : Controller
{
public ActionResult Index()
{
return View();
}
}
}


If you want to give permission to particular user then use the following code. Here only admin can access then action method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMembershipProvider.Controllers
{
public class Authonticate1Controller : Controller
{
[Authorize(Roles="Admin")]

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


And the following code for the particular action method for the particular user
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMembershipProvider.Controllers
{
public class Authonticate1Controller : Controller
{
[Authorize(Roles = "Admin", Users = "munesh")]
public ActionResult Index()
{
return View();
}
}
}

Download this project from this link Downlaod

Assigning Role to User in Asp.Net MVC Membership


Before proceeding to this tutorial please go to Display Roles for the users in Asp.Net MVC Membership
Here we will learn how to How to assign roles to the users in asp.net membership provider. For assigning the roles to the user we need to add a model for member list and roles List.
1st add a model class in account model.cs class name is “AssignRolesToUsers”.

     public class AssignRole
    {
        [Required(ErrorMessage = " Select proper UserRole Name")]
        public string UserRoleName { get; set; }
        [Required(ErrorMessage = "Select UserName")]
        public string UserID { get; set; }
        public List<SelectListItem> Userlist { get; set; }
        public List<SelectListItem> UserRolesList { get; set; }
    }

After creating the model we need to add a action method in controller class name is “AssignRolesToUsers”.

        [HttpGet]
        public ActionResult AssignRolesToUsers()
        {
           
        }

Now add a DbSet to the UserProfile class

   public class UsersRoleContext : DbContext
    {
        public UsersRoleContext()
            : base("DBConnectionForMembership")
        {
        }

        public DbSet<Role> UserRoles { get; set; }
        public DbSet< UserProfile > UserProfile { get; set; }
    }

Now create two nonAction method got getAllUsers and GetAllUserRoles in Account Controller.
So for that write the following code
     [NonAction]
        public List<SelectListItem> GetAll_UserRoles()
        {
            List<SelectListItem> listrole = new List<SelectListItem>();
            listrole.Add(new SelectListItem { Text = "select", Value = "0" });
            using (UsersRoleContext db = new UsersRoleContext())
            {               
                foreach (var item in db.UserRoles)
                {
                    listrole.Add(new SelectListItem { Text = item.RoleName, Value = Convert.ToString( item.RoleId) });
                }
            }
            return listrole;
        }

        [NonAction]
        public List<SelectListItem> GetAll_Users()
        {
            List<SelectListItem> listuser = new List<SelectListItem>();
            listuser.Add(new SelectListItem { Text = "Select", Value = "0" });

            using (UsersRoleContext db = new UsersRoleContext())
            {
                foreach (var item in db.UserProfile)
                {
                    listuser.Add(new SelectListItem { Text = item.UserName, Value = Convert.ToString(item.UserId) });
                }
            }
            return listuser;
        }

Now add the following code to the “AssignRolesToUsers” action method
  [HttpGet]
        public ActionResult AssignRolesToUsers()
        {
            AssignRole _addignroles = new AssignRole();
            _addignroles.UserRolesList = GetAll_UserRoles();
            _addignroles.Userlist = GetAll_Users();
            return View(_addignroles);
        }

Now after assign the object value need to add view for this action method so for that right click on this action method and select strongly typed model as “AssignRoles” and scaffold template as create.






After click on add it will generate some code for us nut we need to make changes in this view
@model MvcMembershipProvider.Models.AssignRole

@{
    ViewBag.Title = "AssignRolesToUsers";
}

<h2>AssignRolesToUsers</h2>
<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrap/js/bootstrap.min.js"></script>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>AssignRole</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserRoleName)
        </div>
        <div class="editor-field">
            @*@Html.EditorFor(model => model.UserRoleName)*@
            @Html.DropDownListFor(m => m.UserRoleName, new SelectList(Model.UserRolesList, "Value", "Text"),
new { style = "width:200px", @class = "form-control" })
            @Html.ValidationMessageFor(model => model.UserRoleName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserID)
        </div>
        <div class="editor-field">
            @*@Html.EditorFor(model => model.UserID)*@
            @Html.DropDownListFor(m => m.UserID, new SelectList(Model.Userlist, "Value", "Text"),
new { style = "width:200px", @class = "form-control" })
            @Html.ValidationMessageFor(model => model.UserID)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Now run your application and go to following url then o/p will look like this
http://localhost:50526/Account/AssignRolesToUsers




Add role to the user
Now here we will create action method to add the role to the users with the post method.
Write the following code in Post action method for the “AssignRolesToUsers”.
  [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AssignRolesToUsers(AssignRole _assignRole)
        {
            if (_assignRole.UserRoleName == "0")
            {
                ModelState.AddModelError("RoleName", " select UserRoleName");
            }
            if (_assignRole.UserID == "0")
            {
                ModelState.AddModelError("UserName", " select Username");
            }
            if (ModelState.IsValid)
            {
                if (Get_CheckUserRoles(Convert.ToInt32(_assignRole.UserID)) == true)
                {
                    ViewBag.ResultMessage = "Current user is already has the role";
                }
                else
                {
                    var UserName = GetUserName_BY_UserID(Convert.ToInt32(_assignRole.UserID));
                    var UserRoleName = GetRoleNameByRoleID(Convert.ToInt32(_assignRole.UserRoleName));
                    Roles.AddUserToRole(UserName, UserRoleName);
                    ViewBag.ResultMessage = "Username added to role successfully !";
                }
                _assignRole.UserRolesList = GetAll_UserRoles();
                _assignRole.Userlist = GetAll_Users();
                return View(_assignRole);
            }
            else
            {
                _assignRole.UserRolesList = GetAll_UserRoles();
                _assignRole.Userlist = GetAll_Users();
            }
            return View(_assignRole);
        }

Following code for get  UserName by using userid
    public string GetUserName_BY_UserID(int UserId)
        {
            using (UsersRoleContext context = new UsersRoleContext())
            {
                var UserName = (from UP in context.UserProfile
                                where UP.UserId == UserId
                                select UP.UserName).SingleOrDefault();
                return UserName;
            }
        }

Following code for get  UserRoleName by using userRoleId
    public string GetRoleNameByRoleID(int RoleId)
        {
            using (UsersRoleContext context = new UsersRoleContext())
            {
                var roleName = (from UP in context.UserRoles
                                where UP.RoleId == RoleId
                                select UP.RoleName).SingleOrDefault();
                return roleName;
            }
        }

Following code for checking that current user have role name or not
       public bool Get_CheckUserRoles(int UserId)
        {
            using (UsersRoleContext context = new UsersRoleContext())
            {
                var data = (from WR in context.webpages_UsersInRole
                            join R in context.UserRoles on WR.RoleId equals R.RoleId
                            where WR.UserId == UserId
                            orderby R.RoleId
                            select new
                            {
                                WR.UserId
                            }).Count();

                if (data > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

Now run your application and go to the following URL and check the entries

http://localhost:50526/Account/AssignRolesToUsers


database table is


Create a view with all roles and all the users
First for this add a model in account.cs class under model folder. So code for this is

    public class AllroleWithAllUser
    {
        public string UserRoleName { get; set; }
        public string UserName { get; set; }
        public IEnumerable<AllroleWithAllUser> AllDetailsUserlist { get; set; }
    }

Write a nonAction method in controller to get all user with respective UserRole
  [NonAction]
        public List<AllroleWithAllUser> GetUserNameResepectiveToRole()
        {
            using (UsersRoleContext db = new UsersRoleContext())
            {
                var Alldata = (from User in db.UserProfile
                               join WU in db.webpages_UsersInRole on User.UserId equals WU.UserId
                               join WR in db.UserRoles on WU.RoleId equals WR.RoleId
                               select new AllroleWithAllUser { UserName = User.UserName, UserRoleName = WR.RoleName }).ToList();

                return Alldata;
            }
        }

Now write a action method for getting this

        [HttpGet]
        public ActionResult DisplayAllUserroles()
        {
            AllroleWithAllUser _alluserWithRole = new AllroleWithAllUser();
            _alluserWithRole.AllDetailsUserlist = GetUserNameResepectiveToRole();
            return View(_alluserWithRole);
        }


Now we need to add a view for showing  All user with their respective Role. So right click on action method and add a view with scaffold template as empty.


And the write following code in the view
@model MvcMembershipProvider.Models.AllroleWithAllUser

@using GridMvc.Html
@{
    ViewBag.Title = "DisplayAllUserroles";
}
<h2>DisplayAllUserroles</h2>
<link href="~/Content/Gridmvc.css" rel="stylesheet" />
<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/gridmvc.js"></script>
@Html.Grid(Model.AllDetailsUserlist).Columns(columns =>
{
    columns.Add(c => c.UserName).Titled("UserName").Filterable(true).SetWidth(300);
    columns.Add(c => c.UserRoleName).Titled("RoleName").Filterable(true).SetWidth(300);
}).WithPaging(10).Sortable(true)


Now run your application and go to following URL

http://localhost:50526/Account/DisplayRoleForUsers




Download this project from this link Downlaod

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...