public ActionResult Register(RegisterViewModel model) { if (ModelState.IsValid) { try { // создаем нового пользователя _userLogic.AddUser(new Common.User { Name = model.Name, SurName = model.SurName, Patronymic = model.Patronymic, City = model.City, Faculty = model.Faculty, University = model.University, Direction = model.Direction, EMail = model.Email, Password = model.Password }); User user = _userLogic.GetUserByEMail(model.Email); // если пользователь удачно добавлен в бд if (user != null) { FormsAuthentication.SetAuthCookie(model.Email, true); return(RedirectToAction("Index", "Home")); } } catch { ModelState.AddModelError("", "Пользователь с таким логином уже существует"); } } return(View(model)); }
public ActionResult Signup(SignupModel model) { if (ModelState.IsValid) { if (!_logic.CheckUserReg(model.Username)) { MailAddress from = new MailAddress("*****@*****.**", "Registration"); MailAddress to = new MailAddress(model.Email); MailMessage msg = new MailMessage(from, to); msg.Subject = "Подтверждение регистрации"; msg.Body = string.Format("Для завершения регистрации перейдите по ссылке: " + "<a href=\"{0}\" title=\"Подтвердить регистрацию\">{0}</a>", Url.Action("ConfirmEmail", "User", new { userName = model.Username, email = model.Email }, Request.Url.Scheme)); msg.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**", "Drocsid_2018"); smtp.EnableSsl = true; smtp.Send(msg); _logic.AddUser(model.Username, CreatePasswordHash(model.Password /*_logic.GenerateSalt(model.Password.Length)*/), model.Email); return(RedirectToAction("Confirm", "User", new { email = model.Email })); } else { ModelState.AddModelError("", "Пользователь с таким логином уже существует"); } } return(View(model)); }
public static void Main() { NinjectCommon.NinjectCommon.Registration(); _userLogic = NinjectCommon.NinjectCommon.Kernel.Get<IUserLogic>(); _reviewLogic = NinjectCommon.NinjectCommon.Kernel.Get<IReviewLogic>(); var userIllario = new User {Id = 3, Name = "Illario", Password = "******", Role = 3}; _userLogic.AddUser(userIllario); _reviewLogic.AddReview(userIllario.Id, new Review {Id = 2, Name = "Google Play", Comment = "OK"}); Console.WriteLine("Users: "); foreach (var item in _userLogic.GetUsers()) { Console.WriteLine($"{item.Id} : {item.Name} : {item.Role} "); } Console.WriteLine(); Console.WriteLine("Reviews: "); foreach (var item in _reviewLogic.GetReviews()) { Console.WriteLine($"{item.Id} : {item.Name} : {item.Comment}"); } Console.WriteLine(); foreach (var item in _reviewLogic.GetReviewsForUser(1)) { Console.WriteLine($"{item.Name} : {item.Comment}"); } _reviewLogic.AddReview(userIllario.Id, new Review {Id = 1, Name = "App store", Comment = "Not OK"}); Console.WriteLine("Reviews: "); foreach (var item in _reviewLogic.GetReviews()) { Console.WriteLine($"{item.Id} : {item.Name} : {item.Comment}"); } _userLogic.UpdateUserForAdmin(1, 2); _userLogic.UpdateUserForUsers(1, "Petro"); _reviewLogic.UpdateReview(1, "App store", "Now it's OK"); _userLogic.DeleteUser(4); _reviewLogic.DeleteReview(3); var user = _userLogic.GetUserById(1); Console.WriteLine(user.Name); var review = _reviewLogic.GetReviewById(1); Console.WriteLine(review.Name); Console.ReadKey(); }
public ActionResult AddUser(UserModel model) { ViewBag.Message = "AddUser"; if (ModelState.IsValid) { userLogic.AddUser(model.Name, model.DateIfBirth, model.Age); return(RedirectToAction("Index")); } return(View()); }
private static void AddUser(IUserLogic userLogic) { var user = new User { Name = "John", DateOfBirth = new DateTime(1986, 07, 24), }; userLogic.AddUser(user); }
public IActionResult Register(RegisterViewModel registerViewModel) { if (registerViewModel != null) { registerViewModel.Password = _accountLogic.EncryptPassword(registerViewModel.Password); registerViewModel.RePassword = _accountLogic.EncryptPassword(registerViewModel.RePassword); Response message = _userLogic.AddUser(_accountControllerHelper.BuildDTO(registerViewModel), registerViewModel.RePassword); } return(RedirectToAction("Index", "Share")); }
//добавление информации private static void Adding() { while (true) { Console.WriteLine(); Console.WriteLine($"1: Add user"); Console.WriteLine($"2: Add award"); Console.WriteLine($"3: HELP"); Console.WriteLine($"4: EXIT"); Console.Write($"Choose action: "); var userAction = Console.ReadLine(); switch (userAction) { case "1": Console.Write($"User's Name: "); var name = Console.ReadLine(); Console.Write($"User's Birthday: "); var birthday = Console.ReadLine(); Console.Write($"User's Email: "); if (userLogic.AddUser(name, birthday, null) != default) { Console.WriteLine($"User is created!{Environment.NewLine}"); } else { Console.WriteLine($"User isn't created!{Environment.NewLine}"); } break; case "2": Console.Write($"Award's Title: "); var title = Console.ReadLine(); Console.Write($"Award's Description: "); var description = Console.ReadLine(); awardLogic.AddAward(title, description, null); Console.WriteLine($"Award is created!{Environment.NewLine}"); break; case "3": Console.WriteLine($"HELP YOURSELF"); break; case "4": return; default: Console.WriteLine("I don't know this comuserd"); break; } } }
public async Task SignUpUser(SignUpModel signUpModel) { if (await _userLogic.AddUser(signUpModel)) { } else { //TODO: Throw custom exception throw new Exception("Failed to sign up users"); } }
public ActionResult <User> PostUser([FromBody] User user) { if (user.Username != null && user.Password != null && !_userLogic.UsernameExists(user)) { _userLogic.AddUser(user); return(CreatedAtAction(nameof(GetUser), new { id = user.Id }, user)); } else { return(StatusCode(422)); } }
public static void AddUser() { Console.WriteLine("Enter full name"); var fullName = Console.ReadLine(); Console.WriteLine("Enter date of birth"); var dateOfBirth = Console.ReadLine(); Console.WriteLine("Enter age"); var age = Console.ReadLine(); userLogic.AddUser(fullName, dateOfBirth, int.Parse(age)); }
public IActionResult AddUser([FromBody] Users user) { try { _logger.LogInfo("Adding User"); var result = iUserLogic.AddUser(user); return(Ok(result)); } catch (Exception ex) { _logger.LogError($"Something went wrong: {ex}"); return(StatusCode(500, "Internal Server error")); } }
public IActionResult Post([FromBody] UserModel model) { try { var user = UserModel.ToEntity(model); var toReturn = userLogic.AddUser(user); return(Ok("Se agregó el usuario " + user.Username + " con el ID " + toReturn.ID)); } catch (AlreadyExistsException) { return(BadRequest("No es posible agregar un usuario ya existente")); } catch (NullException) { return(BadRequest("No es posible agregar un usuario nulo")); } catch (NullReferenceException) { return(BadRequest("No es posible agregar un usuario nulo")); } catch (NotValidException) { return(BadRequest("No es posible agregar un usuario no válido")); } catch (DataBaseLogicException) { return(BadRequest("Error en la conexión con la base de datos")); } catch (InvalidOperationLogicException) { return(BadRequest("Error en el sistema")); } }
public ActionResult Create(UserCreateVM user) { try { if (ModelState.IsValid) { _userLogic.AddUser(Mapper.Map <UserCreateVM, User>(user)); return(RedirectToAction("Index")); } } catch (Exception ex) { ModelState.AddModelError(String.Empty, ex); } return(View(user)); }
public async Task <IActionResult> AddUser([FromBody] AdditionRegisterInDto model) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var _ = await _logic.AddUser(model); return(Ok(_)); } catch (Exception e) { return(ExceptionResult(e)); } }
public async Task <object> AddUser([FromBody] UserModel userModel) { var errors = _userValidations.ValidateUserData(userModel, "insertion"); if (errors != null) { return(errors); } var response = await _userLogic.AddUser(userModel); if (response) { return(_userValidations.UserAddedSuccess()); } return(_userValidations.UserAddedFailed()); }
public async Task <ActionResult> AddUser(UserViewModel user) { if (ModelState.IsValid && _userLogic.DoesThisUserExist(user.Name) != true) { _userLogic.AddUser(_mapper.Map <UserModel>(user)); await LoginUser(user); return(RedirectToAction("ListMovies", "Movie")); } ModelState.AddModelError("Name", "This user already exists."); var viewUser = new UserViewModel { UserTypes = Enum.GetValues(typeof(UserTypes)).Cast <UserTypes>().ToList(), }; return(View(viewUser)); }
public IActionResult RegisterUser([FromBody] NewUserModel userModel) { LoginResponseStruct loginResponse = new LoginResponseStruct(); try { if (ModelState.IsValid) { if (_UserLogic.IsUserExist(userModel.UserName)) { return(BadRequest("User with this user name already exist.")); } if (HttpContext.Request.Headers.TryGetValue("TimezoneOffset", out StringValues timezoneOffset)) { if (int.TryParse(timezoneOffset.ToString(), out int offset)) { UserEntity user = userModel.Map <UserEntity>(); user.Person = userModel.Person.Map <PersonEntity>(); user = PrepareUser(user, offset); user = _UserLogic.AddUser(user); user.Password = ""; loginResponse.TokenDetails = JwtService.GenerateToken(user); loginResponse.User = user; return(Ok(loginResponse)); } else { return(BadRequest("Header TimezoneOffset is not typeof number.")); } } else { return(BadRequest("Header must container TimezoneOffset.")); } } else { return(BadRequest(ModelState)); } } catch (Exception e) { return(StatusCode(500, e)); } }
public IActionResult Register(RegisterViewModel registerViewModel) { if (registerViewModel != null) { if (string.IsNullOrEmpty(registerViewModel.Password) || string.IsNullOrEmpty(registerViewModel.RePassword)) { ModelState.AddModelError("Password cannot be null", "Password cannot be null"); return(View("Register", registerViewModel)); } registerViewModel.Password = _accountLogic.EncryptPassword(registerViewModel.Password); registerViewModel.RePassword = _accountLogic.EncryptPassword(registerViewModel.RePassword); Response message = _userLogic.AddUser(_accountControllerHelper.BuildDTO(registerViewModel), registerViewModel.RePassword); if (!message.IsCompletedSuccesfuly) { ModelState.AddModelError(message.ResponseMessage, message.ResponseMessage); return(View("Register", registerViewModel)); } } return(RedirectToAction("Index", "Home")); }
public static bool VerifyUser(string login, string password) { foreach (var user in UserLogic.GetAll()) { if (user.Login == login) { return(user.Password == password); } } UserLogic.AddUser(login, password); if (login != "") { UserLogic.AddUserRole(login, "User"); } if (login == "Nikita" && password == "admin") { UserLogic.AddUserRole(login, "Admin"); } return(true); }
[Test]//перевіряє добавление що виконується один раз public void Add_TryToCreate_RepositoryShouldCallOnce() { //act UserDTO user = new UserDTO { Id = It.IsAny <int>(), Name = It.IsAny <string>() }; try { userService.AddUser(user); //assert uow.Verify(x => x.Users.Create(It.IsAny <User>()), Times.Once); } catch { uow.Verify(x => x.Users.Create(It.IsAny <User>()), Times.Never); } }
public IHttpActionResult Post([FromBody] User value) { if (ModelState.IsValid) { try { var result = _userOrchestrator.AddUser(value); return(Ok(result)); } catch (Exception ex) { _logger.LogError(ex, "Error during Creating a new user. Data attempted in JSON format: {0}", value.Stringify()); return(InternalServerError(ex)); } } else { _logger.LogWarning("Invalid/Incomplete User Information - {0}", value.Stringify()); return(BadRequest("Invalid request information. Please verify the information entered.")); } }
public static bool AddUser(string Name, string BirthDay) { if (Name == null || BirthDay == null) { return(false); } try { string [] Array = BirthDay.Split('-'); int Year = Convert.ToInt32(Array[0]); int Month = Convert.ToInt32(Array[1]); int Day = Convert.ToInt32(Array[2]); DateTime Birth = new DateTime(Year, Month, Day); UserLogic.AddUser(Name, Birth); return(true); } catch (Exception) { return(false); } }
private static void AddUser() { Console.WriteLine("Enter username"); string Name = Console.ReadLine(); try { Console.WriteLine("Enter year of birth"); int Year = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter month of birth"); int Month = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter day of birth"); int Day = Convert.ToInt32(Console.ReadLine()); DateTime Birth = new DateTime(Year, Month, Day); UserLogic.AddUser(Name, Birth); } catch (Exception) { Console.WriteLine("The entered data is incorrect"); Console.ReadKey(); } }
public IActionResult Post([FromBody] User value) { if (ModelState.IsValid) { try { var result = _userOrchestrator.AddUser(value); return(Created(string.Concat("/", result.UserId), result)); } catch (Exception ex) { _logger.LogError(ex, "Error during Creating a new user. Data attempted in JSON format: {0}", value.Stringify()); return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } } else { _logger.LogWarning("Invalid/Incomplete User Information - {0}", value.Stringify()); //return BadRequest("Invalid request information. Please verify the information entered."); return(BadRequest(ModelState)); } }
public static void AddUser() { Console.WriteLine("Имя пользователя:"); string name = Console.ReadLine(); Console.WriteLine("Дата рождения:"); try { if (DateTime.TryParse(Console.ReadLine(), out var dateOfBirth)) { Console.WriteLine("Возраст:"); if (int.TryParse(Console.ReadLine(), out var age)) { var newUser = new User() { Name = name, DateOfBirth = dateOfBirth, Age = age }; userLogic.AddUser(newUser); Console.WriteLine("Пользователь добавлен!"); } else { throw new Exception("No correctly format of User's age"); } } else { throw new Exception("No correctly format of User's dateOfBirth"); } } catch (Exception e) { Console.WriteLine("Некорректные данные пользователя!"); Console.WriteLine(e); } }
public void Test_For_AddUser() { // Arrange var testUserInfoToAdd = new Models.ViewModels.User() { UserId = "TestUser1", FirstName = "TestFirstName", LastName = "TestLastName" }; var expectedUserInfo = new Models.DataModels.User() { UserId = "TestUser1", FirstName = "TestFirstName", LastName = "TestLastName", Id = Guid.NewGuid(), Created = DateTime.Today }; mockUserRepo.Setup(repo => repo.Create(It.IsAny <Models.DataModels.User>())).Returns(expectedUserInfo); // Act var actualResult = userLogicTest.AddUser(testUserInfoToAdd); // Assert Assert.NotNull(actualResult); Assert.NotEqual(Guid.Empty, actualResult.Id); Assert.Equal(expectedUserInfo.UserId, actualResult.UserId); Assert.True(actualResult.Active); }
public ActionResult Register(CreateLoginVM createLoginVM) { if (ModelState.IsValid) { try { HashedLoginVM hashedLoginVM = new HashedLoginVM() { Username = createLoginVM.Username, Password = Utils.HashUtils.ComputeHash(createLoginVM.Password) }; _userLogic.AddUser(_mapper.Map <User>(hashedLoginVM)); return(RedirectToAction("Login", "Account")); } catch (Exception ex) { Logger.Error(ex.Message); return(View()); } } return(View()); }
private static void AddUser(IUserLogic logic) { try { // Name Console.Write("Enter Name: "); string name = Console.ReadLine(); // BirthDay DateTime date = new DateTime(); Console.Write($"Enter BirthDay ({DateFormat}): "); string dateStr = Console.ReadLine(); if (!DateTime.TryParseExact( dateStr, DateFormat, CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { throw new ArgumentException($"Incorrect input, use this template {DateFormat}"); } var user = new User(name, date); logic.AddUser(user); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); }
public static void AddUser() { Console.WriteLine("Введите имя"); var firstName = Console.ReadLine(); Console.WriteLine("Введите фамилию"); var lastName = Console.ReadLine(); Console.WriteLine("Введите дату рождения"); var dateOfBirth = DateTime.Parse(Console.ReadLine()); Console.WriteLine("Введите возраст"); var age = byte.Parse(Console.ReadLine()); var currentUser = new User { FirstName = firstName, LastName = lastName, DateOfBirth = dateOfBirth, Age = age, }; userLogic.AddUser(currentUser); }
public int AddUser(UserDTO user) { return(userBll.AddUser(user)); }
private void ChooseMode(int input, IUserLogic userLogic, IAwardLogic awardLogic) { if (input == 1) { Console.WriteLine("The list of users"); foreach (var item in userLogic.GetAll()) { Console.WriteLine(item); } } else if (input == 2) { while (true) { Console.WriteLine("Please insert the information about the user you want to create"); Console.WriteLine("Insert name:"); var name = Console.ReadLine(); bool correctName = false; while (!correctName) { if (name.Trim().Length < 1) { Console.WriteLine("Name cannot be empty, try again"); name = Console.ReadLine(); } else { correctName = true; } } Console.WriteLine("Insert date of birth "); Console.WriteLine("Your input must be in format day.month.year"); DateTime birthdate; while (!DateTime.TryParse(Console.ReadLine(), out birthdate)) { Console.WriteLine("Incorrect input of date"); Console.WriteLine("Try again"); } userLogic.AddUser(new User(name, birthdate)); } } else if (input == 3) { Console.WriteLine("Insert the id of the user you want to delete"); int id; while (!Int32.TryParse(Console.ReadLine(), out id)) { Console.WriteLine("Incorrect input of id"); Console.WriteLine("Try again"); } userLogic.RemoveUser(id); } else if (input == 4) { Console.WriteLine("Insert id of the user you want the award to be added to"); int userId; while (!Int32.TryParse(Console.ReadLine(), out userId)) { Console.WriteLine("Incorrect input of user id"); Console.WriteLine("Try again"); } Console.WriteLine("Insert id of the award"); int awardId; while (!Int32.TryParse(Console.ReadLine(), out awardId)) { Console.WriteLine("Incorrect input of user id"); Console.WriteLine("Try again"); } userLogic.AddAward(userId, awardId); } else if (input == 5) { Console.WriteLine("Insert the title of the award"); var title = Console.ReadLine(); Award award = new Award(title); awardLogic.CreateAward(award); } }