public async Task <IActionResult> AddUser(UserAddModel addUser) { if (!ModelState.IsValid) { return(View(addUser)); } var user = new User { UserName = addUser.UserName, Email = addUser.Email, IDCard = addUser.IDCard, Url = addUser.Url, }; var result = await _user.CreateAsync(user, addUser.Password); if (result.Succeeded) { return(RedirectToAction("Index")); } foreach (var item in result.Errors) { ModelState.AddModelError(string.Empty, item.Description); } return(View(addUser)); }
public ActionResult Add(UserAddModel model) { this.CheckPermission(UserRoleAction.ManageUsers); if (!this.ModelState.IsValid) { return(this.View(model)); } if (this.Entities.User.Any(u => u.Email == model.Email.Trim())) { this.ModelState.AddModelError("Email", "Этот адрес уже занят"); return(this.View(model)); } User user = new User(); user.Name = model.Name; user.Email = model.Email; user.IsDisabled = model.IsDisabled; user.Password = model.Password; user.Guid = Guid.NewGuid(); user.Role = model.Role; this.Entities.User.Add(user); this.Entities.SaveChanges(); return(this.RedirectToAction("List")); }
public IActionResult AddUser(AddUserModel addUser) { if (!ModelState.IsValid) { return(View(addUser)); } UserAddModel user = new UserAddModel() { IntialBalance = addUser.IntialBalance, Name = addUser.Name, Password = addUser.Password, UserName = addUser.UserName, AdminUserId = User.FindFirstValue(ClaimTypes.NameIdentifier) }; var result = userService.AddUser(user); if (!result.IsSuccessFul) { ModelState.AddModelError("", result.Data); return(View(addUser)); } return(RedirectToAction("UserList", "Account")); }
public Task <ApplicationUser> CreateUser(UserAddModel user) { using (var unitOfWork = new UnitOfWork()) { return(unitOfWork.UserRepository.CreateUser(user)); } }
public void UserAdd_Post_ReturnsViewIfModelStateIsInvalid() { // Arrange AccountController controller = GetAccountController(); UserAddModel model = new UserAddModel { Email = "goodEmail", UserName = "******", FirstName = "goodFName", LastName = "goodLName", Organization = "MPR", AccountType = null, AccountTypeOptions = null, RadioSelectedState = 1, RoleSelections = new List <RoleSelection>(), RadioStateSelections = new List <StateSelection>(), CheckboxStateSelections = new List <StateSelection>() }; controller.ModelState.AddModelError(string.Empty, "Dummy error message."); // Act ActionResult result = controller.Add(model); // Assert Assert.IsInstanceOf(typeof(ViewResult), result); ViewResult viewResult = (ViewResult)result; Assert.AreEqual(model, viewResult.ViewData.Model); }
public Result <string> Login(UserAddModel model) { if (model == null) { return(GetInvalidResult <string>(null, "无效的会员登录信息")); } if (string.IsNullOrEmpty(model.MerchantId)) { return(GetInvalidResult <string>(null, "商户Id不能为空")); } if (string.IsNullOrEmpty(model.UserName)) { return(GetInvalidResult <string>(null, "会员名称不能为空")); } if (string.IsNullOrEmpty(model.SignKey)) { return(GetInvalidResult <string>(null, "签名不能为空")); } try { var result = this.UserService.GetUserToken(model); return(GetSuccessResult(result)); } catch (Exception ex) { return(GetExceptionResult <string>(null, ex)); } }
public void UserAdd_Post_ReturnsRedirectOnSuccess() { // Arrange AccountController controller = GetAccountController(); UserAddModel model = new UserAddModel { Email = "goodEmail", UserName = "******", FirstName = "goodFName", LastName = "goodLName", Organization = "MPR", AccountType = null, AccountTypeOptions = null, RadioSelectedState = 1, RoleSelections = new List <RoleSelection>(), RadioStateSelections = new List <StateSelection>(), CheckboxStateSelections = new List <StateSelection>() }; // Act ActionResult result = controller.Add(model); // Assert Assert.IsInstanceOf(typeof(RedirectToRouteResult), result); RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; Assert.AreEqual("Account", redirectResult.RouteValues["controller"]); Assert.AreEqual("Users", redirectResult.RouteValues["action"]); }
public void RegisterUserDetails(UserAddModel userDeets) { using (var context = new ApplicationDbContext()) { var userStore = new UserStore <ApplicationUser>(context); var userManager = new UserManager <ApplicationUser>(userStore); var users = userManager.Users.ToList(); var user = users.Find(item => item.Email == userDeets.Email); Console.WriteLine(); /*foreach (var user in users) * { * ApplicationUserModel u = new ApplicationUserModel * { * Id = user.Id, * Email = user.Email * }; * }*/ var userDetails = new UserAddModel { Id = user.Id, Email = user.Email, FirstName = userDeets.FirstName, LastName = userDeets.LastName }; UserData data = new UserData(); data.RegisterUserDetails(userDetails); } }
public void UserAdd_Post_ReturnsViewIfUserAddFails() { // Arrange AccountController controller = GetAccountController(); UserAddModel model = new UserAddModel { Email = "*****@*****.**", UserName = "******", FirstName = "goodFName", LastName = "goodLName", Organization = "MPR", AccountType = null, AccountTypeOptions = null, RadioSelectedState = 1, RoleSelections = new List <RoleSelection>(), RadioStateSelections = new List <StateSelection>(), CheckboxStateSelections = new List <StateSelection>() }; // Act ActionResult result = controller.Add(model); // Assert Assert.IsInstanceOf(typeof(ViewResult), result); ViewResult viewResult = (ViewResult)result; Assert.AreEqual(model, viewResult.ViewData.Model); Assert.AreEqual( "Username already exists. Please enter a different user name.", controller.ModelState[string.Empty].Errors[0].ErrorMessage); }
public async Task <IHttpActionResult> PostUser(UserAddModel user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (db.Users.Any(x => x.FaceBookUniqueId == user.FaceBookUniqueId)) { var ux = db.Users.Where(x => x.FaceBookUniqueId == user.FaceBookUniqueId).First(); return(CreatedAtRoute("DefaultApi", new { id = ux.UserId }, ux)); } //return new System.Web.Http.Results.OkResult(this); var u = new User { Email = user.Email, FaceBookUniqueId = user.FaceBookUniqueId, FirstName = user.FirstName, LastName = user.LastName, PhoneNo = user.PhoneNo, }; db.Users.Add(u); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = u.UserId }, u)); }
public ActionResult Add(UserAddModel model) { if (ModelState.IsValid) { try { User user = new User() { UserName = model.UserName, Email = model.Email, Role = model.Role, RegisterDate = DateTime.Now, NiceName = model.UserName }; _userService.AddUser(user); return(RedirectToAction("Index", new { Message = "用户添加成功。" })); } catch (Exception ex) { ViewBag.Message = ex.Message; } } else { foreach (var value in ModelState.Values) { foreach (var error in value.Errors) { ViewBag.Message = error.ErrorMessage; break; } if (ViewBag.Message != null) { break; } } } return(View()); }
public ActionResult Add(UserAddModel model) { if (!ModelState.IsValid) { string msg = mvchelper.GetValiMsg(ModelState); return(Json(new AjaxResult { status = "error", errorMsg = msg })); } //服务器端的校验必不可少 bool exists = UserSvc.GetByPhoneNum(model.phonenum) != null; if (exists) { return(Json(new AjaxResult { status = "error", errorMsg = "手机号已经存在" })); } long userId = UserSvc.AddUser(model.account, model.nickname, model.phonenum, model.gender, model.password, model.email); UserRoleSvc.AddUserRole(userId, model.RoleIds); //roleService.AddRoleIds(userId, model.RoleIds); return(Json(new AjaxResult { status = "ok" })); }
public IActionResult Add([FromBody] UserAddModel user) { var userDto = new User { Id = null, Name = user.Name, Password = user.Password }; try { return(Ok(new AddUserReturnModel { Name = ServiceFactory.UsersService.Add(userDto).Name })); } catch (UserAlreadyExistsException e) { return(BadRequest(e)); } catch (Exception e) { return(BadRequest(e)); } }
public async Task <ApplicationUser> CreateUser(UserAddModel user) { try { var aUser = new ApplicationUser { Email = user.Email, FirstName = user.FirstName, MiddelName = user.MiddelName, LastName = user.LastName, Contact = user.Contact, RoleID = user.RoleID, DesignationID = user.DesignationID, Status = true, Delete = false, CreatedDate = DateTime.Now, DesignationName = user.DesignationName, EmailConfirmed = true, UserName = user.UserName, PasswordHash = user.Password, Address = user.Address }; var chkUser = await _userManager.CreateAsync(aUser, user.Password); if (chkUser.Succeeded) { await _userManager.AddToRoleAsync(aUser, user.RoleName); } } catch (Exception ex) { throw ex; } return(null); }
public async Task AddUserAsync(UserAddModel user) { var channel = new Channel(channelTarget, ChannelCredentials.Insecure); try { var client = new UsersGrpcService.UsersGrpcServiceClient(channel); var request = new AddUserRequest() { Id = user.Id.ToString(), Username = user.Username, Email = user.Email, YearOfBirth = user.YearOfBirth, LibraryId = user.LibraryId.ToString() }; var response = await client.AddUserAsync(request); return; } finally { await channel.ShutdownAsync(); } }
/// <summary> /// 代理商登录 /// </summary> /// <param name="model">登录信息</param> /// <returns>用户登录Token</returns> public string GetUserToken(UserAddModel model) { using (var dbContext = new TicketEntities()) { if (string.IsNullOrEmpty(model.MerchantId) && string.IsNullOrEmpty(model.UserName) && string.IsNullOrEmpty(model.SignKey)) { throw new KeyNotFoundException("无效的用户登录信息"); } //1, 判断用户是否存在 var merchantEntity = dbContext.N_Merchant.FirstOrDefault(it => (it.MerchantId.Equals(model.MerchantId, StringComparison.OrdinalIgnoreCase))); if (merchantEntity == null) { Log.Error("商户不存在"); throw new KeyNotFoundException("商户不存在"); } if (string.IsNullOrEmpty(merchantEntity.Code)) { Log.Error("无效的商户"); throw new KeyNotFoundException("无效的商户"); } //2, 验证加密串 var signKey = MD5Cryptology.GetMD5(string.Format("{0}&{1}&{2}", model.MerchantId, model.UserName, merchantEntity.Code), "gb2312"); if (string.Compare(signKey, model.SignKey, true) != 0) { Log.Error("无效的商户安全码:" + signKey); throw new KeyNotFoundException("无效的商户安全码:" + signKey); } //3,验证用户 var userEntity = dbContext.N_User.FirstOrDefault(it => it.UserName.Equals(model.UserName, StringComparison.OrdinalIgnoreCase)); if (userEntity == null) { Log.Error("用户不存在"); throw new KeyNotFoundException("用户不存在"); } var token = this.GenerateToken(); // 获取用户登录Token userEntity.Token = token; userEntity.ExpirationTime = DateTime.Now.AddDays(2); // 设置Token有效期 SaveDbChanges(dbContext); string message = null; if (string.IsNullOrEmpty(token)) { message = "登录失败,请重新登录!"; } message = "恭喜你,登陆成功!"; return(token + "@" + message); } }
//public ActionResult AddUserInfo() //{ // UserAddModel model = new UserAddModel(); // int roleLevel = (int)GetUserSession().RoleInfo.RoleLevel; // model.RoleSelectList = RoleBLL.GetRolesByCurrentUserRoleLevel(roleLevel).ToSelectList(m => GetSelectListItem(m.ID, m.RoleName)); // //model.StrucSelectList = StructureBLL.GetStructures().ToSelectList(m => GetSelectListItem(m.ID, m.StrucName)); // //model.StrucSelectList.First().Selected = true; // return PartialView("_AddUserInfo", model); //} //[HttpPost, ValidateAntiForgeryToken] //public ActionResult AddUserInfo(UserAddModel model) //{ // if (ModelState.IsValid) // { // var result = UserBLL.Adduser(model,base.UserIDForLog); // base.DoLog(OperationTypeEnum.Add, result, "UserName:"******"_AddUserInfo", model); // } //} //[HttpPost, AsiatekSubordinateFunction("AddUserInfo")] //public ActionResult CheckAddUserNameExists(string userName) //{ // return Json(!UserBLL.CheckUserNameExists(userName)); //} #endregion #region 编辑 //public ActionResult EditUserInfo(int id) //{ // var obj = UserBLL.GetUserByID(id); // if (obj.DataResult == null) // { // return Content(obj.Message); // } // var model = obj.DataResult; // int roleLevel = (int)GetUserSession().RoleInfo.RoleLevel; // model.RoleSelectList = RoleBLL.GetRolesByCurrentUserRoleLevel(roleLevel).ToSelectList(m => GetSelectListItem(m.ID, m.RoleName)); // //model.StrucSelectList = StructureBLL.GetStructures().ToSelectList(m => GetSelectListItem(m.ID, m.StrucName)); // return PartialView("_EditUserInfo", model); //} //[HttpPost, ValidateAntiForgeryToken] //public ActionResult EditUserInfo(UserEditModel model) //{ // if (ModelState.IsValid) // { // var result = UserBLL.EditUser(model,base.UserIDForLog); // base.DoLog(OperationTypeEnum.Edit, result, "UserID:" + model.ID); // return Json(result); // } // else // { // int roleLevel = (int)GetUserSession().RoleInfo.RoleLevel; // model.RoleSelectList = RoleBLL.GetRolesByCurrentUserRoleLevel(roleLevel).ToSelectList(m => GetSelectListItem(m.ID, m.RoleName)); // //model.StrucSelectList = StructureBLL.GetStructures().ToSelectList(m => GetSelectListItem(m.ID, m.StrucName)); // return PartialView("_EditUserInfo", model); // } //} //[HttpPost, AsiatekSubordinateFunction("EditUserInfo")] //public ActionResult CheckEditUserNameExists(string userName, int id) //{ // return Json(!UserBLL.CheckUserNameExists(userName, id)); //} #endregion #region 新增编辑用户新版 #region 新增 public ActionResult AddUserInfo() { UserAddModel model = new UserAddModel(); int roleLevel = (int)GetUserSession().RoleInfo.RoleLevel; model.RoleSelectList = RoleBLL.GetRolesByCurrentUserRoleLevel(roleLevel).ToSelectList(m => GetSelectListItem(m.ID, m.RoleName)); model.VehicleViewMode = true; return(PartialView("_AddUserInfo", model)); }
public async Task <HttpResponseMessage> CreateAsync(UserAddModel model) { var user = await Services.Management.CreateUserAsync(model); var response = Request.CreateResponse(HttpStatusCode.Created); var uri = Url.Link(RetrieveUserRoute, new { id = user.Id }); response.Headers.Location = new Uri(uri); return(response); }
public Result <string> AddUser(UserAddModel userAddModel) { User user = dbContext.Users.FirstOrDefault(u => u.UserName == userAddModel.UserName); if (user != null) { return new Result <string>() { IsSuccessFul = false, Data = "User name already exist" } } ; user = new User() { Id = Guid.NewGuid(), Name = userAddModel.Name, Password = passwordHasher.Hash(userAddModel.Password), Role = UserRole.Standard, UserName = userAddModel.UserName }; Account account = new Account() { Balance = (decimal)userAddModel.IntialBalance, Id = Guid.NewGuid(), UserId = user.Id, }; account.SetAcountNumber(); user.Account = account; dbContext.Users.Add(user); var admin = dbContext.Users.Include(u => u.Account).FirstOrDefault(a => a.Id == Guid.Parse(userAddModel.AdminUserId)); Transaction transaction = new Transaction() { Id = Guid.NewGuid(), Description = "Initial account setup", Amount = (decimal)userAddModel.IntialBalance, SourceAccount = admin.Account.Number, TargetAccount = account.Number, Status = TransctionStatus.Pending, TransactionDate = DateTime.Now, Type = TransactionType.Credit }; dbContext.Transactions.Add(transaction); dbContext.SaveChanges(); return(new Result <string>() { IsSuccessFul = true }); } }
public async Task <IActionResult> Add([FromBody] UserAddModel userAddModel) { if (!ModelState.IsValid) { return(BadRequest()); } var userDto = _mapper.Map <UserDtoForCreate>(userAddModel); var response = await _userService.AddAsync(userDto); return(_userResponseCreator.ResponseForCreate(response, userDto)); }
public async Task <IResultModel> Add(UserAddModel model) { var entity = _mapper.Map <UserEntity>(model); //if (await _repository.Exists(entity)) //{ //return ResultModel.HasExists; //} var result = await _repository.AddAsync(entity); return(ResultModel.Result(result)); }
public async Task <ServiceResult> CreateNew([FromBody] UserAddModel apiEntity) { var entity = UserAddModel.Map(apiEntity); var result = await _userService.AddAsync(entity, apiEntity.Password); if (result.TryCastModel(out AppUser user)) { result.ViewModel = UserViewModel.Map(user); } return(result); }
/// <summary> /// Perform server side validation prior to saving /// </summary> /// <param name="model"></param> private void ValidateCopyModel(UserAddModel model, UserToken token) { //check for dup user name if (_dal.Count(x => x.UserName.ToLower().Equals(model.UserName.ToLower()), token) > 0) { ModelState.AddModelError("User Name", "Duplicate user name. Please enter a different user name."); } //Check for duplicate service and return model state error //if (model.Attributes != null && model.Attributes.GroupBy(v => v.Name).Where(g => g.Count() > 1).Any()) //{ // ModelState.AddModelError("", "Duplicate attribute names found. Remove the duplicates."); //} }
public void AddUser() { var userDetails = new UserAddModel { FirstName = FirstName, LastName = LastName, Email = Email, Password = Password, ConfirmPassword = ConfirmPassword }; _userEndpoint.AddUser(userDetails); }
public async Task <object> Post([FromBody] UserAddModel user) { var output = new ResponseDetail(); try { if (ModelState.IsValid && user != null) { var aUser = new ApplicationUser { Email = user.Email, FirstName = user.FirstName, MiddelName = user.MiddelName, LastName = user.LastName, Contact = user.Contact, RoleID = user.RoleID, DesignationID = user.DesignationID, Status = true, Delete = false, CreatedDate = DateTime.Now, DesignationName = user.DesignationName, EmailConfirmed = true, UserName = user.Email, PasswordHash = user.Password, Address = user.Address, PhoneNumberConfirmed = true }; var chkUser = await _userManager.CreateAsync(aUser, user.Password); if (chkUser.Succeeded) { await _userManager.AddToRoleAsync(aUser, user.RoleName); output.Success = true; output.Message = "User created successfully!"; return(output); } output.Success = false; return(output); } output.Message = "Error Occured"; output.Success = false; return(output); } catch (Exception ex) { output.Success = false; output.Message = ex.Message; return(output); } }
public async Task <IActionResult> UpdateAsync([FromBody] UserAddModel userModel) { if (userModel == null) { return(BadRequest()); } var response = await _userApplication.UpdateAsync(userModel); if (response.IsSuccess) { return(Ok(response)); } return(BadRequest(response.Message)); }
public IActionResult Update([FromBody] UserAddModel userModel) { if (userModel == null) { return(BadRequest()); } var response = _userApplication.Update(userModel); if (response.IsSuccess) { return(Ok(response)); } return(BadRequest(response.Message)); }
public ActionResult AddUserInfo(UserAddModel model) { if (ModelState.IsValid) { var result = UserBLL.Adduser(model, base.UserIDForLog); base.DoLog(OperationTypeEnum.Add, result, "UserName:"******"_AddUserInfo", model)); } }
public ActionResult AddUser() { try { UserAddModel model = new UserAddModel(); model.FillDDLs(); return(View("AddUser", model)); } catch (RepositoryException repEx) { Trace.TraceError("A Repository Error has occurred as the followings: {0}", repEx.ToString()); return(Redirect(Url.Action(nameof(Index))) .WithDangerSnackbar("عفواً. حدث خطأ أثناء جلب البيانات. الرجاء المحاولة لاحقاً.")); } }
public static UserModel GetUserAddModel(UserAddModel model, int userId) { Nullable <DateTime> endDate = null; return(new UserModel() { FirstName = model.first_name, LastName = model.last_name, SubmitDate = DateTime.Now, Password = model.password, RoleId = model.role, UserName = model.username, CreatedUser = userId, EndDate = model.end_date != null?Utils.DateTimeHelper.JalaliStringToGregorian(model.end_date) : endDate, }); }