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 ActionResult ChangeAcessMode(ScheduleAccessMode mode)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            if (HttpContext.User.IsInRole("Admin"))
            {
                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                string userName = HttpContext.User.Identity.GetUserName();
                var adminUser = userManager.FindByName(userName);
                adminUser.ScheduleAccessMode = mode;
                try
                {
                    userManager.Update(adminUser);
                }
                catch (Exception ex)
                {
                    return RedirectToAction("View","Error",new CustomError(ex.Message));
                }
                string previousUrl = System.Web.HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
                //return RedirectToAction("View", "Schedule", new { course = 1 });
                return Redirect(previousUrl);
            }
            return RedirectToAction("View", "Error", new CustomError("Access Denied"));
        }
Example #3
0
 public bool MapUserToPerson(ApplicationUser user,Person person)
 {
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new EntityDbContext()));
     user.Person = person;
     var idResult = um.Update(user);
     return idResult.Succeeded;
 }
Example #4
0
 public void Update(ApplicationUser user)
 {
     var store = new UserStore<ApplicationUser>(this.Context);
     var userManager = new UserManager<ApplicationUser>(store);
     var context = store.Context;
     userManager.Update(user);
     context.SaveChanges();
 }
        public async Task<ActionResult> DisableUser(string userName)
        {

   
            List<string> users;
            List<string> enabledUsers;
            List<string> disabledUsers;
            using (var context = new ApplicationDbContext())
            {

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                var selectedUser = userManager.FindByName(userName);

                if (selectedUser == null)
                    throw new Exception("User not found!");

                if (!selectedUser.UserName.Equals("[email protected]"))
                {


                    if (!selectedUser.LockoutEnabled)
                    {
                        userManager.SetLockoutEnabled(selectedUser.Id, true);
                        DateTime lockoutDate = DateTime.Now.AddYears(50);
                        await userManager.SetLockoutEndDateAsync(selectedUser.Id, lockoutDate);
                        context.SaveChanges();
                        userManager.Update(selectedUser);
                        ViewBag.ResultMessage = "Disabled successfully !";

                    }
                }
                else
                {
                    ViewBag.ResultMessage = "Cannot disable Admin";
                }

                users = (from u in userManager.Users select u.UserName).ToList();
                disabledUsers = new List<string>(users);
                enabledUsers = new List<string>(users);
                foreach (var user in users)
                {
                    if (!userManager.FindByName(user).LockoutEnabled)
                    {
                        disabledUsers.Remove(user);
                    }
                    else
                    {
                        enabledUsers.Remove(user);
                    }
                }
            }

            ViewBag.EnabledUsers = new SelectList(enabledUsers);
            ViewBag.DisabledUsers = new SelectList(disabledUsers);
            return View();
        }
        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            var ddlRestaurant = GetDdlValue(fvRestaurateur, "ddlRestaurant");
            var ddlUsers = GetDdlValue(fvRestaurateur, "ddlUsers");

            var rstManager = new RestaurantManager();
            var clientManager = new ClientManager();
            var userManager = new UserManager();

            if (fvRestaurateur.CurrentMode == FormViewMode.Edit)
            {
                var client = clientManager.Get(currentId);
                client.Restaurant = rstManager.Get(ddlRestaurant);

                var user = userManager.Get(ddlUsers);
                user.Position = Role.Restaurateur;
                userManager.Update(user);
                client.UserInfo = user;
                clientManager.Update(client);

            }
            else if (fvRestaurateur.CurrentMode == FormViewMode.Insert)
            {
                var client = new ClientInfo();
                client.Restaurant = rstManager.Get(ddlRestaurant);

                var user = userManager.Get(ddlUsers);

                user.Position = Role.Restaurateur;
                userManager.Update(user);
                client.UserInfo = user;

                clientManager.Add(client);

            }
            PopupHelper.HidePopup("#pop", this);
            gvClients.DataBind();
        }
        public ActionResult ChangeTheme(string themename)
        {
            var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager<ApplicationUser>(userStore);
            var user = manager.FindById(User.Identity.GetUserId());
            user.CssTheme = themename;
            manager.Update(user);

            if (Request.UrlReferrer != null)
            {
                var returnUrl = Request.UrlReferrer.ToString();
                return new RedirectResult(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }
        public void UploadPhoto()
        {
            var httpRequest = HttpContext.Current.Request;
            var imageFile = httpRequest.Files["file0"];

            if(imageFile != null)
            {
                var userManager = new UserManager();
                var photoUrl = this.SavePhoto(imageFile);

                var user = userManager.Get()
                    .FirstOrDefault(u => u.Login == HttpContext.Current.User.Identity.Name);
                user.PhotoUrl = photoUrl;
                userManager.Update(user);
            }
        }
        public ActionResult Edit(User input)
        {
            UserManager manager = new UserManager();
            User user = manager.findById(input.Id);

            if (ModelState.IsValid) {
                //db.Users.Attach(userprofile);
                //db.Entry(userprofile).Property(x => x.Active).IsModified = true;
                //db.SaveChanges();

                user.Active = input.Active;
                manager.Update(user);

                return RedirectToAction("Index");
            }
            return View(user);
        }
        public static IdentityResult Update(this ApplicationUser user)
        {
            using (
                var userManager =
                    new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {

                var userUpdated = userManager.FindById(user.Id);

                userUpdated.Name = user.Name;
                userUpdated.LastName = user.LastName;
                userUpdated.PhoneNumber = user.PhoneNumber;
                userUpdated.AlterPhoneNumber = user.AlterPhoneNumber;
                userUpdated.Email = user.Email;
                userUpdated.AlterEmail = user.AlterEmail;
                userUpdated.UserName = user.UserName;

                return userManager.Update(userUpdated);
            }
        }
        // The id parameter name should match the DataKeyNames value set on the control
        public void ProfileForm_UpdateItem(int? id)
        {
            var manager = new UserManager();

            var user = manager.FindByName(User.Identity.Name);

            var item = user.Profile;

            // Load the item here, e.g. item = MyDataLayer.Find(id);
            if (item == null)
            {
                // The item wasn't found
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                manager.Update(user);
                // Save changes here, e.g. MyDataLayer.SaveChanges();
            }
        }
        protected void setPassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Create the local login info and link the local account to the user
                UserManager manager = new UserManager();

                var user = manager.FindById(User.Identity.GetUserId());

                IdentityResult result = manager.AddPassword(user.Id, password.Text);

                if (result.Succeeded)
                {
                    user.IsApproved = true;
                    manager.Update(user);

                    Response.Redirect("~/IdentityAccount/Manage.aspx?m=SetPwdSuccess");
                }
                else
                {
                    AddErrors(result);
                }
            }
        }
        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            try
            {
                using (ApplicationDbContext ctx = new ApplicationDbContext())
                {
                    //var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
                    Logic.CustomUserValidator customerUserValidator = new Logic.CustomUserValidator();
                    manager.UserValidator = customerUserValidator;
                    var user = new ApplicationUser()
                    {
                        UserName = txtUsername.Text,
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        Email = txtEmail.Text,
                        PhoneNumber = txtPhone.Text,
                        Status = ctx.UserStatuses.First(us => us.StatusDescription == "Active"),
                        HasBeenDisassociated = false,
                        DisassociatedMerchant = null
                    };

                    String randomPassword = CreatePassword();

                    IdentityResult result = manager.Create(user, randomPassword);

                    if (result.Succeeded)
                    {
                        lblNewUserMessage.Text = "";

                        ApplicationUser newUser = manager.FindByName(user.UserName);

                        if (newUser != null)
                        {
                            if (!manager.IsInRole(newUser.Id, "Merchant"))
                            {
                                manager.AddToRole(newUser.Id, "Merchant");
                                manager.Update(newUser);
                                ctx.SaveChanges();
                            }

                        }
                        else
                        {
                            lblNewUserMessage.Text = "An error occurred while adding the new user.  Please contact your system administrator before continuing.";
                        }

                        NewUserAdded();

                        btnContinueAddUser.Visible = true;
                        btnCancelAddUser.Visible = false;
                        btnAddUser.Visible = false;
                    }
                    else
                    {
                        lblNewUserMessage.Text = result.Errors.FirstOrDefault();
                    }
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "btnAddUser_Click");
            }
        }
        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);
        }
        public void UpdateUserByID(string userID, string email)
        {
            try
            {
                var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context1));
                var userToUpdate1 = userMgr.FindById(userID);
                    userToUpdate1.Email = email;
                userMgr.Update(userToUpdate1);

            }
            catch (OptimisticConcurrencyException ocex)
            {
                throw ocex;
            }
            catch (ArgumentNullException argex)
            {
                throw argex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ActionResult EnableUser(string userName)
        {

            List<string> users;
            List<string> enabledUsers;
            List<string> disabledUsers;
            using (var context = new ApplicationDbContext())
            {

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                var selectedUser = userManager.FindByName(userName);
                if (selectedUser == null)
                    throw new Exception("User not found!");
                if (selectedUser.LockoutEnabled)
                {
                    userManager.SetLockoutEnabled(selectedUser.Id, false);
                    context.SaveChanges();
                    userManager.Update(selectedUser);


                }


                users = (from u in userManager.Users select u.UserName).ToList();
                disabledUsers = new List<string>(users);
                enabledUsers = new List<string>(users);
                foreach (var user in users)
                {
                    if (!userManager.FindByName(user).LockoutEnabled)
                    {
                        disabledUsers.Remove(user);
                    }
                    else
                    {
                        enabledUsers.Remove(user);
                    }
                }
            }
            ViewBag.ResultMessage = "Enabled successfully !";
            ViewBag.EnabledUsers = new SelectList(enabledUsers);
            ViewBag.DisabledUsers = new SelectList(disabledUsers);
            return View("DisableUser");
        }
        public ActionResult Edit(IndexViewModel indexViewModel)
        {
            if(ModelState.IsValid)
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
                var ctx = store.Context;
                var currentUser = manager.FindById(User.Identity.GetUserId());

                currentUser.FirstName = indexViewModel.User.FirstName;
                currentUser.LastName = indexViewModel.User.LastName;
                currentUser.Address = indexViewModel.User.Address;
                currentUser.City = indexViewModel.User.City;
                currentUser.State = indexViewModel.User.State;
                currentUser.Phone = indexViewModel.User.Phone;
                currentUser.PostalCode = indexViewModel.User.PostalCode;
                manager.Update(currentUser);
                return RedirectToAction("Index", new { message = ManageMessageId.ProfileUpdateSuccess });
            }
            return View(indexViewModel);
        }
 public ActionResult SchemeAddToUser(string UserName, string[] SchemeName)
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     ApplicationUser user = userManager.FindByNameAsync(UserName).Result;
     user.Scheme = string.Join(",", SchemeName);
     userManager.Update(user);
     ViewBag.ResultMessageAddScheme = "Scheme's added to User successfully";
     // prepopulat roles for the view dropdown
     var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
     var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList();
     ViewBag.Roles = list;
     var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
     ViewBag.Users = listUsers;
     ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text");
     return View("Index");
 }
 public ActionResult ChangeMail([Bind(Include = "NewMail")] ChangeMailViewModel model)
 {
     ManageMessageId? m;
     var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
     var manager = new UserManager<ApplicationUser>(store);
     ApplicationUser user = manager.FindById(User.Identity.GetUserId());
     user.Email = model.NewMail;
     var result = manager.Update(user);
     if (result.Succeeded)
     {
         store.Context.SaveChanges();
         m = ManageMessageId.ChangeMailSuccess;
     }
     else
     {
         m = ManageMessageId.Error;
     }
     return RedirectToAction("Index", new { message = m });
 }
        public JsonResult ChangePassword(string userName, string NewPassword)
        {
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            userMgr.UserValidator = new UserValidator<ApplicationUser>(userMgr) { AllowOnlyAlphanumericUserNames = false };
            var user = userMgr.FindByName(userName);
            String hash = userMgr.PasswordHasher.HashPassword(NewPassword);
            //UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
            user.PasswordHash = hash;
            userMgr.Update(user);
            //store.UpdateAsync(user).Wait();

            return Json(new
            {
                Status = "OK",
                Msg = ""
            });
        }
    protected void btncreateaccount_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            //try
            //{
            string emailAddress = txtEmail.Text;
            if (!string.IsNullOrEmpty(emailAddress))
            {
                try
                {

                    System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(emailAddress);
                }
                catch
                {
                    litErrorMsg.Text = "Please Enter Valid Email Address.";
                    return;
                }
            }
            UserData userToCreate = new UserData()
            {
                Username = txtUsername.Text,
                Password = txtPassword.Text,
                FirstName = txtFirstName.Text,
                LastName = txtLastname.Text,
                DisplayName = txtUsername.Text,
                Email = txtEmail.Text,
                IsMemberShip = true
            };
            userToCreate.CustomProperties = userManager.GetCustomPropertyList();
            userToCreate.CustomProperties["Phone"].Value = txtPhone.Text;
            userToCreate.CustomProperties["Country"].Value = ddlCountrylist.SelectedValue;
            userToCreate.CustomProperties["Time Zone"].Value = "GMT Standard Time";

            string userSubs = "";

            if (chkHotDeals.Checked)
                userSubs = Resources.ID.SubscriptionHotDealsId;

            if (chkNews.Checked)
                userSubs += "," + Resources.ID.SubscriptionNewsId;
            if (userSubs.StartsWith(","))
                userSubs = userSubs.Remove(0, 1);

            userToCreate.CustomProperties["Subscriptions"].Value = userSubs;

            Ektron.Cms.Framework.User.UserManager umanager = new UserManager();
            UserData userToEdit = umanager.GetItem(Ektron.Cms.CommonApi.Current.UserId, true);

            userToEdit.FirstName = userToCreate.FirstName;
            userToEdit.LastName = userToCreate.LastName;
            userToEdit.Email = userToCreate.Email;
            userToEdit.CustomProperties["Phone"].Value = userToCreate.CustomProperties["Phone"].Value;
            userToEdit.CustomProperties["Country"].Value = userToCreate.CustomProperties["Country"].Value;
            userToEdit.CustomProperties["Time Zone"].Value = userToCreate.CustomProperties["Time Zone"].Value;
            userToEdit.Username = userToCreate.Username;
            userToEdit.Password = userToCreate.Password;
            userToEdit.DisplayName = userToCreate.Email;

            umanager.Update(userToEdit);

            if (userToEdit.Id != 0)
            {
                divRegistrationwrapper.Visible = false;
                litErrorMsg.Text = "<br /><br />" + Resources.Text.UserCreatedSuccess + "<br /><br />";
            }
            else
            {
                litErrorMsg.Text = Resources.Text.UserCreatedFail;
            }
            //}

            //catch (Exception ex)
            //{
            //    litErrorMsg.Text = Resources.Text.UserCreatedFail;
            //}
        }
    }
