/// <summary> /// パスワード生成 /// </summary> private void GetPassword() { try { int cnt = Common.ParseTextBox(passwordCount); int len = Common.ParseTextBox(passwordLength); var ins = new GeneratePassword(cnt, len); result.Text = ins.Execute(); } catch (FunctionException ex) { switch (ex.ErrorCode) { case GeneratePassword.PASSWORD_COUNT_NOT_INPUT: case GeneratePassword.PASSWORD_COUNT_OUT_OF_RANGE: break; case GeneratePassword.PASSWORD_LENGTH_NOT_INPUT: case GeneratePassword.PASSWORD_LENGTH_OUT_OF_RANGE: break; default: break; } ShowErrorMessage(ex.Message); return; } catch (Exception) { throw; } }
public IHttpActionResult GenerateDevicePassword(int DeviceId) { try { if (ModelState.IsValid) { var createpassword = new GeneratePassword(); var Password = GenerateRandomPassword(); createpassword.DeviceId = DeviceId; createpassword.Password = Password; db.GeneratePasswords.Add(createpassword); db.SaveChanges(); return(Ok(createpassword)); } else { return(Ok("Please Enter All the mandatory Fields")); } } catch (Exception ex) { return(NotFound()); } }
public IActionResult Save(MuseumVM museum) { if (!ModelState.IsValid) { museum.MuseumType = new SelectList(museumtypeRepository.GetMuseumTypes(), "Id", "Name").ToList(); return(View("Add", museum)); } UserAccounts u = new UserAccounts(); if (museum.PasswordHash == museum.PasswordSalt) { string password = museum.PasswordHash; u.PasswordSalt = GeneratePassword.GenerateSalt(); u.PasswordHash = GeneratePassword.GenerateHash(password, u.PasswordSalt); u.Username = museum.Username; u.RegistrationDate = DateTime.Now; u.Active = true; userRepository.InsertUser(u); museumRepository.Save(); Museums m = new Museums(); m.MuseumTypeId = museum.MuseumTypeId; m.Name = museum.Name; m.UserId = u.Id; museumRepository.InsertMuseum(m); museumRepository.Save(); } return(RedirectToAction("Index")); }
public void LoginCheck(LoginModel loginModel, GenericRepository <AM.Account> accountRepository, List <SubUserResponse> users) { if (string.IsNullOrEmpty(loginModel.Username) || string.IsNullOrEmpty(loginModel.Password)) { throw new ResponseValidationException(ResponseMessage.ToError("username and password is required.")); } var account = accountRepository.GetById(a => a.Username == loginModel.Username); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("username or Password is incorrect.")); } byte[] hashedPassword = GeneratePassword.HashedPassword(loginModel.Password, account.PasswordSalt); account = accountRepository.GetById(a => a.Username == loginModel.Username && a.Password == hashedPassword); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("username or Password is incorrect.")); } var user = users.Where(a => loginModel.Username.Equals(a.UserCode)).FirstOrDefault(); if (user == null) { throw new ResponseValidationException(ResponseMessage.ToError("username or Password is incorrect.")); } }
private static void PerformAction(int num) { switch (num) { case 1: var rest1 = new GenerateQuick(Program.user1); rest1.PerformAction(1); break; case 2: var rest2 = new GenerateRandom(); rest2.ShowResult(); break; case 3: var rest3 = new GeneratePassword(); rest3.ShowResult(); break; case 4: ExitApp(); break; default: Thread.Sleep(2000); System.Console.WriteLine("You've given wrong number..."); break; } }
public async Task <IActionResult> UserAdd() { var model = await _logonViewModelService.PrepareLogonModel(); model.Password = GeneratePassword.CreateRandomPassword(); return(View(model)); }
public ActionResult ForgotPassword(ForgotPasswordModel entity) { if (ModelState.IsValid) { var dao = new UserDao(); string newPass = GeneratePassword.Generate(); int check = dao.changePassword(entity.UserName, entity.Email, newPass); if (check == 1) { string content = "Mật khẩu mới của bạn là: <b>" + newPass + "</b>"; new MailHelper().SendEmail(entity.Email, "Mobile World - Quên mật khẩu", content); //ModelState.AddModelError("", "Mật khẩu mới đã được gửi vào email của bạn"); string message = "Mật khẩu mới đã được gửi vào email của bạn"; TempData["Message"] = message; return(RedirectToAction("index", "login")); } else if (check == -2) { ModelState.AddModelError("", "Email không đúng"); } else { ModelState.AddModelError("", "Tài khoản không đúng"); } } return(View("ForgotPassword")); }
public IActionResult Register(UserVM model) { if (!ModelState.IsValid) { return(View("Index", model)); } UserAccounts user = new UserAccounts(); user.Active = true; user.RegistrationDate = DateTime.Now; user.Username = model.Username; user.PasswordSalt = GeneratePassword.GenerateSalt(); user.PasswordHash = GeneratePassword.GenerateHash(model.Password, user.PasswordSalt); userRepository.InsertUser(user); userRepository.Save(); Clients client = new Clients(); client.Email = model.Email; client.FirstName = model.FirstName; client.LastName = model.LastName; client.UserId = user.Id; clientRepository.InsertClient(client); clientRepository.Save(); return(RedirectToAction("Index", "Autentification")); }
public Dictionary <int, string> AuthAccount(UserDTO userDTO) { Dictionary <int, string> result = new Dictionary <int, string>(); var user = _context.Users.SingleOrDefault(x => x.username == userDTO.username); if (user == null) { result.Add(0, ""); } else if (!user.email.Equals(userDTO.email)) { result.Add(-1, ""); } else { var password = GeneratePassword.Generate(); user.password = Hashing.HashPassword(password); try { _context.SaveChanges(); } catch (Exception) { result.Add(-2, ""); } result.Add(1, password); } return(result); }
void GetReferences() { generatePassword = FindObjectOfType <GeneratePassword>(); m_safeLocksScript = safeLogic.GetComponent <SafeLocks>(); m_hackingDocumentScript = ai.GetComponent <HackingDocuments>(); m_passwordSavingScript = gameObject.GetComponent <Passwords>(); }
public IActionResult Login(LoginVM login) { UserAccounts u = userRepository.GetUser(login.Username); string password; if (u == null) { TempData["Error"] = "You have entered an invalid username or password!"; return(RedirectToAction("Index", "Autentification")); } password = GeneratePassword.GenerateHash(login.Password, u.PasswordSalt); u = userRepository.GetUser(login.Username, password); if (u == null) { TempData["Error"] = "You have entered an invalid username or password!"; return(RedirectToAction("Index", "Autentification", login)); } HttpContext.SetLoggedUser(u, login.RememberPassword); return(RedirectToAction("Index", "Home", new { area = "" })); }
public AccountModel Create(AccountModel accountModel, IConfiguration configuration) { accountBusinessRules.CreateCheck(accountModel, unitOfWork.Account); accountModel.Password = GeneratePassword.CreateRandomPassword(); unitOfWork.Account.Insert(accountBuilder.Build(accountModel)); unitOfWork.Save(); SendCreateAccountEmail(accountModel, configuration); return(GetAccountByUsername(accountModel.Username)); }
public RarFile(string dirOfFile, string nameOfFile, bool isGeneratePasswd, int lengthOfPasswd, string setOfChar) { IsCompleted = false; UnrarObj = new Unrar(); IsGeneratePasswd = isGeneratePasswd; // Open archive for extraction UnrarObj.DestinationPath = @"E:\"; UnrarObj.Open(dirOfFile + nameOfFile, Unrar.OpenMode.Extract); PasswdList = new GeneratePassword(lengthOfPasswd, setOfChar); }
public UserModel ResetPassword(Guid forgotPasswordKey, string password) { accountBusinessRules.ResetPasswordCheck(forgotPasswordKey, unitOfWork.Account); var account = unitOfWork.Account.GetById(a => a.PasswordResetKey == forgotPasswordKey, "Organisation, Company, Role"); account.PasswordSalt = GeneratePassword.PasswordSalt(); account.Password = GeneratePassword.HashedPassword(password, account.PasswordSalt); unitOfWork.Account.Update(account); unitOfWork.Save(); return(accountBuilder.BuildToUserModel(account)); }
public UserModel ChangePassword(string username, string oldPassword, string password) { accountBusinessRules.ChangePasswordCheck(username, oldPassword, unitOfWork.Account); var account = unitOfWork.Account.GetById(a => a.Username == username, "Organisation, Company, Role"); account.PasswordSalt = GeneratePassword.PasswordSalt(); account.Password = GeneratePassword.HashedPassword(password, account.PasswordSalt); unitOfWork.Account.Update(account); unitOfWork.Save(); return(accountBuilder.BuildToUserModel(account)); }
public Response <SecurityUserDto> ChangePassword(string username, string oldPassword, string newPassword) { Response <SecurityUserDto> response = _SecurityUserBusinessRules.ChangePasswordPasswordCheck(username, oldPassword, newPassword); if (response.HasErrors) { return(response); } using (UnitOfWork unitOfWork = new UnitOfWork()) { SecurityUser securityUser = unitOfWork.SecurityUserRepository.GetEntities(s => s.UserName.ToLower() == username.ToLower(), null, "SecurityUserRoles").FirstOrDefault <SecurityUser>(); if (securityUser == null) { response.HasErrors = true; response.FieldErrors.Add(new FieldError() { FieldName = "Username", ErrorMessage = "Incorrect username." }); return(response); } byte[] hashedPassword = GeneratePassword.HashedPassword(oldPassword, securityUser.PasswordSalt); securityUser = unitOfWork.SecurityUserRepository.GetEntities(s => s.UserName.ToLower() == username.ToLower() && s.Password == hashedPassword, null, "SecurityUserRoles").FirstOrDefault <SecurityUser>();; if (securityUser == null) { response.HasErrors = true; response.FieldErrors.Add(new FieldError() { FieldName = "Password", ErrorMessage = "Incorrect password." }); return(response); } byte[] newHashedPassword = GeneratePassword.HashedPassword(newPassword, securityUser.PasswordSalt); securityUser.Password = newHashedPassword; securityUser.FirstTimeLogInInd = true; unitOfWork.SecurityUserRepository.Update(securityUser); unitOfWork.Save(); response.Model = _SecurityUserMapper.MapToSecurityUserDto(securityUser); } return(response); }
protected void RadButtonSend_Click(object sender, EventArgs e) { string userName = TextBoxUserName.Text; MembershipUser membershipUser = Membership.GetUser(userName); if (membershipUser != null) { String password = GeneratePassword.Generate(10, 10); membershipUser.ChangePassword(membershipUser.ResetPassword(), password); String emailTemplate = HttpContext.Current.Server.MapPath(Path.Combine(@"~\Files\EmailTemplates", "MailTemplateChangePasswordSuccesfull_eng.html")); StreamReader streamReader = new StreamReader(emailTemplate); String mailMessageBody = streamReader.ReadToEnd(); String fromEmailAddress; String subject; String toEmailAddress; mailMessageBody = EmailClass.GetMailParams(mailMessageBody, out fromEmailAddress, out toEmailAddress, out subject); mailMessageBody = mailMessageBody.Replace("{Username}", userName); mailMessageBody = mailMessageBody.Replace("{Password}", password); try { MailMessage mailMessage = new MailMessage(); mailMessage.IsBodyHtml = true; mailMessage.From = new MailAddress(fromEmailAddress); mailMessage.To.Add(userName); mailMessage.Subject = subject; mailMessage.Body = mailMessageBody; SmtpClient smtpClient = new SmtpClient(); smtpClient.Send(mailMessage); PanelForgetPassword.Visible = false; LiteralPasswordRequestSuccesfull.Visible = true; } catch (Exception ex) { // TODO: Create errorpage for user Response.Redirect("~/Pages/OrderSuccess.aspx"); } } else { LiteralUsernameNotFound.Visible = true; } }
public AM.Account MapFromRegisterModel(RegisterModel registerModel) { AM.Account account = new AM.Account(); account.Username = registerModel.EmailAddress; account.Firstname = registerModel.FirstName; account.LastName = registerModel.LastName; account.EmailAddress = registerModel.EmailAddress; account.CountryId = registerModel.CountryId; account.CreateDate = DateTime.Now; account.IsFirstTimeLogin = true; account.PasswordSalt = GeneratePassword.PasswordSalt(); account.Password = GeneratePassword.HashedPassword(registerModel.Password, account.PasswordSalt); return(account); }
static void Main(string[] args) { Dictionary <string, string> arguments = GetArguments(args); if (!(arguments.ContainsKey("-Length") && arguments.ContainsKey("-SpecialCharacters") && arguments.ContainsKey("-Numbers"))) { Console.WriteLine("USAGE: GeneratePasswordConsole -Length=<number> -SpecialCharacters=<number> -Numbers=<number> [-TransformVowels=<true/false>] [-NumberOfPasswords=<number>]"); } else { int length = int.Parse(arguments["-Length"]); int specialChars = int.Parse(arguments["-SpecialCharacters"]); int numbers = int.Parse(arguments["-Numbers"]); bool transform = false; if (arguments.ContainsKey("-TransformVowels")) { transform = bool.Parse(arguments["-TransformVowels"]); } int n = 1; if (arguments.ContainsKey("-NumberOfPasswords")) { n = int.Parse(arguments["-NumberOfPasswords"]); } Console.WriteLine("These are the passowrd generated:"); GeneratePassword passGen = new GeneratePassword(); List <string> generated = new List <string>(); for (int i = 0; i < n; i++) { string pass = passGen.Create(length, specialChars, numbers, transform); generated.Add(pass); Console.WriteLine(i + 1 + ": " + pass); } Console.WriteLine("Please type the number for the password you want to store in your clipboard:"); string store = Console.ReadLine(); string passToSave = generated[int.Parse(store) - 1]; Clipboard.SetText(passToSave); Console.WriteLine("Password " + passToSave + " saved to clipboard."); } Console.ReadLine(); }
public async Task <IActionResult> UserAdd(LogonModel model) { if (ModelState.IsValid) { var logonObj = _mapper.Map <Logon>(model); await _userService.InsertNewUser(logonObj); SuccessNotification("The user data has been saved successfully."); return(RedirectToAction("UserAdd")); } //If something failed redisplay form model = await _logonViewModelService.PrepareLogonModel(); model.Password = GeneratePassword.CreateRandomPassword(); return(View(model)); }
// // GET: /Login/ //public ActionResult Index() //{ // GeneratePassword password = new GeneratePassword(); // return View(password); //} public ActionResult Index(string name, string password) { GeneratePassword pass = new GeneratePassword(); if (name != null) { if (password == null) { pass.GeneratePass(name); } else { pass.Login(true, password); } } return(View(pass)); }
public void ChangePasswordCheck(string username, string oldPassword, AccountRepository accountRepository) { var account = accountRepository.GetById(a => a.Username == username); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("Password change failed, user does not exists.")); } byte[] hashedPassword = GeneratePassword.HashedPassword(oldPassword, account.PasswordSalt); account = accountRepository.GetById(a => a.Username == username && a.Password == hashedPassword); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("Password change failed, username or old password is incorrect.")); } }
public async Task <ActionResult> CreateUser(IPLBidder iplBidder) { iplBidder.password = GeneratePassword.CreateRandomPassword(8); iplBidder.roleID = (int)UserRoles.Bidder; int success = userDB.createUser(iplBidder, 1); if (success == 1) { // Task.Run(async () => SendEmail(iplBidder)); return(Json(new { data = new Result { Status = ResultStatus.Success, Message = "User registered successfully." } }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { data = new Result { Status = ResultStatus.Error, Message = "Error occurred while registering user." } }, JsonRequestBehavior.AllowGet)); } }
public IActionResult Edit(MuseumVM museum) { if (!ModelState.IsValid) { museum.MuseumType = new SelectList(museumtypeRepository.GetMuseumTypes(), "Id", "Name").ToList(); return(View("Edit", museum)); } UserAccounts u = userRepository.GetUserById(museum.UserId); if (museum.PasswordHash != null && museum.PasswordSalt != null) { if (museum.NewPassword == museum.RepeatPassword) { if (museum.NewPassword != null && museum.RepeatPassword != null) { string password = museum.NewPassword; u.PasswordSalt = GeneratePassword.GenerateSalt(); u.PasswordHash = GeneratePassword.GenerateHash(password, u.PasswordSalt); } else { u.PasswordHash = museum.PasswordHash; u.PasswordSalt = museum.PasswordSalt; } u.Username = museum.Username; userRepository.UpdateUser(u); museumRepository.Save(); Museums m = museumRepository.GetMuseum(museum.Id); m.MuseumTypeId = museum.MuseumTypeId; m.Name = museum.Name; m.UserId = u.Id; museumRepository.UpdateMuseum(m); museumRepository.Save(); } } return(RedirectToAction("Index")); }
public void ValidCreateUserTest() { SecurityUserDto securityUser = new SecurityUserDto() { Title = "Mr", FirstName = "Qinisela", LastName = "Molefe", Initials = "Q E", UserName = GeneratePassword.CreateRandomPassword(), PasswordSalt = GeneratePassword.PasswordSalt(), IDNumber = "8707255584080", CrudOperation = CrudOperations.Create }; securityUser.Password = GeneratePassword.HashedPassword("password1", securityUser.PasswordSalt); Response <SecurityUserDto> response = _PhekoServiceClient.SaveUser(securityUser); Assert.IsFalse(response.HasErrors); Assert.IsTrue(response.FieldErrors.Count == 0); Assert.IsNotNull(response.Model); }
public IActionResult UserEdit(UserAccounts user) { if (!ModelState.IsValid) { Administrators a = adminRepository.GetAdministrator(user.Id); return(View("Index", a)); } if (user.PasswordHash != null && user.PasswordSalt != null) { if (user.PasswordHash == user.PasswordSalt) { string password = user.PasswordHash; user.PasswordSalt = GeneratePassword.GenerateSalt(); user.PasswordHash = GeneratePassword.GenerateHash(password, user.PasswordSalt); userRepository.UpdateUser(user); userRepository.Save(); } } return(RedirectToAction("Profile", "User")); }
public Account Build(AccountModel accountModel) { Account account = new Account { Username = accountModel.Username, Firstname = accountModel.Firstname, Lastname = accountModel.Lastname, EmailAddress = accountModel.EmailAddress, ContactNumber = accountModel.ContactNumber, RoleId = accountModel.RoleId.Value, OrganisationId = accountModel.OrganisationId.Value, CompanyId = accountModel.CompanyId, CreateUserId = accountModel.CreateUserId, CreateDate = DateTime.Now, IsFirstTimeLogin = true, PasswordSalt = GeneratePassword.PasswordSalt() }; account.Password = GeneratePassword.HashedPassword(accountModel.Password, account.PasswordSalt); return(account); }
public void LoginCheck(LoginModel loginModel, AccountRepository accountRepository) { if (string.IsNullOrEmpty(loginModel.Username) || string.IsNullOrEmpty(loginModel.Password)) { throw new ResponseValidationException(ResponseMessage.ToError("Username and password is required.")); } var account = accountRepository.GetById(a => a.Username == loginModel.Username); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("Username or Password is incorrect.")); } byte[] hashedPassword = GeneratePassword.HashedPassword(loginModel.Password, account.PasswordSalt); account = accountRepository.GetById(a => a.Username == loginModel.Username && a.Password == hashedPassword); if (account == null) { throw new ResponseValidationException(ResponseMessage.ToError("Username or Password is incorrect.")); } }
public ActionResult Index([Bind(Exclude = "SCHOOL_ID")] ApplicationModel model) { //Thread.Sleep(5000); if (!ModelState.IsValid) { /* * TITLE PROVINCE */ IList <TB_M_PROVINCE> mProvinceLists = db.TB_M_PROVINCE.ToList <TB_M_PROVINCE>(); IEnumerable <SelectListItem> provinceLists = from s in mProvinceLists select new SelectListItem { Text = s.PROVINCE_NAME, Value = s.PROVINCE_ID.ToString() }; /* * SCHOOL TYPE */ List <RadioButtonModel> list = new List <RadioButtonModel>(); list.Add(new RadioButtonModel() { ID = 1, Name = Resources.Application.Application.SCHOOL_TYPE_01 }); //สพฐ list.Add(new RadioButtonModel() { ID = 2, Name = Resources.Application.Application.SCHOOL_TYPE_02 }); //เอกชน list.Add(new RadioButtonModel() { ID = 3, Name = Resources.Application.Application.SCHOOL_TYPE_03 }); //กทม list.Add(new RadioButtonModel() { ID = 4, Name = Resources.Application.Application.SCHOOL_TYPE_04 }); //อุดมศึกษา list.Add(new RadioButtonModel() { ID = 5, Name = Resources.Application.Application.SCHOOL_TYPE_OTHER }); //อื่น ๆ SelectList schoolTypes = new SelectList(list, "ID", "Name"); model.provinceLists = provinceLists; model.rSchoolTypes = schoolTypes; return(View(model)); } //using (ChinaPhet10Entities context = new ChinaPhet10Entities()) //{ //using (TransactionScope tran = new TransactionScope()) //{ try { //Check school duplicate var isExist = db.TB_APPLICATION_SCHOOL.Any(k => k.SCHOOL_EMAIL == model.school.SCHOOL_EMAIL); if (!isExist) { /* * SCHOOL MODEL */ CultureInfo ci = (CultureInfo)this.Session["PhetCulture"]; TB_APPLICATION application = db.TB_APPLICATION.FirstOrDefault(); //VALIDATE NULL VALUE model.school.SCHOOL_ADDR_PROVINCE = (model.SCHOOL_ADDR_PROVINCE == null) ? -1 : Convert.ToInt32(model.SCHOOL_ADDR_PROVINCE); model.school.SCHOOL_ADDR_AMPHUR = (model.SCHOOL_ADDR_AMPHUR == null) ? -1 : Convert.ToInt32(model.SCHOOL_ADDR_AMPHUR); model.school.SCHOOL_ADDR_TOMBON = (model.SCHOOL_ADDR_TOMBON == null) ? -1 : Convert.ToInt32(model.SCHOOL_ADDR_TOMBON); model.school.SCHOOL_ZONE_EDU = (model.school.SCHOOL_ZONE_EDU == null) ? "" : model.school.SCHOOL_ZONE_EDU; model.school.SCHOOL_ZONE = (model.school.SCHOOL_ZONE == null) ? "" : model.school.SCHOOL_ZONE; model.school.SCHOOL_TYPE_OTHER = (model.school.SCHOOL_TYPE_OTHER == null) ? "" : model.school.SCHOOL_TYPE_OTHER; model.school.SCHOOL_ADDR = (model.school.SCHOOL_ADDR == null) ? "" : model.school.SCHOOL_ADDR; model.school.SCHOOL_ADDR_SOI = (model.school.SCHOOL_ADDR_SOI == null) ? "" : model.school.SCHOOL_ADDR_SOI; model.school.SCHOOL_ADDR_ROAD = (model.school.SCHOOL_ADDR_ROAD == null) ? "" : model.school.SCHOOL_ADDR_ROAD; model.school.SCHOOL_ADDR_ZIPCODE = (model.school.SCHOOL_ADDR_ZIPCODE == null) ? "" : model.school.SCHOOL_ADDR_ZIPCODE; model.school.SCHOOL_ADDR_PHONE = (model.school.SCHOOL_ADDR_PHONE == null) ? "" : model.school.SCHOOL_ADDR_PHONE; model.school.SCHOOL_ADDR_FAX = (model.school.SCHOOL_ADDR_FAX == null) ? "" : model.school.SCHOOL_ADDR_FAX; model.school.SCHOOL_NAME = (model.school.SCHOOL_NAME == null) ? "" : model.school.SCHOOL_NAME; model.school.SCHOOL_PROVINCE = (model.school.SCHOOL_PROVINCE == null) ? -1 : model.school.SCHOOL_PROVINCE; model.school.SCHOOL_PASSWORD = (model.school.SCHOOL_PASSWORD == null) ? "" : model.school.SCHOOL_PASSWORD; model.school.SCHOOL_DOC_PATH = (model.school.SCHOOL_DOC_PATH == null) ? "" : model.school.SCHOOL_DOC_PATH; model.school.SCHOOL_REGISTER_DATE = (model.school.SCHOOL_REGISTER_DATE == null) ? DateTime.Now : model.school.SCHOOL_REGISTER_DATE; model.school.SCHOOL_EMAIL = (model.school.SCHOOL_EMAIL == null) ? "" : model.school.SCHOOL_EMAIL; model.school.SCHOOL_CULTURE = ci.Name; model.school.SCHOOL_ROUND = Convert.ToInt32(application.PROJECT_ROUND); model.school.SCHOOL_TYPE = (model.idSelectedSchoolType == null) ? "" : model.idSelectedSchoolType; model.school.SCHOOL_APPROVED_STATUS = 1; //Y=Approved,N=DisApproved /* generate password*/ String generatedPassword = GeneratePassword.Generate(8); model.school.SCHOOL_PASSWORD = generatedPassword; // MD5.md5(generatedPassword); db.TB_APPLICATION_SCHOOL.Add(model.school); db.SaveChanges(); /* * STAFF */ if (model.Staffs != null) { foreach (TB_APPLICATION_STAFF staff in model.Staffs) { ////VALIDATE NULL VALUE staff.STAFF_SCHOOL_ID = model.school.SCHOOL_ID; staff.STAFF_POSITION = (staff.STAFF_POSITION == null) ? 0 : staff.STAFF_POSITION; staff.STAFF_NAME = (staff.STAFF_NAME == null) ? "" : staff.STAFF_NAME; staff.STAFF_SURNAME = (staff.STAFF_SURNAME == null) ? "" : staff.STAFF_SURNAME; staff.STAFF_PHONE = (staff.STAFF_PHONE == null) ? "" : staff.STAFF_PHONE; staff.STAFF_TITLE_ID = (staff.STAFF_TITLE_ID == null) ? 0 : staff.STAFF_TITLE_ID; staff.STAFF_FOR_LEVEL = (staff.STAFF_FOR_LEVEL == null) ? 0 : staff.STAFF_FOR_LEVEL; if (!String.IsNullOrEmpty(staff.STAFF_NAME) && !String.IsNullOrEmpty(staff.STAFF_SURNAME)) { staff.STAFF_SCHOOL_ID = model.school.SCHOOL_ID; db.TB_APPLICATION_STAFF.Add(staff); } } } /* * STUDENT */ if (model.Students != null) { foreach (TB_APPLICATION_STUDENT student in model.Students) { //VALIDATE NULL VALUE student.STD_TITLE_ID = (student.STD_TITLE_ID == null) ? 0 : student.STD_TITLE_ID; student.STD_NAME = (student.STD_NAME == null) ? "" : student.STD_NAME; student.STD_SURNAME = (student.STD_SURNAME == null) ? "" : student.STD_SURNAME; student.STD_LEVEL_ID = (student.STD_LEVEL_ID == null) ? 0 : student.STD_LEVEL_ID; student.STD_SCHOOL_ID = model.school.SCHOOL_ID; student.STD_PICTURE_PATH = (student.STD_PICTURE_PATH == null) ? "" : student.STD_PICTURE_PATH; student.STD_PHONE = (student.STD_PHONE == null) ? "" : student.STD_PHONE; student.STD_EMAIL = (student.STD_EMAIL == null) ? "" : student.STD_EMAIL; student.STD_ID_CARD = (student.STD_ID_CARD == null) ? "" : student.STD_ID_CARD; student.STD_PASSPORT_ID = (student.STD_PASSPORT_ID == null) ? "" : student.STD_PASSPORT_ID; student.STD_GRADE = (student.STD_GRADE == null) ? 0 : student.STD_GRADE; student.STD_PHONE_PROVIDER = (student.STD_PHONE_PROVIDER == null) ? "" : student.STD_PHONE_PROVIDER; student.STD_APPROVED_STATUS = 1; student.STD_IS_CONCERN = "0"; student.STD_NATION = student.STD_NATION; student.STD_NATION_OTHER = student.STD_NATION_OTHER; #region "CONCERN STUDENT." bool isValidLevel = false; int currentYear = DateTime.Now.Year; if (!String.IsNullOrEmpty(student.STD_BIRTH_DAY)) { currentYear = currentYear - Convert.ToInt16(student.STD_BIRTH_DAY.Split('-')[0]); } if (currentYear <= 9) { if (student.STD_LEVEL_ID == 1) { isValidLevel = true;; } } else if (currentYear >= 10 && currentYear <= 12) { if (student.STD_LEVEL_ID == 2) { isValidLevel = true; } } else if (currentYear >= 13 && currentYear <= 15) { if (student.STD_LEVEL_ID == 3) { isValidLevel = true; } } else if (currentYear >= 16 && currentYear <= 18) { if (student.STD_LEVEL_ID == 4) { isValidLevel = true; } } else { if (student.STD_LEVEL_ID == 5) { isValidLevel = true; } } if (isValidLevel == false) { student.STD_IS_CONCERN = "1"; } #endregion if (!String.IsNullOrEmpty(student.STD_NAME) && !String.IsNullOrEmpty(student.STD_SURNAME)) { db.TB_APPLICATION_STUDENT.Add(student); } } } db.SaveChanges(); //tran.Complete(); /* send email school account to user*/ if (!String.IsNullOrEmpty(model.school.SCHOOL_EMAIL)) { if (Email.IsValidEmail(model.school.SCHOOL_EMAIL)) { Email.SendEmail(model.school, generatedPassword, ci.Name); } else { logger.Debug(model.school.SCHOOL_ID + "," + model.school.SCHOOL_NAME + "invalid email format."); } } else { logger.Debug(model.school.SCHOOL_ID + "," + model.school.SCHOOL_NAME + "no have email."); } } else { return(View("Exception")); } } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { errorMessage += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine; } } throw new Exception(errorMessage, dbEx); } //} //} ViewBag.UserName = model.school.SCHOOL_EMAIL; ViewBag.Password = model.school.SCHOOL_PASSWORD; ViewBag.PageContent = Resources.Application.Application.REGISTER_ITEM016; return(View("Complete")); }
private void generateButton_Click(object sender, EventArgs e) { GeneratePassword generatePassword = new GeneratePassword(); passwordBox.Text = generatePassword.GenerateToken(20); }