public ActionResult Registration(UserViewModel model) { if (ModelState.IsValid) { var password = model.Password; var encryptedPassword = CustomEncrypt.Encrypt(password); using (var context = new MvcDbContext()) { var userAlreadyExists = context.Users.Any(usr => usr.Email == model.Email); if (userAlreadyExists) { return(RedirectToAction("Registration")); } Users user = context.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Name = model.Name; user.Country = model.Country; context.Users.Add(user); context.SaveChanges(); } return(RedirectToAction("Login", "Auth")); } ModelState.AddModelError("", "One or more fields are invalid"); return(View()); }
public ActionResult Create(NewUser newUser) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { string dateEdited = DateTime.Now.ToString("yyyy-MM-dd"); var encryptedPassword = CustomEncrypt.Encrypt(newUser.Password); var user = db.NewUsers.Create(); user.FirstName = newUser.FirstName; user.LastName = newUser.LastName; user.Email = newUser.Email; user.Password = encryptedPassword; user.DateEdited = dateEdited; db.NewUsers.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "Missing some field(s) value"); } return(RedirectToAction("Index")); }
public ActionResult Registration(Users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { var queryUser = db.Users.FirstOrDefault(u => u.Email == model.Email); if (queryUser == null) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Country = model.Country; user.Name = model.Name; db.Users.Add(user); db.SaveChanges(); } else { return(RedirectToAction("Registration")); } } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
public ActionResult Registration(users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { { var encryptedPassword = CustomEncrypt.Encrypt(model.PASSWORD); var user = db.users.Create(); user.USER_NO = model.USER_NO; user.USER_ID = model.USER_ID; user.PASSWORD = encryptedPassword; user.COUNTRY = model.COUNTRY; user.NAME = model.NAME; user.MAIL = model.MAIL; user.USER_STATUS = "A10"; db.users.Add(user); db.SaveChanges(); } return(RedirectToAction("Login", "auth")); } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
public static CaptchaModel GetCaptchaModel(string name) { var model = new CaptchaModel(); if (name != "") { model.ID = name; } else { model.ID = "captcha"; } // This Captcha code was extracted from: // http://www.stefanprodan.eu/2012/01/user-friendly-captcha-for-asp-net-mvc/ var rand = new Random((int)DateTime.Now.Ticks); // Generate new question int a = rand.Next(0, 9); int b = rand.Next(0, 9); int c = rand.Next(0, 9); int d = rand.Next(0, 9); int e = rand.Next(0, 9); var captcha = string.Format("{0} {1} {2} {3} {4}", a, b, c, d, e); using (var mem = new MemoryStream()) using (var bmp = new Bitmap(130, 30)) using (var gfx = Graphics.FromImage(bmp)) { gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; gfx.SmoothingMode = SmoothingMode.AntiAlias; gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height)); // Add noise int i, r, x, y; Pen pen = new Pen(Color.Yellow); for (i = 1; i < 10; i++) { pen.Color = Color.FromArgb((rand.Next(0, 255)), (rand.Next(0, 255)), (rand.Next(0, 255))); r = rand.Next(0, (130 / 3)); x = rand.Next(0, 130); y = rand.Next(0, 30); gfx.DrawEllipse(pen, x - r, y - r, r, r); } // Add question gfx.DrawString(captcha, new Font("Tahoma", 16), Brushes.Gray, 2, 3); // Render as Png bmp.Save(mem, ImageFormat.Png); model.Image = Convert.ToBase64String(mem.GetBuffer()); model.EncryptedValue = CustomEncrypt.Encrypt(captcha.Replace(" ", "")); } return(model); }
public ActionResult RegisterDonor(DonorRegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.AspNetUsers.FirstOrDefault(o => o.Email == user.Email) != null || db.Donors.FirstOrDefault(o => o.cnp == user.CNP) != null) { TempData["UserAlreadyExists"] = "This donor already exists"; return(View(user)); } var donor = new Donor(); donor.cnp = user.CNP; donor.firstName = user.firstName; donor.lastName = user.lastName; donor.birthDate = user.birthDate; donor.address = user.address; donor.email = user.Email; donor.phoneNumber = user.phoneNumber; if (donor.idBlood != 9) { donor.idBlood = user.idBlood; } db.Donors.Add(donor); var userDb = new AspNetUser(); userDb.Email = user.Email; userDb.Password = encryptedPassword; userDb.idRole = 1; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("Login", "Account")); } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult Register(RegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.Patients.Find(user.cardNumber) != null) { if (db.AspNetUsers.Any(o => o.cardNumber == user.cardNumber)) { TempData["UserAlreadyExists"] = "This user already exists"; return(View(user)); } var userDb = new AspNetUser(); userDb.cardNumber = user.cardNumber; userDb.Password = encryptedPassword; userDb.Email = db.Patients.Find(user.cardNumber).email; userDb.idRole = 4; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("LoginPatient", "Account")); } else { TempData["Error"] = "You entered a wrong health card number"; return(View(user)); } } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult RegisterCentreEmployee(CentreEmployeeRegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.AspNetUsers.Any(o => o.Email == user.Email)) { TempData["UserAlreadyExists"] = "This employee already exists"; return(View(user)); } var employee = new centerEmployee(); employee.firstName = user.firstName; employee.lastName = user.lastName; employee.email = user.Email; employee.idCenter = user.idCenter; db.centerEmployees.Add(employee); var userDb = new AspNetUser(); userDb.Email = user.Email; userDb.Password = encryptedPassword; userDb.idRole = 2; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("Login", "Account")); } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult Login(LoginViewModel user) { if (!ModelState.IsValid) { return(View()); } var emailCheck = db.AspNetUsers.FirstOrDefault(u => u.Email == user.Email && u.idRole != 4); if (emailCheck != null) { var getPassword = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Password); var materializePassword = getPassword.ToList(); var password = materializePassword[0]; var encryptedPass = CustomEncrypt.Encrypt(user.Password); if (encryptedPass == password) { var getEmail = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Email); var materializeEmail = getEmail.ToList(); var email = materializeEmail[0]; var idRole = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.idRole); var materializeRole = idRole.ToList(); var role = materializeRole[0]; var roleName = db.AspNetRoles.Find(role).Name.ToString(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Name, email), new Claim(ClaimTypes.Role, roleName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var accountManager = ctx.Authentication; accountManager.SignIn(identity); TempData["SuccessRegistration"] = "You signed in into your account as "; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The username or password is incorrect"); } } else { ModelState.AddModelError("", "The username or password is incorrect"); } return(View()); }
public bool CrearUsuario(string nombre, string ap, string am, string email, string ci, string userid, string password) { ctlPersonas persona = new ctlPersonas(); try { var personaid = persona.RegistrarPersona(nombre, ap, am, email, ci); using (var db = new DBServices.AccessDBContext()) { var persona_con_acceso = db.Personas_con_Accesos.Create(); persona_con_acceso.PersonaId = personaid; db.Personas_con_Accesos.Add(persona_con_acceso); db.SaveChanges(); if (persona_con_acceso.Id == 0) { throw new Exception("Error en asignacion de acceso..."); } var encryptedpassword = CustomEncrypt.Encrypt(password); var usuario = db.Usuarios.Create(); usuario.UserId = userid; usuario.Password = encryptedpassword; usuario.PersonaId = persona_con_acceso.Id; usuario.PermisoId = 1; db.Usuarios.Add(usuario); db.SaveChanges(); if (usuario.Id != 0) { return(true); } else { return(false); } } } catch (Exception e) { throw e; } finally { } }
public ActionResult Registration(UserViewModel uservm) { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(uservm.Password); using (var context = new MvcDbContext()) { var user = context.Users.Create(); user.Email = uservm.Email; user.Password = encryptedPassword; user.Country = uservm.Country; user.Name = uservm.Name; context.Users.Add(user); context.SaveChanges(); } } else { ModelState.AddModelError("", "One or more fields are invalid"); } return(View()); }
public ActionResult Registration(User model) { if (ModelState.IsValid) { using (var db = new OfferEntities1()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Country = model.Country; user.Name = model.Name; db.Users.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
public ActionResult Registration(Users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Name = model.Name; user.Country = model.Country; db.Users.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "Missing some field(s) value"); } return(View()); }
public ActionResult Registeration(User user) { if (!ModelState.IsValid) { return(View(user)); } user.PasswordHash = CustomEncrypt.Encrypt(user.PasswordHash); _context.Users.Add(user); _context.SaveChanges(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; authManager.SignIn(identity); return(RedirectToAction("Index", "Book")); }
public ActionResult Registration(User model) { if (ModelState.IsValid) { using (var db = new BettingSystemDbContext()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Username = model.Username; user.Password = encryptedPassword; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "One or more fields have been missing!"); } return(View()); }
//[Authorize(Roles = RoleNames.ROLE_ADMIN)] public ActionResult Registration(UserFullView ufv_cl) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { //Console.WriteLine(ufv_cl); string encryptedPassword_str = CustomEncrypt.Encrypt(ufv_cl.uli_cl.password); var applicationUser = db.applicationUser.Create(); applicationUser.Password = encryptedPassword_str; applicationUser.UserName = ufv_cl.uli_cl.username; applicationUser.UserFullName = ufv_cl.ubi_cl.userFullName; applicationUser.UserEmployer = ufv_cl.ubi_cl.clientBasicInfo.clientName; applicationUser.UserRole = ufv_cl.ubi_cl.lostAndFoundRoles.roleName; db.applicationUser.Add(applicationUser); db.SaveChanges(); } } return(RedirectToAction("Index", "Admin")); }
public static string Encrypt(string text) { return(CustomEncrypt.Encrypt(text)); }
public ActionResult Login(LoginViewModel user) { if (!ModelState.IsValid) { return(View(user)); } var emailCheck = db.AspNetUsers.FirstOrDefault(u => u.Email == user.Email); if (emailCheck != null) { var getPassword = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Password); var materializePassword = getPassword.ToList(); var password = materializePassword[0]; var encryptedPass = CustomEncrypt.Encrypt(user.Password); if (encryptedPass == password) { string name = ""; if (db.Donors.Any(d => d.email == user.Email) == true) { var getFirstName = db.Donors.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.Donors.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; name = "1" + firstName + " " + lastName; } else { if (db.Medics.Any(d => d.email == user.Email) == true) { var getFirstName = db.Medics.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.Medics.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; var getCentreId = db.Medics.Where(u => u.email == user.Email).Select(u => u.idHospital); var materId = getCentreId.ToList(); var centreID = materId[0]; name = centreID + firstName + " " + lastName; } else { if (db.centerEmployees.Any(d => d.email == user.Email) == true) { var getFirstName = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; var getCentreId = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.idCenter); var materId = getCentreId.ToList(); var centreID = materId[0]; name = centreID + firstName + " " + lastName; } else //role = admin { name = "1Admin"; } } } var getEmail = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Email); var materializeEmail = getEmail.ToList(); var email = materializeEmail[0]; var idRole = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.idRole); var materializeRole = idRole.ToList(); var role = materializeRole[0]; var roleName = db.AspNetRoles.Find(role).Name.ToString(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Role, roleName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var accountManager = ctx.Authentication; accountManager.SignIn(identity); TempData["SuccessRegistration"] = "You signed in into your account as "; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The password is incorrect"); } } else { ModelState.AddModelError("", "The email is incorrect"); } return(View(user)); }
public ActionResult LoginPatient(LoginPatientViewModel user) { if (!ModelState.IsValid) { return(View(user)); } var cardNumberCheck = db.AspNetUsers.FirstOrDefault(u => u.cardNumber == user.cardNumber); if (cardNumberCheck != null) { if (db.Patients.Find(user.cardNumber) != null) { var getName = db.Patients.Where(u => u.cardNumber == user.cardNumber).Select(u => u.firstName); var materName = getName.ToList(); var firstName = materName[0]; var getName1 = db.Patients.Where(u => u.cardNumber == user.cardNumber).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; var getPassword = db.AspNetUsers.Where(u => u.cardNumber == user.cardNumber).Select(u => u.Password); var materializePassword = getPassword.ToList(); var password = materializePassword[0]; var encryptedPass = CustomEncrypt.Encrypt(user.Password); if (encryptedPass == password) { var getId = db.AspNetUsers.Where(u => u.cardNumber == user.cardNumber).Select(u => u.Id); var materializeId = getId.ToList(); var id = materializeId[0]; var getCardNumber = db.AspNetUsers.Where(u => u.cardNumber == user.cardNumber).Select(u => u.cardNumber); var materializeEmail = getCardNumber.ToList(); var cardNumber = materializeEmail[0]; var idRole = db.AspNetUsers.Where(u => u.cardNumber == user.cardNumber).Select(u => u.idRole); var materializeRole = idRole.ToList(); var role = materializeRole[0]; var roleName = db.AspNetRoles.Find(role).Name.ToString(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, id.ToString()), new Claim(ClaimTypes.Name, firstName + " " + lastName), new Claim(ClaimTypes.Email, cardNumber), new Claim(ClaimTypes.Role, roleName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var accountManager = ctx.Authentication; accountManager.SignIn(identity); TempData["SuccessRegistration"] = "You signed in into your account as "; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The username or password is incorrect"); } } else { ModelState.AddModelError("", "The username or password is incorrect"); } } return(View(user)); }
public ActionResult Registration(RegistrationViewModel model, HttpPostedFileBase file1) { if (ModelState.IsValid) //check if fields empty/valid { try { using (var db = new MainDbContext()) { var emailCheck = db.Users.FirstOrDefault(u => u.Email == model.Email); if (emailCheck == null) //check if account with same email exsist. { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.FirstName = model.FirstName; user.LastName = model.LastName; user.Country = RegionInfo.CurrentRegion.DisplayName; //save user uploaded picture to the database as binary. byte[] imgByte = null; if (file1 != null && file1.ContentLength > 0) { MemoryStream target = new MemoryStream(); file1.InputStream.CopyTo(target); imgByte = target.ToArray(); user.DisplayPicture = imgByte; } else { user.DisplayPicture = imgByte; //set null } db.Users.Add(user); //add provided data to sample database db.SaveChanges(); TempData["msg-type"] = "alert-success"; TempData["msg-head"] = "Success"; TempData["msg-des"] = "Account created successfully!! Login from here."; return(RedirectToAction("Login", "Auth")); } TempData["msg-type"] = "alert-warning"; TempData["msg-head"] = "Warning"; TempData["msg-des"] = "Account already exist for this email!!"; return(View()); } } catch (ProviderIncompatibleException) { TempData["msg-type"] = "alert-danger"; TempData["msg-head"] = "Oh Snap!!"; TempData["msg-des"] = "Unable to create account!! Could not establish connection with server!!"; return(View(model)); } } TempData["msg-type"] = "alert-warning"; TempData["msg-head"] = "Warning"; TempData["msg-des"] = "Account creation was unsuccessful. Please correct the errors and try again!!"; return(View()); }
protected override void Seed(library_prototype.DAL.LibraryDbContext context) { var crypto = new SimpleCrypto.PBKDF2(); var encrypPass = crypto.Compute("rodnerraymundo"); string pin = RandomPassword.Generate(6, PasswordGroup.Lowercase, PasswordGroup.Lowercase, PasswordGroup.Numeric); var cryptoPin = new SimpleCrypto.PBKDF2(); var encrypPin = crypto.Compute(pin); var grades = new List <library_prototype.DAL.LibraryDbContext.GradesModel> { new library_prototype.DAL.LibraryDbContext.GradesModel { Grade = "Administrator", CreatedAt = DateTime.UtcNow, Sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel> { context.Sections.SingleOrDefault(s => s.Section == "Developer") } } }; grades.ForEach(g => context.Grades.AddOrUpdate(g)); var sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel> { new library_prototype.DAL.LibraryDbContext.SectionsModel { Section = "Developer", CreatedAt = DateTime.UtcNow, } }; sections.ForEach(s => context.Sections.AddOrUpdate(s)); var addresses = new List <library_prototype.DAL.LibraryDbContext.StudentAddressModel> { new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Lumang Dito", Address2 = "Banda Rito", City = "Pineapple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 1234 }, new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Matuwid na Daan", Address2 = "Pork Doon", City = "Apple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 5678 }, new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Dating Dito", Address2 = "Banda Doon", City = "Pineapple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 9012 } }; addresses.ForEach(a => context.StudentAddresses.AddOrUpdate(a)); context.SaveChanges(); var accounts = new List <library_prototype.DAL.LibraryDbContext.UserModel> { new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "administrator", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Rodner", MiddleInitial = "A", LastName = "Raymundo", Status = true, Birthday = DateTime.UtcNow.AddYears(-20), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 9012), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "staff", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Kevin", MiddleInitial = "G", LastName = "Tiu", Status = true, Birthday = DateTime.UtcNow.AddYears(-20), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 5678), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "student", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Jake", MiddleInitial = "S", LastName = "Arroyo", Status = true, Birthday = DateTime.UtcNow.AddYears(-15), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 1234), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, }; accounts.ForEach(a => context.Users.AddOrUpdate(a)); try { context.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } var publishers = new List <DAL.LibraryDbContext.PublisherModel> { new DAL.LibraryDbContext.PublisherModel { PublisherName = "Kewl Publisher", CreatedAt = DateTime.UtcNow, } }; publishers.ForEach(p => context.Publishers.AddOrUpdate(p)); var subjects = SubjectSeeder.Subject(); subjects.ForEach(s => context.Subjects.AddOrUpdate(s)); context.SaveChanges(); var books = new List <library_prototype.DAL.LibraryDbContext.BookModel> { new library_prototype.DAL.LibraryDbContext.BookModel { Title = "Discrete Mathematics for Kids", ISBN = "978-971-95546-0-8", Copyright = new DateTime(2012, 1, 1), NoOfPages = 215, Price = 165.00, Quantity = 2, Synopsis = "This book is for students who failed Discrete Mathematics", Borrow = true, CreatedAt = DateTime.UtcNow, Volume = "1", Subject = context.Subjects.SingleOrDefault(s => s.CallNo == 001), Publisher = context.Publishers.SingleOrDefault(p => p.PublisherName == "Kewl Publisher") } }; books.ForEach(b => context.Books.AddOrUpdate(b)); var authors = new List <library_prototype.DAL.LibraryDbContext.AuthorModel> { new library_prototype.DAL.LibraryDbContext.AuthorModel { LastName = "Gonzales", FirstName = "George", MiddleInitial = "A", } }; authors.ForEach(a => context.Authors.AddOrUpdate(a)); var booksauthors = new List <library_prototype.DAL.LibraryDbContext.BookAuthorModel> { new library_prototype.DAL.LibraryDbContext.BookAuthorModel { Book = context.Books.SingleOrDefault(b => b.Title == "Discrete Mathematics for Kids"), Author = context.Authors.SingleOrDefault(a => a.LastName == "Gonzales"), } }; booksauthors.ForEach(b => context.BooksAuthors.AddOrUpdate(b)); context.SaveChanges(); var emailCredential = new List <DAL.LibraryDbContext.EmailCredentialModel> { new DAL.LibraryDbContext.EmailCredentialModel { Host = "smtp.sendgrid.net", Username = "******", Password = CustomEncrypt.Encrypt("bg5PSAAPof9L2TW"), CreatedAt = DateTime.UtcNow, Deleted = false, EmailMessages = new List <DAL.LibraryDbContext.EmailMessageModel> { new DAL.LibraryDbContext.EmailMessageModel { Type = "notification", From = "*****@*****.**", Subject = "Book Deadline", Body = "This is a reminder that your borrowed book's deadline is coming near. We urge you to return the book on or before it's deadline. Thank you", CreatedAt = DateTime.UtcNow, Deleted = false, }, new DAL.LibraryDbContext.EmailMessageModel { Type = "accountpincode", From = "*****@*****.**", Subject = "Account Activation", Body = "You have received because you are registered at Santo Tomas de Villanueva Parochial School Web and Android Online Public Access Catalog System. Otherwise please disregard this email.", CreatedAt = DateTime.UtcNow, Deleted = false, } } } }; emailCredential.ForEach(e => context.EmailCredentials.AddOrUpdate(e)); context.SaveChanges(); /*var information = new List<library_prototype.DAL.LibraryDbContext.StudentModel> * { * new DAL.LibraryDbContext.StudentModel * { * FirstName = "Rodner", MiddleInitial = "Y", LastName = "Raymundo", Status = true, * ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", * } * }; * information.ForEach(i => context.Students.AddOrUpdate(i)); */ /* * var sections = new List<library_prototype.DAL.LibraryDbContext.SectionsModel> * { * new DAL.LibraryDbContext.SectionsModel * { * Section = "Administrator", CreatedAt = DateTime.UtcNow, * }, * * new DAL.LibraryDbContext.SectionsModel * { * Section = "Co-Administrator", CreatedAt = DateTime.UtcNow, * } * }; * var nonStudentGroup = context.Grades.FirstOrDefault(g => g.Grade == "Non-student"); * sections.ForEach(s => nonStudentGroup.Sections.Add(s)); * context.SaveChanges(); */ base.Seed(context); }
public ActionResult CreateUser([Bind(Exclude = "uniqueUserId")] UserInfo ui) { SetRolesForViewBag(); SetTypeOfActionWithRequestForm("Create"); if (!ModelState.IsValid) //Checks if input fields have the correct format { return(View(ui)); //Returns the view with the input values so that the user doesn't have to retype again } else { try { string decryptedPassword = CustomEncrypt.Encrypt(ui.userPwd); if (CheckIfSuchUserAlreadyExistsInDatabase(ui.userId, false) == true) { ModelState.AddModelError("userId", "Username must be unique"); return(View(ui)); } else { string uniqueEightDigitNumber = GenerateUniqueValues.ReturnUniqueEightDigitNumber(); string connectionStringCommon = CommonManager.ReturnNeededConnectionStringForCommonDatabase(); string sqlToCreateUser = @"INSERT INTO tblUser (userId, userPwd, userEmployer, userUniqueDatabaseId, ifRemoved) VALUES (@userId, @userPwd, @userEmployer, @userUniqueDatabaseId, @ifRemoved)"; using (SqlConnection conn = new SqlConnection(connectionStringCommon)) { conn.Open(); SqlCommand cmdToCreateUser = new SqlCommand(sqlToCreateUser, conn); cmdToCreateUser.Parameters.AddWithValue("@userId", ui.userId); cmdToCreateUser.Parameters.AddWithValue("@userPwd", decryptedPassword); cmdToCreateUser.Parameters.AddWithValue("@userEmployer", GetCurrentClaimValues.GetCurrentUserEmployer()); cmdToCreateUser.Parameters.AddWithValue("@userUniqueDatabaseId", uniqueEightDigitNumber); cmdToCreateUser.Parameters.AddWithValue("@ifRemoved", 0); cmdToCreateUser.ExecuteNonQuery(); } string connectionStringHotel = CommonManager.ReturnNeededConnectionStringForHotel(); string sqlToCreateInfoAboutUser = @"INSERT INTO tblUserInformation (userFullName, userType, userId, userUniqueDatabaseId, userEmail, userPhoneNumber, ifRemoved) VALUES (@userFullName, @userType, @userId, @userUniqueDatabaseId, @userEmail, @userPhoneNumber, @ifRemoved)"; using (SqlConnection conn = new SqlConnection(connectionStringHotel)) { conn.Open(); SqlCommand cmdToCreateMainUser = new SqlCommand(sqlToCreateInfoAboutUser, conn); cmdToCreateMainUser.Parameters.AddWithValue("@userId", ui.userId); cmdToCreateMainUser.Parameters.AddWithValue("@userFullName", ui.userFullName); cmdToCreateMainUser.Parameters.AddWithValue("@userType", ui.userType); cmdToCreateMainUser.Parameters.AddWithValue("@userUniqueDatabaseId", uniqueEightDigitNumber); cmdToCreateMainUser.Parameters.AddWithValue("@userEmail", ui.userEmail); cmdToCreateMainUser.Parameters.AddWithValue("@userPhoneNumber", ui.userPhoneNumber); cmdToCreateMainUser.Parameters.AddWithValue("@ifRemoved", 0); cmdToCreateMainUser.ExecuteNonQuery(); if (ui.userType == "Driver") { string sqlDriverAvailability = @"INSERT INTO tblDriverAvailability VALUES (@driverUniqueId, @driverAvailability)"; SqlCommand cmdToCreateDriverAvailability = new SqlCommand(sqlDriverAvailability, conn); cmdToCreateDriverAvailability.Parameters.AddWithValue("@driverUniqueId", uniqueEightDigitNumber); cmdToCreateDriverAvailability.Parameters.AddWithValue("@driverAvailability", true); cmdToCreateDriverAvailability.ExecuteNonQuery(); } } return(RedirectToAction("Index")); } } catch (Exception ex) { //Console.WriteLine(ex); return(HttpNotFound("Something went wrong. Please, contact the administration")); } } }
public ActionResult EditUser(UserInfo ui) { SetRolesForViewBag(); SetTypeOfActionWithRequestForm("Edit"); if (!ModelState.IsValid) //Checks if input fields have the correct format { return(View(ui)); //Returns the view with the input values so that the user doesn't have to retype again } try { if (CheckIfSuchUserAlreadyExistsInDatabase(ui.userId, true) == true) { ModelState.AddModelError("userId", "Username must be unique"); return(View(ui)); } else { string connectionStringCommon = CommonManager.ReturnNeededConnectionStringForCommonDatabase(); string decryptedPassword = CustomEncrypt.Encrypt(ui.userPwd); string sqlToUpdateInfoAboutUser = @"UPDATE tblUser SET userId=@userId, userPwd=@userPwd WHERE userUniqueDatabaseId = @userUniqueDatabaseId"; using (SqlConnection conn = new SqlConnection(connectionStringCommon)) { conn.Open(); SqlCommand cmdToUpdateInfoAboutUser = new SqlCommand(sqlToUpdateInfoAboutUser, conn); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userId", ui.userId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userPwd", decryptedPassword); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userUniqueDatabaseId", ui.uniqueUserId); cmdToUpdateInfoAboutUser.ExecuteNonQuery(); } string connectionStringHotel = CommonManager.ReturnNeededConnectionStringForHotel(); string sqlToUpdateMainInfoAboutUser = @"UPDATE tblUserInformation SET userType=@userType, userFullName=@userFullName, userEmail=@userEmail, userId=@userId, userPhoneNumber=@userPhoneNumber WHERE userUniqueDatabaseId = @userUniqueDatabaseId"; using (SqlConnection conn = new SqlConnection(connectionStringHotel)) { conn.Open(); SqlCommand cmdToUpdateInfoAboutUser = new SqlCommand(sqlToUpdateMainInfoAboutUser, conn); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userType", ui.userType); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userFullName", ui.userFullName); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userUniqueDatabaseId", ui.uniqueUserId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userEmail", ui.userEmail); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userId", ui.userId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userPhoneNumber", ui.userPhoneNumber); cmdToUpdateInfoAboutUser.ExecuteNonQuery(); } return(RedirectToAction("Index")); } } catch (Exception ex) { //Console.WriteLine(ex); return(HttpNotFound("Something went wrong. Please, contact the administration")); } }
public override void Add(User entity) { entity.Password = CustomEncrypt.Encrypt(entity.Password); base.Add(entity); }