// // GET: /Account/Register public ActionResult UpdateAccount(string Id) { ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin")) .ToList(), "Name", "Name"); var userInfo = UserManager.FindById(Id); UpdateAccountViewModel _user = new UpdateAccountViewModel { Id = Id, UserName = userInfo.UserName, Email = userInfo.Email, FullName = userInfo.FullName, //ProvinceId=userInfo.ProvinceId, //ProvinceId=userInfo.ProvinceIds.Split(','), }; var _roles = context.Roles.Where(u => !u.Name.Contains("Admin")); foreach (var _role in _roles) { if (UserManager.IsInRole(Id, _role.Name)) { _user.Role = _role.Name; } } return(View(_user)); }
public async void Update_Should_Return_Status_200() { var user = await Factory.User(); await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); var account = await Factory.Account(userId : user.Id); await _context.Accounts.AddAsync(account); await _context.SaveChangesAsync(); _accessor.HttpContext.User = new ClaimsPrincipal ( new ClaimsIdentity ( new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) } ) ); var viewModel = new UpdateAccountViewModel { Name = "Itaú", Type = "Poupança" }; var result = await _controller.Update(account.Id, viewModel); Assert.IsAssignableFrom <OkObjectResult>(result); }
public AccountViewModel() { CreateAccountViewModel = new CreateAccountViewModel(); DeleteAccountViewModel = new DeleteAccountViewModel(); UpdateAccountView = new UpdateAccountViewModel(); GetAccountViewModel = new GetAccountViewModel(); GetAccountCollectionViewModel = new GetAccountCollectionViewModel(); }
public async Task <ActionResult> UpdateAccount(UpdateAccountViewModel model) { if (ModelState.IsValid) { var user = UserManager.FindById(model.Id); user.FullName = model.FullName; user.Email = model.Email; var result = await UserManager.UpdateAsync(user); if (!UserManager.IsInRole(model.Id, model.Role)) { var _roles = context.Roles.Select(ss => ss.Name).Where(u => !u.Contains("Admin")).ToArray(); UserManager.RemoveFromRoles(model.Id, _roles); UserManager.AddToRole(model.Id, model.Role); } if (!string.IsNullOrEmpty(model.Password)) { bool isOldPassword = UserManager.CheckPassword(user, model.Password); if (!isOldPassword) { var token = UserManager.GeneratePasswordResetToken(model.Id); try { //Reset password using the reset token and the new password UserManager.ResetPassword(model.Id, token, model.Password); } catch (Exception e) { ModelState.AddModelError("", String.Format("{0} Exception caught.", e)); } } } AddErrors(result); } //var _province = TIT.Datas.Services.ProvinceService.GetList(); //ViewBag.provinces = new MultiSelectList(_province, "ProvinceId", "Name"); //ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin")) // .ToList(), "Name", "Name"); //if (model.ProvinceId != null) //{ // var _selected = _province.Where(w => model.ProvinceId.Contains(w.ProvinceId.ToString())).ToList(); // ViewBag.ProvinceSelected = ""; // foreach (var _s in _selected) // { // ViewBag.ProvinceSelected += _s.Name + "; "; // } //} // If we got this far, something failed, redisplay form return(View(model)); }
[HttpGet] // GET: /MyAccount/UpdateAccount public ActionResult UpdateAccount() { var model = new UpdateAccountViewModel(); model.States = new SelectList(_svc.StateGetAll(), "StateId", "StateId"); model.EmailAddress = User.Identity.Name; return(View(model)); }
public ActionResult UpdateAccount() { var model = new UpdateAccountViewModel(); var statesRepo = StatesRepositoryFactory.GetRepository(); model.States = new SelectList(statesRepo.GetAll(), "StateId", "StateId"); model.EmailAddress = User.Identity.Name; return(View(model)); }
public ActionResult UpdateAccount(UpdateAccountViewModel model) { ApplicationUser user = db.Users.Find(User.Identity.GetUserId()); List <Country> countries = db.Countries.Where(x => x.Visible).ToList(); Country country = db.Countries.SingleOrDefault(x => x.Name_En == user.Country); List <City> cities = db.Cities.Where(x => x.Country.Id == country.Id).ToList(); City city = db.Cities.SingleOrDefault(x => x.Name_En == user.City); switch (SiteLanguages.GetCurrentLanguageCulture()) { case "en-US": ViewBag.Country = new SelectList(countries, "Id", "Name_En", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_En", city.Id); break; case "ar-SA": ViewBag.Country = new SelectList(countries, "Id", "Name_Ar", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_Ar", city.Id); break; default: ViewBag.Country = new SelectList(countries, "Id", "Name_En", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_En", city.Id); break; } try { user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.PhoneNumber = model.PhoneNumber; user.Gender = model.Gender; user.Country = db.Countries.Find(int.Parse(model.Country)).Name_En; user.City = db.Cities.Find(int.Parse(model.City)).Name_En; db.SaveChanges(); ViewBag.Message = Resource.AccountUpdated; ViewBag.Alert = "alert alert-success"; return(View(model)); } catch { } ViewBag.Message = Resource.ErrorUpdateAccount; ViewBag.Alert = "alert alert-danger"; return(View(model)); }
public async Task <ActionResult> EditProfile() { var findUser = await UserManager.FindByIdAsync(User.Identity.GetUserId()); UpdateAccountViewModel model = new UpdateAccountViewModel() { Name = findUser.Name, Phone = findUser.PhoneNumber }; return(View(model)); }
public ActionResult UpdateAccount(UpdateAccountViewModel model) { var currentUser = UserManager.FindByEmail(User.Identity.Name); currentUser.UserName = model.EmailAddress; currentUser.Email = model.EmailAddress; currentUser.StateId = model.StateId; UserManager.Update(currentUser); return(RedirectToAction("UpdateAccount")); }
public async Task<IActionResult> Update(UpdateAccountViewModel request) { var result = await _mediator.SendAsync(request); if (!result.Succeeded) { AddErrorsToModelState(result); return RedirectToAction("Update"); } return RedirectToAction("Index"); }
public async Task <ActionResult <UpdateAccountResponseModel> > Post(UpdateAccountViewModel input) { string userId = input.UserId; decimal balance = decimal.Parse(input.Balance); decimal tradeFee = decimal.Parse(input.TradeFee); decimal monthlyFee = decimal.Parse(input.MonthlyFee); await this.accountManagement.UpdateUserAccountAsync(userId, balance, tradeFee, monthlyFee); return(new UpdateAccountResponseModel { Response = "Updated", }); }
public IActionResult UpdateAccount() { var user = Gateway.GetParticipant(Actor.Me.Id); var updateViewModel = new UpdateAccountViewModel(); updateViewModel.Password = new PasswordChangeViewModel(); updateViewModel.Details = new DetailsUpdateViewModel { YearOfBirth = user.YearOfBirth, FullName = user.FullName, Email = user.Email, IsAllowingPromotions = user.IsAllowingPromotions, PhoneNumber = user.PhoneNumber }; return(View(updateViewModel)); }
public async Task <IActionResult> ChangePassword(PasswordChangeViewModel viewmodel) { if (ModelState.IsValid) { var result = await Gateway.ChangePassword(viewmodel); var user = Gateway.GetParticipant(Actor.Me.Id); var updateViewModel = new UpdateAccountViewModel(); updateViewModel.Password = new PasswordChangeViewModel(); updateViewModel.Details = new DetailsUpdateViewModel { YearOfBirth = user.YearOfBirth, FullName = user.FullName, Email = user.Email, IsAllowingPromotions = user.IsAllowingPromotions, PhoneNumber = user.PhoneNumber }; if (result.AnswerType == AnswerType.Success) { SetUserSuccess("שינוי סיסמה", "הסיסמה שונתה בהצלחה"); return(View("UpdateAccount", updateViewModel)); } else { SetUserSuccess("שינוי סיסמה", "תקלה - " + result.Message); return(View("UpdateAccount", updateViewModel)); } } else { var user = Gateway.GetParticipant(Actor.Me.Id); var updateViewModel = new UpdateAccountViewModel(); updateViewModel.Password = new PasswordChangeViewModel(); updateViewModel.Details = new DetailsUpdateViewModel { YearOfBirth = user.YearOfBirth, FullName = user.FullName, Email = user.Email, IsAllowingPromotions = user.IsAllowingPromotions, PhoneNumber = user.PhoneNumber }; var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid); SetUserError("תקלה במידע שהתקבל", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב"); return(View("UpdateAccount", updateViewModel)); } }
public async Task <IActionResult> Update([FromRoute] int id, [FromBody] UpdateAccountViewModel viewModel) { var user = await _auth.User(); var account = await(from current in _context.Accounts where current.Id == id && current.UserId == user.Id select current).FirstAsync(); account.Name = viewModel.Name; account.Type = viewModel.Type; await _context.SaveChangesAsync(); var response = new ResponseViewModel <int>(account.Id); return(Ok(response)); }
public IActionResult Update(int id) { var dto = Db.Get <Account>(id); var model = new UpdateAccountViewModel { ID = dto.ID, Name = dto.Name, Type = dto.Type, StartingBalance = dto.StartingBalance, IncludeInNetWorth = dto.IsIncludedInNetWorth, DisplayOrder = dto.DisplayOrder, IsDormant = dto.IsDormant, NumberLast4Digits = dto.NumberLast4Digits }; return(View(model)); }
public IActionResult UpdateUserAccount(UpdateAccountViewModel updatedUser) { if (!ModelState.IsValid) { return(RedirectToAction("UpdateAccount", "UserAccount")); } User user = new User { Id = (int)HttpContext.Session.GetInt32("id"), Email = updatedUser.Email, Username = updatedUser.UserName, Password = updatedUser.Password }; UserLogic.UpdateUser(user); return(RedirectToAction("UserAccount", "UserAccount")); }
public async Task <ActionResult> Update(int id = 0) { var account = await _accountService.GetAccountById(id); if (account == null) { ModelState.AddModelError(string.Empty, Constants.UnknowErrorMessage); return(RedirectToAction("Update")); } UpdateAccountViewModel viewAccount = _mapper.Map <Account, UpdateAccountViewModel>(account); viewAccount.Roles = _roleService.GetRolesForAccount(account.AccountId).Select(n => n.RoleName).ToList(); //role for combobox List <RoleViewModel> roles = _mapper.Map <IEnumerable <Role>, IEnumerable <RoleViewModel> >(_roleService.GetListRoles()).ToList(); ViewBag.Roles = new SelectList(roles, "Name", "Name"); return(View(viewAccount)); }
public async Task <IActionResult> UpdateDetails(DetailsUpdateViewModel viewModel) { if (ModelState.IsValid) { var updateViewModel = new UpdateAccountViewModel { Password = new PasswordChangeViewModel(), Details = viewModel }; var result = await Gateway.UpdateDetails(viewModel); if (result.AnswerType == AnswerType.Success) { SetUserSuccess("עדכון פרטים", "הפרטים עודכנו בהצלחה"); if (result.Message == "Logout") { return(RedirectToAction("LoginOrRegister", "Account")); } else { return(View("UpdateAccount", updateViewModel)); } } else { var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid); SetUserError("תקלה בעדכון פרטים", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב"); return(View("UpdateAccount", updateViewModel)); } } else { var updateViewModel = new UpdateAccountViewModel { Password = new PasswordChangeViewModel(), Details = viewModel }; var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid); SetUserError("תקלה במידע שהתקבל", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב"); return(View("UpdateAccount", updateViewModel)); } }
public async Task <IActionResult> UpdateAccount([FromForm] UpdateAccountViewModel accountModel) { if (!ModelState.IsValid) { return(View(accountModel)); } else { var account = UpdateAccountToAccountDTOMapper.Instance.Map(accountModel); var result = await apiBankAccountService.UpdateAccount(account); var validateReult = ValidateApiResult(result); if (validateReult == null) { return(RedirectToAction(nameof(GetAllAccounts))); } return(validateReult); } }
public ActionResult Update(UpdateAccountViewModel model, params string[] selectedRoles) { if (ModelState.IsValid) { Account updatedAccount = _mapper.Map <UpdateAccountViewModel, Account>(model); var updateResult = _accountService.Update(updatedAccount); if (!updateResult) { return(RedirectToAction("Update")); } } else { ModelState.AddModelError(string.Empty, Constants.UnknowErrorMessage); return(RedirectToAction("Update")); } return(RedirectToAction("Index")); }
public async Task <ActionResult> EditProfile(UpdateAccountViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var findUser = await UserManager.FindByIdAsync(User.Identity.GetUserId()); var user = await UserManager.FindAsync(findUser.Email, model.Password); bool nameEquals = UserManager.Users.Any(x => x.Name.Equals(model.Name) && !x.Email.Equals(findUser.Email)); bool phoneEquals = UserManager.Users.Any(x => x.PhoneNumber.Equals(model.Phone) && !x.Email.Equals(findUser.Email)); if (user != null) { if (user.Name.Equals(model.Name) && user.Name.Equals(model.Phone)) { return(RedirectToAction("Index", "Places")); } if (nameEquals || phoneEquals) { if (nameEquals) { ModelState.AddModelError("Name", "ชื่อนี้มีผู้ใช้แล้ว"); } if (phoneEquals) { ModelState.AddModelError("Phone", "เบอร์โทรศัพท์นี้มีผู้ใช้แล้ว"); } return(View(model)); } user.Name = model.Name; user.PhoneNumber = model.Phone; await UserManager.UpdateAsync(user); return(RedirectToAction("Index", "Places")); } ModelState.AddModelError("", "รหัสผ่านไม่ถูกต้อง"); return(View(model)); }
public async Task <Object> UpdateAccount(UpdateAccountViewModel model) { Account account = _unitOfWork.AccountRepository.GetByID(model.Id); if (account == null) { return(_apiResponse.Error(ShoerserException.AccountException.A01, nameof(ShoerserException.AccountException.A01))); } account.FullName = model.Fullname; if (account.FullName.Length == 0) { return(_apiResponse.Error(ShoerserException.AccountException.A04, nameof(ShoerserException.AccountException.A04))); } account.Address = model.Address; account.Role = model.Role; _unitOfWork.AccountRepository.Update(account); var result = _apiResponse.Ok(_unitOfWork.Save()); return(result); }
public async Task <ActionResult> UpdateUser([FromBody] UpdateAccountViewModel request) { if (!ModelState.IsValid) { return(BadRequest("Wrong request")); } try { await accountService.UpdateUser(request); return(Ok()); } catch (NotFoundException e) { return(NotFound(e.Message)); } catch (DataSaveException e) { return(BadRequest(e.Message)); } }
public async Task UpdateUser(UpdateAccountViewModel model) { DappUser user = userRepo.FirstOrDefault(x => x.PublicAddress == model.PublicAddress); if (user is null) { throw new NotFoundException("User not found"); } user.FullName = model.FullName; user.Address = model.Address; user.Email = model.Email; user.PhoneNumber = model.PhoneNumber; try { await work.SaveAsync(); } catch { throw new DataSaveException("User information update failed"); } }
/* * Update User information */ public ActionResult UpdateAccount() { ApplicationUser user = db.Users.Find(User.Identity.GetUserId()); UpdateAccountViewModel ua = new UpdateAccountViewModel() { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Gender = user.Gender, PhoneNumber = user.PhoneNumber, Country = user.Country, City = user.City }; List <Country> countries = db.Countries.Where(x => x.Visible).ToList(); Country country = db.Countries.SingleOrDefault(x => x.Name_En == user.Country); List <City> cities = db.Cities.Where(x => x.Country.Id == country.Id).ToList(); City city = db.Cities.SingleOrDefault(x => x.Name_En == user.City); switch (SiteLanguages.GetCurrentLanguageCulture()) { case "en-US": ViewBag.Country = new SelectList(countries, "Id", "Name_En", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_En", city.Id); break; case "ar-SA": ViewBag.Country = new SelectList(countries, "Id", "Name_Ar", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_Ar", city.Id); break; default: ViewBag.Country = new SelectList(countries, "Id", "Name_En", country.Id); ViewBag.city = new SelectList(cities, "Id", "Name_En", city.Id); break; } return(View(ua)); }
public async Task <IActionResult> UpdateAccount([FromForm] UpdateAccountViewModel accountModel) { if (accountModel == null) { return(BadRequest("Object of type account is null")); } if (!ModelState.IsValid) { return(View(accountModel)); } else { try { var account = await accountService.GetAccountById(accountModel.Id); if (account == null) { return(NotFound()); } else { var updatedAccount = UpdateAccountToAccountDTOMapper.Instance.Map(accountModel); await accountService.UpdateAccount(updatedAccount); return(RedirectToAction(nameof(GetAllAccounts))); } } catch (DbUpdateException ex) { logger.LogError($"Unable to update account becuase of {ex.Message}"); ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists, " + "see your system administrator."); return(View(accountModel)); } } }
public async void Update_Should_Account_Has_Been_Updated() { var user = await Factory.User(); await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); var account = await Factory.Account(userId : user.Id); await _context.Accounts.AddAsync(account); await _context.SaveChangesAsync(); _accessor.HttpContext.User = new ClaimsPrincipal ( new ClaimsIdentity ( new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) } ) ); var viewModel = new UpdateAccountViewModel { Name = "Itaú", Type = "Corrente" }; _context.Entry(account).Reload(); await _controller.Update(account.Id, viewModel); Assert.Equal(viewModel.Name, account.Name); Assert.Equal(viewModel.Type, account.Type); }
public async Task <IActionResult> Update(UpdateAccountViewModel model) { if (ModelState.IsValid) { if (model.NewPassword != "" || model.NewPasswordConfirmation != "") { if (model.NewPassword != model.NewPasswordConfirmation) { ModelState.AddModelError("NewPasswordConfirmation", "Passwords do not match."); return(View(model)); } } int userId = int.Parse(User.Claims.First(c => c.Type == "UserId").Value); User user = Database.User .Where(u => u.Id == userId) .FirstOrDefault(); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; if (model.NewPassword != null) { HashAlgorithm algorithm = SHA256.Create(); string password = Encoding.UTF8.GetString(algorithm.ComputeHash(Encoding.ASCII.GetBytes(model.NewPassword))); user.Password = password; } await Database.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(model)); }
public IActionResult Update(UpdateAccountViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var dto = Db.Get <Account>(model.ID); var updated = dto.WithUpdates( name: model.Name, type: model.Type, startingBalance: model.StartingBalance.Value, displayOrder: model.DisplayOrder.Value, isIncludedInNetWorth: model.IncludeInNetWorth, isDormant: model.IsDormant, numberLast4Digits: model.NumberLast4Digits); Db.InsertOrUpdate(updated); UnitOfWork.CommitChanges(); return(RedirectToAction(nameof(Index))); }
public ActionResult Update(UpdateAccountViewModel model) { var result = new AjaxOperationResult(); try { var service = this.Service <IAspNetUserService>(); AspNetUser user = service.Get(model.Id); user.UserName = model.UserName; user.Email = model.Email; user.FullName = model.FullName; user.PhoneNumber = model.PhoneNumber; user.Address = model.Address; user.City = model.City; user.District = model.District; user.Ward = model.Ward; user.Birthday = model.Birthday; user.Gender = model.Gender; service.Update(user); var roleService = this.Service <IAspNetRoleService>(); AspNetRole newRole = roleService.Get(model.RoleId); var roles = UserManager.GetRoles(user.Id).ToArray(); //var oldRoles = Roles.GetRolesForUser(user.UserName); UserManager.RemoveFromRoles(user.Id, roles); UserManager.AddToRole(user.Id, newRole.Name); result.Succeed = true; } catch (Exception e) { result.Succeed = false; } return(Json(result)); }
public async Task <IActionResult> Update(UpdateAccountViewModel model) { if (ModelState.IsValid) { User userToUpdate = await userManager.FindByNameAsync(User.Identity.Name); if (!string.IsNullOrWhiteSpace(model.NewEmail)) { if (model.NewEmail == userToUpdate.Email) { ModelState.AddModelError(string.Empty, "Новый email совпадает со старым"); return(View(model)); } else { userToUpdate.UserName += ApplicationConstantsProvider.AvoidValidationCode(); var updateEmailResult = await userManager.SetEmailAsync(userToUpdate, model.NewEmail); if (!updateEmailResult.Succeeded) { foreach (var updateEmailError in updateEmailResult.Errors) { ModelState.AddModelError(string.Empty, updateEmailError.Description); } return(View(model)); } } } if (!string.IsNullOrWhiteSpace(model.NewTelegramUserName)) { if (model.NewTelegramUserName == userToUpdate.TelegramUsername) { ModelState.AddModelError(string.Empty, "Новое имя пользователя в Telegram совпадает со старым"); return(View(model)); } else { User sameTelegramUser = (await userLogic.Read(new User { TelegramUsername = model.NewTelegramUserName }))?.FirstOrDefault(); if (sameTelegramUser != null) { ModelState.AddModelError(string.Empty, "Уже есть пользователь с таким Telegram-идентификатором"); } else { userToUpdate.Email += ApplicationConstantsProvider.AvoidValidationCode(); userToUpdate.UserName += ApplicationConstantsProvider.AvoidValidationCode(); userToUpdate.TelegramUsername = model.NewTelegramUserName; string tempChatId = userToUpdate.TelegramChatId; userToUpdate.TelegramChatId = string.Empty; var updateTelegramResult = await userManager.UpdateAsync(userToUpdate); if (updateTelegramResult.Succeeded) { if (!string.IsNullOrWhiteSpace(tempChatId)) { await telegramBot.SendMessage("Вы отписаны от уведомлений, " + "т.к. изменили учетные данные на сайте", tempChatId); } } else { foreach (var updateTelegramError in updateTelegramResult.Errors) { ModelState.AddModelError(string.Empty, updateTelegramError.Description); } return(View(model)); } } } } return(RedirectToAction("Personal", "Account")); } return(View(model)); }
public ActionResult Update(UpdateAccountViewModel model) { var currentUserId = User.Identity.GetUserId(); var userToUpdate = this.users .All() .Where(u => u.Id == currentUserId) .First(); userToUpdate.FirstName = model.FirstName; userToUpdate.LastName = model.LastName; userToUpdate.Avatar = model.Avatar; userToUpdate.Address = model.Address; this.users.Update(userToUpdate); this.users.SaveChanges(); return this.RedirectToAction("UserProfile", "Account"); }