internal bool UpdateUser(string username, string realUsername, string permission)
 {
     IdentityResult result = null;
     Models.ApplicationDbContext context = new Models.ApplicationDbContext();
     var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     var user = userMgr.FindByName(username);
     if (!string.IsNullOrEmpty(realUsername))
     {
         user.RealUserName = realUsername;
         result = userMgr.Update(user);
     }
     if (!string.IsNullOrEmpty(permission) && !userMgr.IsInRole(user.Id, permission))
     {
         userMgr.RemoveFromRoles(user.Id, "read", "edit", "administrator");
         switch (permission)
         {
             case "administrator":
                 result = userMgr.AddToRole(user.Id, "administrator");
                 break;
             case "edit":
                 result = userMgr.AddToRole(user.Id, "edit");
                 break;
             default:
                 result = userMgr.AddToRole(user.Id, "read");
                 break;
         }
     }
     if (result == IdentityResult.Success) return true; else return false;
 }
 public async Task<ActionResult> AssignRole(string username, string rolename)
 {
     UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(_identityDb);
     UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
     var user = userManager.Users.FirstOrDefault(u => u.UserName == username);
     await Task.Run(() => userManager.RemoveFromRoles(user.Id, userManager.GetRoles(user.Id).ToArray()));
     //var role = roles.FirstOrDefault(r => r == rolename);
     //if(role == null)
     userManager.AddToRole(user.Id, rolename);
     return RedirectToAction("Users", "Admin");
 }
        protected void grvUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var row = grvUsers.Rows[e.RowIndex];
            var id = grvUsers.DataKeys[e.RowIndex].Value.ToString();

            var firstName = ((TextBox)row.FindControl("txtFirstName")).Text;
            var lastName = ((TextBox)row.FindControl("txtLastName")).Text;
            var email = ((TextBox)row.FindControl("txtEmail")).Text;
            var currentPassword = ((TextBox)row.FindControl("txtCurrentPassword")).Text;
            var newPassword = ((TextBox)row.FindControl("txtNewPassword")).Text;
            var role = ((DropDownList)row.FindControl("ddlRoleEdit")).Text;
            var jobClinic = ((DropDownList)row.FindControl("ddlJobClinicEdit")).Text; //TODO: Automatically edit RelationType (exept Writer) on files.
            var isActive = ((CheckBox)row.FindControl("chkIsActive")).Checked;

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = userManager.FindById(id);

            if (user != null && (
                userManager.FindById(SharedClass.CurrentUser).UserName == "Admin" ||
                user.UserName != "Admin"
                ))
            {
                if (newPassword != "")
                {
                    var result = userManager.ChangePassword(id, currentPassword, newPassword);
                }
                userManager.SetEmail(id, email);
                userManager.RemoveFromRoles(id, userManager.GetRoles(id).ToArray());
                userManager.AddToRole(id, role);

                using (Medical_Clinic_Entities mc = new Medical_Clinic_Entities())
                {
                    BSI__Clinic_Employee employee = mc.BSI__Clinic_Employees.Where(o => o.Id == id).First();
                    employee.First_Name = firstName;
                    employee.Last_Name = lastName;
                    employee.Job_Clinic = jobClinic;
                    employee.Is_Active = isActive;

                    mc.SaveChanges();
                }
            }
            grvUsers.EditIndex = -1;
        }
        public ActionResult Edit([Bind(Include = "FirstName,LastName,Email,PhoneNumber,UserName")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                var userStore = new UserStore<ApplicationUser>(db);
                var userManager = new UserManager<ApplicationUser>(userStore);

                string userId = userManager.FindByName(applicationUser.UserName).Id;

                userManager.RemoveFromRoles(userId, userManager.GetRoles(userId).ToArray());
                userManager.AddToRoles(userId, Request["Role"].Split(','));

                userManager.Update(applicationUser);

                return RedirectToAction("Index");
            }
            return View(applicationUser);
        }
        private JsonResult ChangeUserAdminStatus(string userId, bool admin)
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_db));
            ApplicationUser user = userManager.FindById(userId);
            IdentityResult result = null;
            
            if (admin)
                result = userManager.AddToRole(userId, "Admin");
            else
                result = userManager.RemoveFromRoles(userId, "Admin");

            string errors = "";

            foreach (string er in result.Errors)
            {
                errors += er + " ";
            }

            if (result.Succeeded)
                return Json(new AppMessage() { Type = AppMessage.Success, Message = String.Format(AppString.UserIsNow, user.Email, admin ? AppString.PartialIsNowAdmin : AppString.PartialIsNoLongerAdmin) });
            else
                return Json(new AppMessage() { Type = AppMessage.Error, Message = String.Format(AppString.UpdateForTypeFailed, AppString.User)  + " " + errors  });
        }