Tuesday, 10 May 2016

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

Monday, 9 May 2016

Display Roles for the users in Asp.Net MVC Membership


Before proceeding to this tutorial please go to Asp.Net MVC Membership Provider
In previous tutorial we learned how to use membership provider in asp.net mvc.Here we will learn how to Display Roles for the users in Asp.Net MVC Membership.
First proceeding to this we need to add a class or we need a model name is Role. Add this role model inside the account model.
Add the following code to the account model.cs class
[Table("webpages_Roles")]
public class Role
{
[Required(ErrorMessage = "Enter Role name")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string RoleName { get; set; }

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
}

 After creating this Role model we need to add a Acton method name RoleCreate  for HttpPost and HttpGet , so for that write following code in account controller
[HttpGet]
public ActionResult UserRole()
{
return View(new Role());
}

[HttpPost]
public ActionResult UserRole(Role role)
{
return View(role);
}


After creating action method for Role we need to add a view for this, For adding view right click on the “UserRole” action method a window will open there you select model class as Role model and select scaffold template as Create,And after selecting all these click on Add.


It will add a view for you and you will see this view under the account folder in View.


Now run your application and login to the page which you created account before. After login to account ,navigate to the following URL
http://localhost:50526/Account/UserRole
 When you will hit this URL it will go to userRole view and page will look like this

After making this view we need to insert role to database so for that we need to add code to insert data into database , so for that  we need to add code in HttpPost method of UserRole action method.
Inside this action method there is a property name is [Roles.RoleExists(role.RoleName) ]to check that this Role is already exist or not in database ,  it return Boolean value. So write the following code in UserRole Action method.
     [HttpPost]
        public ActionResult UserRole(Role role)
        {
            if (ModelState.IsValid)
            {
                if (Roles.RoleExists(role.RoleName))
                {
                    ModelState.AddModelError("Error", " This Rolename already exists");
                    return View(role);
                }
                else
                {
                    Roles.CreateRole(role.RoleName);
                    return RedirectToAction("RoleIndex", "Account");
                }
            }
            else
            {
                ModelState.AddModelError("Error", "Please enter proper Username and Password");
            }
            return View(role);
        }

So far we created Role for the user. Now  we will learn how to assign role to the user.
Assign Roles to the user And Display the Role
For displaying all the user role we will use code first approach so for that we have to creaet a class name is “userContext”  which will be inherited from the “DbContext” class .If you are internet application then is it already exist in account model at top. Code for this class is like following
public class UsersRoleContext : DbContext
    {
        public UsersRoleContext()
            : base("DBConnectionForMembership")
        {
        }

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

DBConnectionForMembership is the connection string name which we defined in web config file.
Now we need to add action method for displaying the role of users and add a action methos in account controller class name is “DisplayRoleForUsers”.
  [HttpGet]
        public ActionResult DisplayRoleForUsers()
        {
            IEnumerable<Role> ListRoles;
            using (UsersRoleContext db = new UsersRoleContext())
            {
                ListRoles = db.UserRoles.ToList();
            }
            return View(ListRoles);
        }

After adding action method ,now need to add view for displaying the role of user so for that right click on DisplayRoleForUsers action method add a view without creating strongly typed view.


Now this view will create a empty view and for showing role of user we need a grid.
Adding MVC Grid to application
For adding grid to the application right click on the application and select “Nuget package manager”


After click on nugget packet manager a window will open  there you search “Grid.Mvc” under online panel. And install this grid to the application.
After adding grid to the application go the “DisplayRoleForUsers” view
Add grid.mvc to this view

Write the following code to this view
@model IEnumerable<MvcMembershipProvider.Models.Role>
   
@using GridMvc.Html
@{
    ViewBag.Title = "Display roles for users";
}

<h2>DisplayAllRoles</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).Columns(columns =>
{
    columns.Add(c => c.RoleId).Titled("Role ID").SetWidth(300);
    columns.Add(c => c.RoleName).Titled("RoleName").Filterable(true).SetWidth(300);
}).WithPaging(5).Sortable(true)


 Now run you application and go to the followinf URL and see the output
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...