Example #22
0
        public ActionResult Edit(EditAccountModel editModel)
        {
            var userManager = new UserManager<Account>(new UserStore<Account>(DbContext));
            Account editAccount = userManager.FindByName(editModel.UserName);

            if (editAccount == null)
            {
                return RedirectErrorPage();
            }

            // Kiểm tra tên tài khoản đã tồn tại hay chưa
            Account accountDb;
            if (editAccount.UserName != editModel.UserName)
            {
                accountDb = userManager.FindByName(editModel.UserName);
                if (accountDb != null)
                {
                    ModelState.AddModelError("UserName", "Tên tài khoản đã được sử dụng.");
                }
            }

            if (editAccount.Email != editModel.Email)
            {
                accountDb = userManager.FindByEmail(editModel.Email);
                if (accountDb != null)
                {
                    ModelState.AddModelError("Email", "Email đã được sử dụng.");
                }
            }
            if (editAccount.Profile.Identity != editModel.Identity)
            {
                accountDb = DbContext.Accounts.FirstOrDefault(s => s.Profile.Identity == editModel.Identity);
                if (accountDb != null)
                {
                    ModelState.AddModelError("Identity", "Mã số này đã được sử dụng.");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var acc = userManager.FindByName(editModel.UserName);
                    acc.Email = editModel.Email;
                    acc.PhoneNumber = editModel.PhoneNumber;
                    acc.Profile.BirthDate = editModel.BirthDate;
                    acc.Profile.FirstName = editModel.FirstName;
                    acc.Profile.LastName = editModel.LastName;
                    acc.Profile.Notes = editModel.Notes;
                    acc.Profile.Actived = editModel.Actived;
                    acc.Profile.Identity = editModel.Identity;
                    var result = userManager.Update(acc);
                    if (result.Succeeded)
                    {
                        if (!string.IsNullOrEmpty(editModel.Password))
                        {
                            userManager.RemovePassword(acc.Id);
                            userManager.AddPassword(acc.Id, editModel.Password);
                        }
                        if (editModel.Role == "Admin")
                        {
                            userManager.AddToRole(acc.Id, "Admin");
                            userManager.AddToRole(acc.Id, "Teacher");
                        }
                        else if (editModel.Role == "Teacher")
                        {
                            userManager.AddToRole(acc.Id, "Teacher");
                        }
                        else
                        {
                            userManager.AddToRole(acc.Id, "Student");
                        }

                        return Redirect(null);
                    }
                    ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau.");
                }
                catch
                {
                    ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau.");
                }
            }
            ViewBag.IsEdit = true;
            InitFormData(editModel);
            return View(editModel);
        }
        public User UpdateUser(User user)
        {
            User result = null;

            /// Validte user and password, to update.
            if (ValidateUser(user.UserName, user.Password) != null)
            {
                using (UserManager manager = new UserManager())
                {
                    result = manager.Update(user);
                }
            }

            return result;
        }