private void InitializeAppEnvironment() { //app environment configuration using (var db = new ApplicationDbContext()) { db.Database.CreateIfNotExists(); var roleStore = new RoleStore<IdentityRole>(db); var role = roleStore.FindByNameAsync("Admin").Result; if (role == null) { roleStore.CreateAsync(new IdentityRole("Admin")).Wait(); } var userStore = new UserStore<ApplicationUser>(db); var manager = new ApplicationUserManager(userStore); var admin = manager.FindByName("admin"); if (admin == null) { admin = new ApplicationUser { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, CreateDate = DateTime.Now }; var r = manager.CreateAsync(admin, "~Pwd123456").Result; } if (!manager.IsInRole(admin.Id, role.Name)) { manager.AddToRole(admin.Id, role.Name); } } }
public bool AddUserToRole(string userId, string roleName) { var um = new ApplicationUserManager( new UserStore<ApplicationUser>(context)); var idResult = um.AddToRole(userId, roleName); return idResult.Succeeded; }
public ActionResult ChangeRole( string id ) { Person p = db.Users.Where( pp => id == pp.Id ).FirstOrDefault(); var userManager = new ApplicationUserManager( new UserStore<Person>( db ) ); if( userManager.IsInRole( p.Id, "editor" ) ) { userManager.RemoveFromRole( p.Id, "editor" ); userManager.AddToRole( p.Id, "admin" ); } else if( userManager.IsInRole( p.Id, "admin" ) ) { userManager.RemoveFromRole( p.Id, "admin" ); userManager.AddToRole( p.Id, "user" ); } else { userManager.RemoveFromRole( p.Id, "user" ); userManager.AddToRole( p.Id, "editor" ); } db.SaveChanges(); return RedirectToAction( "AdminTable" ); }
internal static void Create(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("CreateAdmin.Create should not be being used in a production environment - security changes required"); #endif if (!context.Roles.Any()) { var roleStore = new RoleStore<AspNetRole,Guid,AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole,Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessAllData }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.AccessInstitution }; roleManager.Create(role); role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.SiteAdmin }; roleManager.Create(role); var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); foreach(var user in context.Users.Where(u=>u.Department.Institution.Name== "Starship").ToList()) { var result = userManager.AddPassword(userId: user.Id, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.AccessAllData); } else { throw new DbSeedException(result.Errors); } } } }
public static void SeedIdentityForEF(ApplicationDbContext context) { if ((!context.Roles.Any()) && (!context.Users.Any())) { var roleStore = new ApplicationRoleStore(context); //var roleManager = new RoleManager<ApplicationRole, int>(roleStore); var roleManager = new ApplicationRoleManager(roleStore); var role = new ApplicationRole { Name = "Admin", Description = "Super Admin User group" }; roleManager.Create(role); var userStore = new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context); var userManager = new ApplicationUserManager(userStore); var user = new ApplicationUser { Email = "*****@*****.**", UserName = "******", EmailConfirmed = true }; user.FirstName = "Jack"; user.LastName = "Smith"; userManager.Create(user, "P@ssword"); var result = userManager.SetLockoutEnabled(user.Id, false); userManager.AddToRole(user.Id, "Admin"); //added group manager var groupManager = new ApplicationGroupManager(roleManager,userManager); var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All"); groupManager.CreateGroup(newGroup); groupManager.SetUserGroups(user.Id, new int[] { newGroup.Id }); groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name }); } }
public void Configuration(IAppBuilder app) { var context = new ApplicationDbContext(); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); if (!RoleManager.RoleExists("Admin")) { RoleManager.Create(new IdentityRole("Admin")); RoleManager.Create(new IdentityRole("Teacher")); } if (UserManager.FindByName("*****@*****.**") == null) { var user = new ApplicationUser { Name = "管理员", UserName = "******", Email = "*****@*****.**" }; UserManager.Create(user, "administrator"); UserManager.AddToRole(UserManager.FindByName(user.UserName).Id, "Admin"); } ConfigureAuth(app); }
public void Post(RoleUsersDto dto) { var context = ApplicationDbContext.Create(); var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context)); if (!roleManager.RoleExists(dto.RoleName)) return; foreach ( var user in dto.UserNames.Select(userName => userManager.FindByName(userName)) .Where(user => user != null) .Where(user => !userManager.IsInRole(user.Id, dto.RoleName))) { userManager.AddToRole(user.Id, dto.RoleName); } foreach ( var user in dto.UserNames.Select(userName => userManager.FindByName(userName)) .Where(user => user != null) .Where(user => userManager.IsInRole(user.Id, dto.RoleName))) { userManager.RemoveFromRole(user.Id, dto.RoleName); } }
public void AssignRole(string userId, string roleName) { ApplicationUserManager.AddToRole(userId, roleName); }
protected override void Seed(RBACDbContext context) { //Create Default Roles... IList <ApplicationRole> defaultRoles = new List <ApplicationRole>(); defaultRoles.Add(new ApplicationRole { Name = c_SysAdmin, RoleDescription = "Allows system administration of Users/Roles/Permissions", LastModified = DateTime.Now, IsSysAdmin = true }); defaultRoles.Add(new ApplicationRole { Name = c_DefaultUser, RoleDescription = "Default role with limited permissions", LastModified = DateTime.Now, IsSysAdmin = false }); ApplicationRoleManager RoleManager = new ApplicationRoleManager(new ApplicationRoleStore(context)); foreach (ApplicationRole role in defaultRoles) { RoleManager.Create(role); } //Create User... var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", Firstname = "System", Lastname = "Administrator", LastModified = DateTime.Now, Inactive = false, EmailConfirmed = true }; ApplicationUserManager UserManager = new ApplicationUserManager(new ApplicationUserStore(context)); var result = UserManager.Create(user, "Pa55w0rd"); if (result.Succeeded) { //Add User to Admin Role... UserManager.AddToRole(user.Id, c_SysAdmin); } //Create Default User... user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", Firstname = "Default", Lastname = "User", LastModified = DateTime.Now, Inactive = false, EmailConfirmed = true }; result = UserManager.Create(user, "S4l3su53r"); if (result.Succeeded) { //Add User to Admin Role... UserManager.AddToRole(user.Id, c_DefaultUser); } //Create User with NO Roles... user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", Firstname = "Guest", Lastname = "User", LastModified = DateTime.Now, Inactive = false, EmailConfirmed = true }; result = UserManager.Create(user, "Gu3st12"); base.Seed(context); //Create a permission... PERMISSION _permission = new PERMISSION(); _permission.PermissionDescription = "Home-Reports"; ApplicationRoleManager.AddPermission(_permission); //Add Permission to DefaultUser Role... ApplicationRoleManager.AddPermission2Role(context.Roles.Where(p => p.Name == c_DefaultUser).First().Id, context.PERMISSIONS.First().PermissionId); }
public ActionResult Edit([Bind(Include = "UserId,Roles,UserName,Email")] UserEdit userEdit) { if (userEdit.UserId == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var user = _db.Users.Find(userEdit.UserId); if (user == null) { return HttpNotFound(); } if (!ModelState.IsValid) return View(userEdit); _userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); foreach (var role in userEdit.Roles) { if (role.IsChecked && !_userManager.IsInRole(user.Id, role.Name)) _userManager.AddToRole(user.Id, role.Name); if (!role.IsChecked && _userManager.IsInRole(user.Id, role.Name)) _userManager.RemoveFromRole(user.Id, role.Name); } _db.SaveChanges(); // This was intended to force roles to update without manual logout login, but for now it's more trouble than it's worth /*var authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);*/ return RedirectToAction("Index"); }
protected override void Seed(ApplicationDbContext context) { // To "seed" a database is to provide it with some initial data when the databse is created. #region Seed the security roles //Make the identit's BLL instance to help us manage roles var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); // The Rolemanager<T> and RoleStore<T> are BLL classes that give flexability to the design/structure of how we;re using Asp.Net Identity. //The IdentityRole is an Entity class that represents a securtiy role. // TODO: Move these hard-coded security roles to Web.config foreach (var role in DefaultSecurityRoles) { roleManager.Create(new IdentityRole { Name = role }); } #endregion #region Seed the users // Create an Admin user var adminUser = new ApplicationUser { //ToDO: Move hard-coded values to web.config UserName = AdminUserName, Email = AdminEmail, EmailConfirmed = true }; //Instantiate the BLL user manager var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); // - The aplicationUsermanager is a BLL class in this website's App_Start/IdeneityConfig.cs var result = userManager.Create(adminUser, AdminPassword); // TODO: Move password if (result.Succeeded) { //Get the Id that was generated for the user we created/added var adminId = userManager.FindByName(AdminUserName).Id; //Add the user to Administratiors role userManager.AddToRole(adminId, AdminRole); } //Create the other user accounts for all the people in my Demo database var demoManager = new DemoController(); var people = demoManager.ListPeople(); foreach (var person in people) { var user = new ApplicationUser { UserName = $"{person.FirstName}.{person.LastName}", Email = $"{person.FirstName}.{person.LastName}@DemoIsland.com", EmailConfirmed = true, PersonId = person.PersonID }; result = userManager.Create(user, TempPassword); if (result.Succeeded) { var userId = userManager.FindByName(user.UserName).Id; userManager.AddToRole(userId, UserRole); } } #endregion // Note: keep this call to the case class so it can do its seeding work base.Seed(context); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, "Client"); Client client = new Client(); client.Client_ID = user.Id; //client.user_name = model.user_name; client.Client_Email = model.Email; client.ClientCat_ID = 1; Spins spin = new Spins(); spin.Client_ID = user.Id; db.Spins.Add(spin); db.Clients.Add(client); db.SaveChanges(); #region MailCreate string body = "Good Day" + "<br/>" + "<br/>" + "<h3>Thank You For Registering At Messanger King.. </h3>" + "<br/>" + "<br/>" + "<h4>Please Update Your Personal Details if You Have Not Already <br/> As Soon As You Have Done This You May Make A Booking With Us </h4>" + "<br/>" + "<br/>" + "<br/>" + "Regards, " + "<br/>" + "Messenger Kings Courier Management"; GmailClass gm = new GmailClass(); gm.Gmail("Messanger King ~ Account Creation", body, model.Email);; #endregion MailCreate await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Edit", "Clients", new { ID = client.Client_ID })); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public bool AddUserToRole(ApplicationUserManager userManager, string userId, string roleId) { var idResult = userManager.AddToRole(userId, roleId); return idResult.Succeeded; }
protected override void Seed(ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <ApplicationRole>(new RoleStore <ApplicationRole>(context)); // создаем две роли var adminrole = new ApplicationRole { Name = "admin" }; var userrole = new ApplicationRole { Name = "user" }; var googlerole = new ApplicationRole { Name = "google" }; var yandexrole = new ApplicationRole { Name = "yandex" }; var gmailrole = new ApplicationRole { Name = "gmail" }; // добавляем роли в бд roleManager.Create(adminrole); roleManager.Create(userrole); roleManager.Create(googlerole); roleManager.Create(yandexrole); roleManager.Create(gmailrole); //roleManager.CreateAsync(new ApplicationRole //{ // Name = "admin" //}); //roleManager.CreateAsync(new ApplicationRole //{ // Name = "user" //}); //roleManager.CreateAsync(new ApplicationRole //{ // Name = "google" //}); //roleManager.CreateAsync(new ApplicationRole //{ // Name = "yandex" //}); //roleManager.CreateAsync(new ApplicationRole //{ // Name = "gmail" //}); // создаем пользователей var defaultadmin = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var defaultuser = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password1 = "ad46D_ewr3W"; var result = userManager.Create(defaultadmin, password); var result2 = userManager.Create(defaultuser, password1); // если создание пользователя прошло успешно if (result.Succeeded && result2.Succeeded) { // добавляем для пользователя роль userManager.AddToRole(defaultadmin.Id, adminrole.Name); userManager.AddToRole(defaultadmin.Id, userrole.Name); userManager.AddToRole(defaultuser.Id, userrole.Name); } base.Seed(context); }
public ActionResult UserEdit(UserViewModel model) { if (ModelState.IsValid) { //userManager = new ApplicationUserManager(new ApplicationUserStore(identityDb)); userManager = new ApplicationUserManager(new ApplicationUserStore(identityDb)); var currentUser = identityDb.Users.Find(model.UserId); var currentRoles = currentUser.Roles; var currentRoleIds = currentRoles.Select(r => r.RoleId); var selectedRoles = new HashSet<int>(); if (model.SelectedRoles != null) selectedRoles = new HashSet<int>(model.SelectedRoles); foreach (var role in identityDb.Roles.ToList()) { if (currentRoleIds.Contains(role.Id) && !selectedRoles.Contains(role.Id)) { userManager.RemoveFromRole(currentUser.Id, role.Name); } else if (!currentRoleIds.Contains(role.Id) && selectedRoles.Contains(role.Id)) { userManager.AddToRole(currentUser.Id, role.Name); } } return RedirectToAction("Users"); } return View(model); }
public ActionResult RoleAddToUser(string UserName, string RoleName) { ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); try { manager.AddToRole(user.Id, RoleName); TempData["ValidationMessage"] = ("Success: " + " " + UserName + " " + "Was Added to the " + " " + RoleName + " " + "Role"); } catch { TempData["ValidationMessage"] = ("Error: " + " " + UserName + " " + "Was Not Successfully Added to the " + " " + RoleName + " " + "Role"); } var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.Roles = list; return View("ManageRole"); }
private static void SeedUsers(ApplicationDbContext context) { var usersCount = 50; if (!context.Roles.Any(r => r.Name == "Admin")) { var store = new RoleStore<IdentityRole>(context); var manager = new RoleManager<IdentityRole>(store); var role = new IdentityRole { Name = "Admin" }; manager.Create(role); } if (!context.Users.Any(u => u.UserName == "*****@*****.**")) { var store = new UserStore<ApplicationUser>(context); var manager = new ApplicationUserManager(store); var user = new ApplicationUser { Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("admin"), SecurityStamp = Guid.NewGuid().ToString(), FirstName = "Pe6o admina", LastName = "Adminov", GSM = "99 999 999" }; context.Users.AddOrUpdate(user); context.SaveChanges(); manager.AddToRole(user.Id, "Admin"); } if (context.Users.Count() <= 1) { var random = new Random(); for (int i = 1; i <= usersCount; i++) { var user = new ApplicationUser() { UserName = $"u{i}@site.com", Email = $"u{i}@site.com", PasswordHash = new PasswordHasher().HashPassword($"u{i}"), SecurityStamp = Guid.NewGuid().ToString(), FirstName = Names[random.Next(0, Names.Length)], LastName = Names[random.Next(0, Names.Length)], GSM = random.Next(100000000, 999999999).ToString() }; context.Users.AddOrUpdate(user); } context.SaveChanges(); } }
public ActionResult CreatePatient(CreatePatientViewModel model) { ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); Physician physician = _physicianService.GetPhysician(user.PhysicianId); // Conversions from the model int race = (int)Enum.Parse(typeof(PatientRace), model.Race);//convert.GenderRaceStringToInt(model.Race); int gender = (int)Enum.Parse(typeof(PatientGender), model.Gender);//convert.PatientGenderStringToInt(model.Gender); int ethnicity = (int)Enum.Parse(typeof(PatientEthnicity), model.Ethnicity);// convert.PatientEthnicityStringToInt(model.Ethnicity); // Check if the user is already in the database. if (UserIsInDatabase(model.Username)) { // User is already in the database // Display an error and request the physician to enter in a different username. ModelState.Clear(); ModelState.AddModelError("UsernameExistsError", "Username already exists."); } else { // User is not in the database. // Proceed to add the user to the database. Patient patient = new Patient(); patient.Birthdate = DateTime.Parse(model.Birthdate); //model.Birthdate; // Need to fix this, temporarily putting in 0. patient.Height = (int)model.Height; patient.Weight = (int)model.Weight; patient.Location = (int)Enum.Parse(typeof(Location), model.Location);//model.Location; // Need to fix this. temporarily putting in 12. patient.Ethnicity = ethnicity; patient.Gender = gender; patient.Race = race; patient.Physician = physician; var newUser = new ApplicationUser { UserName = model.Username, Status = (int)Account_Status.Active }; if ((newUser != null) && (model.Password != null)) { //Create a new context to change the user creation validation rules for the patient only. using (ApplicationDbContext context = new ApplicationDbContext()) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); // This user validator is being created only to remove email as a required field for creating a user. // The email field in the AspNetUsers table is nullable and our requirments state that a patient does not // have an email address so in order to satisfy that requiremnt we need to remove the required email // parameter on user creation validation. manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = false }; var result = manager.Create(newUser, model.Password); if (result.Succeeded) { // User added to database successfully. _patientService.CreatePatient(patient); _patientService.SaveChanges(); newUser.PatientId = patient.Id; result = manager.Update(newUser); //Role must match what is found in the database AspNetRoles table. result = manager.AddToRole(newUser.Id, "Patient"); physician.Patients.Add(patient); _physicianService.UpdatePhysician(physician); _physicianService.SaveChanges(); } else { // User failed to add. ModelState.Clear(); foreach (string error in result.Errors) { ModelState.AddModelError("ResultError", error); } return View(model); } } } else { // Username or password was null if we got here. } } return View(model); }
public async Task<ActionResult> Create(SupplierViewModel model, FormCollection collect) { #region Cathing model errors var error = ModelState.Values.SelectMany(e => e.Errors); var errors = ModelState .Where(x => x.Value.Errors.Count > 0) .Select(x => new { x.Key, x.Value.Errors }) .ToArray(); #endregion #region Prep Utilities SupplierContext dataSocket = new SupplierContext(); ApplicationDbContext context = new ApplicationDbContext(); var roleStore = new RoleStore<IdentityRole>(context); UserStore<ApplicationUser> myStore = new UserStore<ApplicationUser>(context); ApplicationUserManager userMgr = new ApplicationUserManager(myStore); var roleManager = new RoleManager<IdentityRole>(roleStore); #endregion #region Bend the rules try { if(collect.GetValue("SupplierType").AttemptedValue == "0") { /*Book Supplier*/ model.RegisterNewSupplier.SupplierType = true; } else if (collect.GetValue("SupplierType").AttemptedValue == "1") { /*Technology Supplier*/ model.RegisterNewSupplier.SupplierType = false; } if (ModelState.ContainsKey("SupplierType")) ModelState["SupplierType"].Errors.Clear(); } catch { ModelState.AddModelError("SupplierType", "Please select a valid supplier type from dropdown !"); } #endregion try { if (ModelState.IsValid) { #region Register Supplier var user = new ApplicationUser() { UserName = model.RegisterNewSupplier.Email, Email = model.RegisterNewSupplier.Email, Address = model.RegisterNewSupplier.Address, PhoneNumber = model.RegisterNewSupplier.ContactPersonNumber }; Models.Supplier supplier = new Models.Supplier { Name = model.RegisterNewSupplier.Name, ContactPerson = model.RegisterNewSupplier.ContactPerson, Fax = model.RegisterNewSupplier.Fax, ContactPersonNumber = model.RegisterNewSupplier.ContactPersonNumber, LastName = model.RegisterNewSupplier.LastName, User_Id = user.Id, IsBookSupplier = model.RegisterNewSupplier.SupplierType }; user.Carts = new Cart { DateLastModified = DateTime.Now }; user.Wishlists = new Wishlist { Status = false }; IdentityResult result = await userMgr.CreateAsync(user, model.RegisterNewSupplier.Password); roleManager.Create(new IdentityRole { Name = "supplier" }); userMgr.AddToRole(user.Id, "supplier"); //dataSocket.Suppliers.Add(supplier); dataSocket.Suppliers.Add(supplier); dataSocket.SaveChanges(); #endregion return RedirectToAction("Index", "Admin", null); } #region Set Up dropdown model.SupplierType = new List<SelectListItem>(); model.SupplierType.Add( new SelectListItem { Text = "Please Select Supplier Type", Value = "", Selected = true } ); model.SupplierType.Add( new SelectListItem { Text = "Book Supplier", Value = "0" } ); model.SupplierType.Add( new SelectListItem { Text = "Technology Supplier", Value = "1" } ); ViewData["SupplierType"] = model.SupplierType; #endregion return View(model); } catch { #region Set Up dropdown model.SupplierType = new List<SelectListItem>(); model.SupplierType.Add( new SelectListItem { Text = "Please Select Supplier Type", Value = "", Selected = true } ); model.SupplierType.Add( new SelectListItem { Text = "Book Supplier", Value = "0" } ); model.SupplierType.Add( new SelectListItem { Text = "Technology Supplier", Value = "1" } ); ViewData["SupplierType"] = model.SupplierType; #endregion return View(model); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // check to see if this user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { // this requires the user to use the same password as the one in the internal database var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); var user = new ApplicationUser { // populate these fields with wxisting data from oldUser GivenName = oldUser.FirstName, FamilyName = oldUser.LastName, PersonID = oldUser.PersonID, // populate these fields normally UserName = model.Email, Email = model.Email }; // create the user with the Identity system UserManager normally var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // use the oldUser.Roles list to add the internally assigned roles to the user foreach (var role in oldUser.Roles) { UserManager.AddToRole(user.Id, role); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } else // not an existing user, create a user withou { var user = new ApplicationUser { // We will uncomment the following two lines later, once our ViewModel and // our View are updated to ask for them: GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // my code var dbUser = new DataObjects.User { FirstName = model.GivenName, LastName = model.FamilyName, Email = model.Email }; usrMgr.AddNewlyRegisteredUser(dbUser, model.Password); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } } catch { // creating old user failed, probably because AuthenticateUser failed return(View(model)); } } // modelstate was not valid return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //prevent user from being signed in automatically, before validation //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); var roleResult = UserManager.AddToRole(user.Id, "USER"); //use own email confirmation method //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); //account created properly, register a user object var suser = new User { Id = Guid.NewGuid().ToString(), AetherAmount = 0, VaporAmount = 10, Avatar = "null", ProfileText = "I'm new here!", UserHandle = "myUserName", UserID = user.Id, Created = DateTime.Now, LastHere = DateTime.Now }; db.Users.Add(suser); db.SaveChanges(); //TODO: do some custom magic and set a userhandle, etc. //USE MAILGUN HTTP API INSTEAD var client = new RestClient(); client.BaseUrl = new Uri("https://api.mailgun.net/v3"); client.Authenticator = new HttpBasicAuthenticator("api", ConfigurationManager.AppSettings["MailgunSecret"].ToString()); var request = new RestRequest(); request.Method = Method.POST; request.Resource = ConfigurationManager.AppSettings["MailgunDomain"].ToString() + "/messages"; //PARAMETERS request.AddParameter("from", "*****@*****.**"); request.AddParameter("to", user.Email); request.AddParameter("subject", "Sea Waves Compo Confirmation"); request.AddParameter("html", string.Format( "<html>Thanks for registering! To complete the registeration, please click here:" + "<a href=\"{0}\" title=\"confirm email\">{0}</a></html>", Url.Action("ConfirmEmail", "Account", new { userid = user.Id, code = code }, Request.Url.Scheme))); try { client.ExecuteAsync(request, response => { if (response.StatusCode == HttpStatusCode.OK) { //OK, continue Console.WriteLine("sent email to new user: "******"something terrible happened. please contact admin" })); return(View(model)); } return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private static User SeedApplicationUser(DbContext dbContext) { const string email = "*****@*****.**"; const string password = "******"; var userManager = new ApplicationUserManager(new UserStore<User>(dbContext)); userManager.UserValidator = new UserValidator<User>(userManager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; userManager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; var user = new User { Email = email, UserName = email, FirstName = "John", LastName = "Doe" }; var result = userManager.Create(user, password); if (!result.Succeeded) return null; userManager.AddToRole(user.Id, "Admin"); return user; }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var user = await UserManager.FindAsync(model.Email, model.Password); if (user != null && !user.EmailConfirmed) { return(RedirectToAction("ConfirmAccount", new { email = model.Email })); } else { bool changed = false; if (user != null && user.Roles.Count > 1) { changed = true; UserManager.RemoveFromRole(user.Id, "Teacher"); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); if (result == SignInStatus.Success) { if (changed) { UserManager.AddToRole(user.Id, "Teacher"); return(RedirectToAction("SelectRole")); } var userInfo = new UserProfile(user.Id); if (userInfo.Id == null) { return(RedirectToAction("ProfileInfo", "Manage")); } else { return(RedirectToAction("Index", "Home")); } } else { switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } } } }
public ActionResult RoleAddToUser(string UserName, string RoleName) { ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); //var account = new AccountController(new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()))); UserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext())); UserManager.AddToRole(user.Id, RoleName); ViewBag.ResultMessage = "Role created successfully !"; // prepopulat roles for the view dropdown var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.Roles = list; // populate userlist var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu => new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList(); ViewBag.UserList = userlist; return View("ManageUserRoles"); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // check to see if this user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); var user = new ApplicationUser { GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { string role = oldUser.Role; UserManager.AddToRole(user.Id, role); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } else // not an existing user, create a user without roles { var user = new ApplicationUser { GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } } catch (Exception ex) { // creating old user failed ViewBag.Error = ex.Message + " " + ex.Source; return(View(model)); } } // modelstate was not valid return(View(model)); }
protected override void Seed(ApplicationContext _context) { var careers = new List <tblCareer> { new tblCareer { Name = "Head Teacher", Salary = 20, Description = "Responsibilities: planning and organization of the educational process (drawing up curricula, timetables, load distribution)quality control of the educational processtraining, adaptation, assessment and organization of teachers' workorganization and control of student progress and attendance." }, new tblCareer { Name = "School cook", Salary = 250, Description = "Responsibilities: to be a team player, part of our team.Great desire to develop in this direction.Preparation of dishes and preparations according to the calculation, production technology and time standards in the Eurasia network.Maintaining cleanliness and order in the workplace in accordance with approved standards." }, new tblCareer { Name = "Watcher", Salary = 150, Description = "Responsibilities: checkpoint mode, ability to communicate, react quickly, think positively :) age is not an obstacle to the desire to work" }, new tblCareer { Name = "Scrubwoman", Salary = 175, Description = "Responsibilities: tidy up and clean up and clean it up in a proper sanitary camp, anchored in the back room - one room, wipe it down for a day (the robot is not folding, it’s clean in the back room, the school is okay, it’s good enough for the client company)" } }; var gallary = new List <tblGallary> { new tblGallary { Description = "Our way in choosing professions", ImageLink = "http://rgg.rv.ua/menu-gimnasium/menu-foto/m-2019-2020/vesna-2019-2020/image?view=image&format=raw&type=img&id=1996" }, new tblGallary { Description = "Spring battles", ImageLink = "http://rgg.rv.ua/images/joomgallery/thumbnails/fotogalery_2/2019-2020_42/vesna_45/foto_20200311_1368832781.jpeg" }, new tblGallary { Description = "Adolescent nutrition: useful, tasty, affordable", ImageLink = "http://rgg.rv.ua/menu-gimnasium/menu-foto/m-2019-2020/vesna-2019-2020" }, new tblGallary { Description = "Holly winter", ImageLink = "http://rgg.rv.ua/menu-gimnasium/menu-foto/m-2019-2020/m-zuma-2019-2020/image?view=image&format=raw&type=img&id=1982" }, new tblGallary { Description = "The future of Ukraine is for healthy youth!", ImageLink = "http://rgg.rv.ua/menu-gimnasium/menu-foto/m-2019-2020/m-zuma-2019-2020/image?view=image&format=raw&type=img&id=1960" }, new tblGallary { Description = "Sports and intellectual relay 'Healthy to be fashionable and modern'", ImageLink = "http://rgg.rv.ua/menu-gimnasium/menu-foto/m-2019-2020/m-zuma-2019-2020/image?view=image&format=raw&type=img&id=1956" } }; var news = new List <tblNews> { new tblNews { Title = "WARNING! WARNING!", Description = "If you know how to organize both your own work and cooperation with peers, are responsible for the work started, cultivate principles, initiative, organizational, communicative and moral qualities, are a student of 8-10 grades - we invite you to become a candidate for the position of Head of Student Government . Voting for the candidates for the Chairman of the Student Self-Government will take place at the reporting and election student conference, which will take place on September 15 at 2:45 p.m. in the assembly hall of the gymnasium. Applications from candidates should be submitted by September 11 to the office of the teacher-organizer.", DatePost = "07/09/2020", LinkImage = "http://rgg.rv.ua/images/joomgallery/details/zagalna_8/2017_26/foto_20200907_1929489264.jpg" }, new tblNews { Title = "Forward, to new accomplishments and knowledge!", Description = "After the summer holidays, on the first day of autumn, all schools in our country meet their students to start another school year. September 1 is a meeting with school, teachers, friends and of course the holiday of the 'First Bell'.", DatePost = "01/09/2020", LinkImage = "http://rgg.rv.ua/images/joomgallery/details/fotogalery_2/2020-2021_47/osin_48/foto_20200901_1171322660.jpg" }, new tblNews { Title = "WARNING! WARNING!", Description = "Dear high school family! There is one day left until the start of the new school year. Tomorrow, September 1, students across Ukraine will go to study in the new conditions, adhering to all anti-epidemic measures. So on the eve of the start of training, we offer you to watch a motivational video dedicated to the beginning of the new school year.", DatePost = "31/08/2020", LinkImage = "http://rgg.rv.ua/images/joomgallery/details/zagalna_8/2017_26/foto_20200831_1768936510.jpg" }, new tblNews { Title = "Implementation of the GSuite system", Description = "Шановні вчителі. В нашій гімназії проходить впровадження в навчальний процес системи GSuite. Протягом 27 серпня, перейдіть за посиланням та вкажіть ваше прізвище та ім'я англійською мовою, так як ви вважаєте є правильним. Дана інформація буде використовуватись під час реєстрації вашого корпоративного облікового запису GSuite.", DatePost = "26/08/2020", LinkImage = "http://rgg.rv.ua/images/joomgallery/details/zagalna_8/2017_26/foto_20200831_1768936510.jpg" } }; var schedule = new List <tblSchedule> { new tblSchedule { SubjectName = "Maths", TeacherName = "Makarchuk Zoya Vladimirovna", DayWeek = "Moday", StartTime = "11:00", EndTime = "11:40" }, new tblSchedule { SubjectName = "World Literature", TeacherName = "Ordynska Vira Hryhorivna", DayWeek = "Moday", StartTime = "12:00", EndTime = "12:40" }, new tblSchedule { SubjectName = "Labor training and technology", TeacherName = "Yaremchuk Irina Petrovna", DayWeek = "Moday", StartTime = "13:00", EndTime = "13:40" }, new tblSchedule { SubjectName = "German language", TeacherName = "Dubych Iryna Mykhailivna", DayWeek = "Moday", StartTime = "14:00", EndTime = "14:40" }, new tblSchedule { SubjectName = "Musical art", TeacherName = "Yatsenya Alla Vladimirovna", DayWeek = "Moday", StartTime = "15:00", EndTime = "15:40" }, new tblSchedule { SubjectName = "Physical education and swimming", TeacherName = "Kovaleva Tatiana Nikolaevna", DayWeek = "Friday", StartTime = "11:00", EndTime = "11:40" }, new tblSchedule { SubjectName = "Ukrainian language", TeacherName = "Basyrova Nina Stepanovna", DayWeek = "Friday", StartTime = "12:00", EndTime = "12:40" }, new tblSchedule { SubjectName = "English language", TeacherName = "Malyarchuk Maria Andreevna", DayWeek = "Friday", StartTime = "13:00", EndTime = "13:40" }, new tblSchedule { SubjectName = "Computer science", TeacherName = "Smulka Victor Vasilyevich", DayWeek = "Friday", StartTime = "14:00", EndTime = "14:40" }, new tblSchedule { SubjectName = "Biology", TeacherName = "Pashko Halyna Ulyanivna", DayWeek = "Friday", StartTime = "15:00", EndTime = "15:40" } }; var schoolParty = new List <tblSchoolParty> { new tblSchoolParty { Description = "Week «Мade in Ukraine»", FullDate = "17/06/2020", ImageLink = "http://rgg.rv.ua/images/joomgallery/details/systemna_7/proektu_23/p70130-124457_20170617_1319682922.jpg" }, new tblSchoolParty { Description = "We gnaw the granite of science. We exchange good grades for sweets.", FullDate = "13/04/20219", ImageLink = "http://rgg.rv.ua/images/joomgallery/details/systemna_7/proektu_23/p1010011_20170617_1564683012.jpg" }, new tblSchoolParty { Description = "Ukrainian embroidered shirt", FullDate = "15/02/2020", ImageLink = "http://rgg.rv.ua/images/joomgallery/details/systemna_7/proektu_23/foto_20200105_1370932733.jpg" }, new tblSchoolParty { Description = "Let's say to the pollution: 'No!'", FullDate = "05/02/2020", ImageLink = "http://rgg.rv.ua/images/joomgallery/details/systemna_7/proektu_23/foto_20200105_1047291689.jpg" } }; var teachers = new List <tblTeachers> { new tblTeachers { FullName = "Alexander Olegovich Kostilov", Description = "WePlay! Clutch Island; IEM Katowice 2020; BLAST Premier Spring Series 2020; ESL Pro League Season 10. Европа; StarSeries & i-League CS:GO Season 7; BLAST Pro Series — Copenhagen 2018; ESL One Cologne 2018; CS:GO Asia Championships 2018; StarSeries i-League Season 5; DreamHack Winter 2017; WESG 2017 Europe Finals; ESL One New York 2016; CIS Championship; Кубок Воронежа;", ImageLink = "https://www.bestsettings.com/wp-content/uploads/2019/08/s1mple.jpg" }, new tblTeachers { FullName = "Kirill Mikhailov", Description = "M.Game League #2; ESL Pro League Season 10. Европа; ", ImageLink = "https://svirtus.cdnvideo.ru/nB1GYWdNb0aly6UtRRtZowvCe8o=/0x0:4023x4025/200x200/filters:quality(100)/https://hb.bizmrg.com/esports-core-media/69/69d241fc44727867be55f294ca6c136a.jpeg?m=d1f01bf22a9ac754da9a88511c9b6fd7" }, new tblTeachers { FullName = "Danilo Igorovich Teslenko", Description = "BLAST Pro Series — Copenhagen 2018; ESL One Cologne 2018; CS:GO Asia Championships 2018; StarSeries i-League Season 5;", ImageLink = "https://svirtus.cdnvideo.ru/TO6LLhKrYD5TF1EEtKwSR0l1QOw=/0x0:400x417/800x0/filters:quality(100)/https://hb.bizmrg.com/cybersportru-media/c8/c8f09618501bae37467478f081f7a5b7.png?m=cde4fa8968828595b175329eb3c0c8ff" }, new tblTeachers { FullName = "John 'Edward' Sukharev", Description = "WESG 2017 Europe Finals; ESL One New York 2016; SLTV StarSeries IX;", ImageLink = "https://svirtus.cdnvideo.ru/T35Gk59v_4RVGdT1xdm4m7LzIEg=/0x0:226x245/200x200/filters:quality(100)/https://hb.bizmrg.com/esports-core-media/27/27a0bbd1b2cda0164a1da43593d38055.jpg?m=946fc4d57657c9bca49fb18ac9b78875" }, }; _context.Teachers.AddRange(teachers); _context.SchoolParty.AddRange(schoolParty); _context.Schedule.AddRange(schedule); _context.News.AddRange(news); _context.Gallary.AddRange(gallary); _context.Career.AddRange(careers); var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(_context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(_context)); var role1 = new IdentityRole { Name = "admin" }; var role2 = new IdentityRole { Name = "user" }; roleManager.Create(role1); roleManager.Create(role2); var admin = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var result = userManager.Create(admin, password); if (result.Succeeded) { userManager.AddToRole(admin.Id, role1.Name); userManager.AddToRole(admin.Id, role2.Name); } _context.SaveChanges(); base.Seed(_context); }
protected override void Seed(ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); // создаем две роли var role1 = new IdentityRole { Name = "admin" }; var role2 = new IdentityRole { Name = "user" }; // добавляем роли в бд roleManager.Create(role1); roleManager.Create(role2); // создаем пользователей var admin = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var result = userManager.Create(admin, password); // если создание пользователя прошло успешно if (result.Succeeded) { // добавляем для пользователя роль userManager.AddToRole(admin.Id, role1.Name); } // ====================================================== var complexity = new List <Сomplexity> { new Сomplexity { Complication = "базовый" }, new Сomplexity { Complication = "повышенный" }, new Сomplexity { Complication = "высокий" } }; complexity.ForEach(c => context.Сomplexitys.Add(c)); context.SaveChanges(); var test = new List <Test> { new Test { Subject = "Математика", TimeToGo = 10, CountQuestions = 5, СomplexityId = 1, }, new Test { Subject = "Математика", TimeToGo = 15, CountQuestions = 5, СomplexityId = 1 }, new Test { Subject = "Математика", TimeToGo = 20, CountQuestions = 25, СomplexityId = 2 }, new Test { Subject = "Физика", TimeToGo = 10, CountQuestions = 5, СomplexityId = 2 }, new Test { Subject = "Физика", TimeToGo = 20, CountQuestions = 10, СomplexityId = 3 } }; test.ForEach(t => context.Tests.Add(t)); context.SaveChanges(); var questions = new List <Question> { new Question { TestId = 1, UserQuestion = "2+2" }, new Question { TestId = 1, UserQuestion = "3+3" }, new Question { TestId = 1, UserQuestion = "2-2" }, new Question { TestId = 1, UserQuestion = "5*2" }, new Question { TestId = 1, UserQuestion = "5+8" }, // второй тест /* * new Question { TestId = 2, UserQuestion = "2*2+2" }, * new Question { TestId = 2, UserQuestion = "3+3-0" }, * new Question { TestId = 2, UserQuestion = "2/2*2" }, * new Question { TestId = 2, UserQuestion = "5*2+1" }, * new Question { TestId = 2, UserQuestion = "5+8*2" }, */ }; questions.ForEach(t => context.Questions.Add(t)); context.SaveChanges(); var answers = new List <Answer> { // ответы только по первому тесту new Answer { QuestionId = 1, UserAnswer = "4", IsCorrect = true }, new Answer { QuestionId = 1, UserAnswer = "5", IsCorrect = false }, new Answer { QuestionId = 2, UserAnswer = "6", IsCorrect = true }, new Answer { QuestionId = 2, UserAnswer = "4", IsCorrect = false }, new Answer { QuestionId = 3, UserAnswer = "0", IsCorrect = true }, new Answer { QuestionId = 3, UserAnswer = "3", IsCorrect = false }, new Answer { QuestionId = 4, UserAnswer = "10", IsCorrect = true }, new Answer { QuestionId = 4, UserAnswer = "12", IsCorrect = false }, new Answer { QuestionId = 5, UserAnswer = "13", IsCorrect = true }, new Answer { QuestionId = 5, UserAnswer = "17", IsCorrect = false }, }; answers.ForEach(t => context.Answers.Add(t)); context.SaveChanges(); base.Seed(context); }
protected override void Seed(ApplicationDbContext context) { #region Phase A - Set up our Security Roles // 1. Instantiate a Controller class from ASP.Net Identity to add roles var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); // 2. Grab our list of security roles from the web.config var startupRoles = ConfigurationManager.AppSettings["startupRoles"].Split(';'); // 3. Loop through and create the security roles foreach (var role in startupRoles) { roleManager.Create(new IdentityRole { Name = role }); } #endregion #region Phase B - Add a Website Administrator // 1. Get the values from the <appSettings> string adminUser = ConfigurationManager.AppSettings["adminUserName"]; string adminRole = ConfigurationManager.AppSettings["adminRole"]; string adminEmail = ConfigurationManager.AppSettings["adminEmail"]; string adminPassword = ConfigurationManager.AppSettings["adminPassword"]; // 2. Instantiate my Controller to manage Users var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); // \ IdentityConfig.cs / \IdentityModels.cs/ // 3. Add the web admin to the database var result = userManager.Create(new ApplicationUser { UserName = adminUser, Email = adminEmail, CustomerId = null, EmployeeId = null }, adminPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(adminUser).Id, adminRole); } #endregion #region Phase C - Add a Customer // 1. Get the values from the <appSettings> int customerId = int.Parse(ConfigurationManager.AppSettings["customerId"]); string customerUser = ConfigurationManager.AppSettings["customerUserName"]; string customerRole = ConfigurationManager.AppSettings["customerRole"]; string customerEmail = ConfigurationManager.AppSettings["customerEmail"]; string customerPassword = ConfigurationManager.AppSettings["customerPassword"]; result = userManager.Create(new ApplicationUser { CustomerId = customerId, UserName = customerUser, Email = customerEmail, EmployeeId = null }, customerPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(customerUser).Id, customerRole); } #endregion #region Phase D - Add a Employee // 1. Get the values from the <appSettings> int employeeId = int.Parse(ConfigurationManager.AppSettings["employeeId"]); string employeeUser = ConfigurationManager.AppSettings["employeeUserName"]; string employeeRole = ConfigurationManager.AppSettings["employeeRole"]; string employeeEmail = ConfigurationManager.AppSettings["employeeEmail"]; string employeePassword = ConfigurationManager.AppSettings["employeePassword"]; result = userManager.Create(new ApplicationUser { EmployeeId = employeeId, UserName = employeeUser, Email = employeeEmail, CustomerId = null }, employeePassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(employeeUser).Id, employeeRole); } #endregion base.Seed(context); }
protected override void Seed(Attendance_System.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // var store = new UserStore <ApplicationUser>(context); var manager = new UserManager <ApplicationUser>(store); var institute = new List <Institute> { new Institute { InstituteName = "eaaa", ILogo = "Logo.jpg", InstituteId = 1 } }; context.Institute.AddOrUpdate(i => i.InstituteId, institute.ToArray()); context.SaveChanges(); //Adds Courses var courses = new List <Course> { new Course { CourseId = 1, CourseName = "Backend", EducationName = "PBA-WEB", Start = new DateTime(2017, 11, 12), End = new DateTime(2018, 03, 12), }, new Course { CourseId = 2, CourseName = "Frontend", EducationName = "PBA-WEB", Start = new DateTime(2017, 11, 12), End = new DateTime(2018, 03, 12), }, new Course { CourseId = 3, CourseName = "Database", EducationName = "PBA-WEB", Start = new DateTime(2017, 11, 12), End = new DateTime(2018, 03, 12), }, new Course { CourseId = 4, CourseName = "Interface Design", EducationName = "PBA-WEB", Start = new DateTime(2017, 11, 12), End = new DateTime(2018, 03, 12), }, new Course { CourseId = 5, CourseName = "Disciplinary Showoff", EducationName = "PBA-WEB", Start = new DateTime(2017, 12, 15), End = new DateTime(2018, 03, 12), } }; context.Course.AddOrUpdate(c => c.CourseId, courses.ToArray()); context.SaveChanges(); //Add Lectures var lectures = new List <Lecture> { new Lecture { CourseId = 5, StartTime = new DateTime(2017, 12, 15, 10, 30, 00), EndTime = new DateTime(2017, 12, 15, 12, 30, 00), LectureName = "Show-Off Presentation", }, new Lecture { CourseId = 1, StartTime = new DateTime(2017, 11, 12, 8, 30, 00), EndTime = new DateTime(2017, 11, 12, 12, 30, 00), LectureName = "Lecture 1", }, new Lecture { CourseId = 1, StartTime = new DateTime(2017, 12, 13, 8, 30, 00), EndTime = new DateTime(2017, 12, 13, 12, 30, 00), LectureName = "Lecture 2", }, new Lecture { CourseId = 1, StartTime = new DateTime(2017, 12, 21, 8, 30, 00), EndTime = new DateTime(2017, 12, 21, 12, 30, 00), LectureName = "Lecture 3", }, new Lecture { CourseId = 1, StartTime = new DateTime(2017, 12, 22, 8, 30, 00), EndTime = new DateTime(2017, 12, 22, 12, 30, 00), LectureName = "Lecture 4", }, new Lecture { CourseId = 2, StartTime = new DateTime(2017, 12, 21, 8, 30, 00), EndTime = new DateTime(2017, 12, 21, 12, 30, 00), LectureName = "Lecture 1", }, new Lecture { CourseId = 2, StartTime = new DateTime(2017, 12, 23, 8, 30, 00), EndTime = new DateTime(2017, 12, 23, 12, 30, 00), LectureName = "Lecture 2", }, new Lecture { CourseId = 2, StartTime = new DateTime(2017, 1, 1, 8, 30, 00), EndTime = new DateTime(2017, 1, 1, 12, 30, 00), LectureName = "Lecture 3", }, new Lecture { CourseId = 2, StartTime = new DateTime(2017, 1, 3, 8, 30, 00), EndTime = new DateTime(2017, 1, 3, 12, 30, 00), LectureName = "Lecture 4", }, new Lecture { CourseId = 3, StartTime = new DateTime(2017, 1, 5, 8, 30, 00), EndTime = new DateTime(2017, 1, 5, 12, 30, 00), LectureName = "Lecture 1", }, new Lecture { CourseId = 3, StartTime = new DateTime(2017, 1, 9, 8, 30, 00), EndTime = new DateTime(2017, 1, 9, 12, 30, 00), LectureName = "Lecture 2", }, new Lecture { CourseId = 3, StartTime = new DateTime(2017, 1, 10, 8, 30, 00), EndTime = new DateTime(2017, 1, 10, 12, 30, 00), LectureName = "Lecture 3", }, new Lecture { CourseId = 3, StartTime = new DateTime(2017, 1, 12, 8, 30, 00), EndTime = new DateTime(2017, 1, 12, 12, 30, 00), LectureName = "Lecture 4", }, new Lecture { CourseId = 4, StartTime = new DateTime(2017, 1, 17, 8, 30, 00), EndTime = new DateTime(2017, 1, 17, 12, 30, 00), LectureName = "Lecture 1", }, new Lecture { CourseId = 4, StartTime = new DateTime(2017, 1, 22, 8, 30, 00), EndTime = new DateTime(2017, 1, 22, 12, 30, 00), LectureName = "Lecture 2", }, new Lecture { CourseId = 4, StartTime = new DateTime(2017, 1, 12, 8, 30, 00), EndTime = new DateTime(2017, 1, 12, 12, 30, 00), LectureName = "Lecture 3", }, new Lecture { CourseId = 4, StartTime = new DateTime(2017, 1, 26, 8, 30, 00), EndTime = new DateTime(2017, 11, 26, 12, 30, 00), LectureName = "Lecture 4", } }; context.Lecture.AddOrUpdate(l => l.LectureId, lectures.ToArray()); context.SaveChanges(); // Add roles to Solution var roleManager = new List <IdentityRole> { new IdentityRole { Id = "1", Name = "Admin" }, new IdentityRole { Id = "2", Name = "Teacher" }, new IdentityRole { Id = "3", Name = "Student" } }; context.Roles.AddOrUpdate(r => r.Id, roleManager.ToArray()); context.SaveChanges(); // Seedint studentUsers Because of IdentityFramework Autogenrated id this is now has own AI ids for further Seed var studentUsers = new List <ApplicationUser> { new ApplicationUser { Id = "6", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "7", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "8", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "9", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "10", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "11", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "12", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "13", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "14", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "15", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "16", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "17", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "18", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "19", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "20", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "21", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "22", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "23", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "24", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "25", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "26", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "27", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "28", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "29", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() }, new ApplicationUser { Id = "30", Email = Faker.Internet.Email(), PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==", UserName = Internet.Email(), FirstName = Name.First(), LastName = Name.Last() } }; context.Users.AddOrUpdate(u => u.Id, studentUsers.ToArray()); context.SaveChanges(); //Adds StudentUsers to the Role Student foreach (ApplicationUser student in studentUsers) { manager.AddToRole(student.Id, "Student"); } context.SaveChanges(); // enrolls the studentUsers with id 6-30 var studentEnrollment = new List <Enrollment> { new Enrollment { CourseId = 1, ApplicationUserId = "6", }, new Enrollment { CourseId = 2, ApplicationUserId = "6", }, new Enrollment { CourseId = 3, ApplicationUserId = "6", }, new Enrollment { CourseId = 4, ApplicationUserId = "7", }, new Enrollment { CourseId = 3, ApplicationUserId = "7", }, new Enrollment { CourseId = 2, ApplicationUserId = "7", }, new Enrollment { CourseId = 1, ApplicationUserId = "8", }, new Enrollment { CourseId = 2, ApplicationUserId = "8", }, new Enrollment { CourseId = 3, ApplicationUserId = "8", }, new Enrollment { CourseId = 3, ApplicationUserId = "9", }, new Enrollment { CourseId = 2, ApplicationUserId = "9", }, new Enrollment { CourseId = 1, ApplicationUserId = "9", }, new Enrollment { CourseId = 1, ApplicationUserId = "10", }, new Enrollment { CourseId = 2, ApplicationUserId = "10", }, new Enrollment { CourseId = 1, ApplicationUserId = "11", }, new Enrollment { CourseId = 4, ApplicationUserId = "11", }, new Enrollment { CourseId = 2, ApplicationUserId = "12", }, new Enrollment { CourseId = 4, ApplicationUserId = "12", }, new Enrollment { CourseId = 2, ApplicationUserId = "13", }, new Enrollment { CourseId = 3, ApplicationUserId = "13", }, new Enrollment { CourseId = 2, ApplicationUserId = "14", }, new Enrollment { CourseId = 4, ApplicationUserId = "14", }, new Enrollment { CourseId = 2, ApplicationUserId = "15", }, new Enrollment { CourseId = 1, ApplicationUserId = "15", }, new Enrollment { CourseId = 2, ApplicationUserId = "16", }, new Enrollment { CourseId = 3, ApplicationUserId = "16", }, new Enrollment { CourseId = 2, ApplicationUserId = "17", }, new Enrollment { CourseId = 4, ApplicationUserId = "17", }, new Enrollment { CourseId = 3, ApplicationUserId = "18", }, new Enrollment { CourseId = 4, ApplicationUserId = "18", }, new Enrollment { CourseId = 1, ApplicationUserId = "18", }, new Enrollment { CourseId = 2, ApplicationUserId = "19", }, new Enrollment { CourseId = 1, ApplicationUserId = "19", }, new Enrollment { CourseId = 1, ApplicationUserId = "20", }, new Enrollment { CourseId = 1, ApplicationUserId = "21", }, new Enrollment { CourseId = 3, ApplicationUserId = "22", }, new Enrollment { CourseId = 4, ApplicationUserId = "22", }, new Enrollment { CourseId = 1, ApplicationUserId = "23", }, new Enrollment { CourseId = 2, ApplicationUserId = "23", }, new Enrollment { CourseId = 3, ApplicationUserId = "24", }, new Enrollment { CourseId = 4, ApplicationUserId = "24", }, new Enrollment { CourseId = 1, ApplicationUserId = "25", }, new Enrollment { CourseId = 2, ApplicationUserId = "25", }, }; context.Enrollment.AddOrUpdate(e => e.EnrollmentId, studentEnrollment.ToArray()); context.SaveChanges(); //FixedAdmin on startup with working PASS PASS123! string password = "******"; string email = "*****@*****.**"; string userName = email; string uId = "2"; ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); ApplicationUser user = userMgr.FindByName(userName); if (user == null) { userMgr.Create(new ApplicationUser { Email = email, UserName = userName, Id = uId }, password); user = userMgr.FindByName(userName); } if (!userMgr.IsInRole(user.Id, "Admin")) { userMgr.AddToRole("2", "Admin"); } context.SaveChanges(); //FixedTeacher on Startup WIth working PASS PASS123! string teacherPassword = "******"; string teacherEmail = "*****@*****.**"; string teacherUserName = teacherEmail; string teacherUId = "3"; ApplicationUser userTeacher = userMgr.FindByName(teacherUserName); if (userTeacher == null) { userMgr.Create(new ApplicationUser { Email = teacherEmail, UserName = teacherUserName, Id = teacherUId }, teacherPassword); userTeacher = userMgr.FindByName(teacherUserName); } if (!userMgr.IsInRole(userTeacher.Id, "Teacher")) { userMgr.AddToRole("3", "Teacher"); } context.SaveChanges(); //FixedTeacher on Startup WIth working PASS PASS123! string studentPassword = "******"; string studentEmail = "*****@*****.**"; string studentUserName = studentEmail; string studentFirstName = "Allan"; string studentLastName = "Olesen"; string studentUId = "4"; ApplicationUser userStudent = userMgr.FindByName(studentUserName); if (userStudent == null) { userMgr.Create(new ApplicationUser { Email = studentEmail, UserName = studentUserName, Id = studentUId, FirstName = studentFirstName, LastName = studentLastName }, studentPassword); userStudent = userMgr.FindByName(studentUserName); } if (!userMgr.IsInRole(userStudent.Id, "Student")) { userMgr.AddToRole("4", "Student"); } context.SaveChanges(); // List of 8 Teachers Without Password or Enrollsments var teachers = Builder <ApplicationUser> .CreateListOfSize(4) .All() .With(s => s.Email = Faker.Name.First() + "@eaaa.com") .With(s => s.PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==") .With(s => s.SecurityStamp = "417d9850-177a-486c-9e08-4be21bad60f7") .With(s => s.UserName = Faker.Internet.UserName() + "_teacher") .With(s => s.PhoneNumber = Faker.Phone.Number()) .With(s => s.TwoFactorEnabled = false) .Build(); context.Users.AddOrUpdate(t => t.Id, teachers.ToArray()); context.SaveChanges(); foreach (ApplicationUser teacher in teachers) { manager.AddToRole(teacher.Id, "Teacher"); } // Creates 15 Test Students/users Who are not enrolled in any course var students = Builder <ApplicationUser> .CreateListOfSize(15) .All() .With(s => s.Email = Faker.Name.First() + "@eaaa.dk") .With(s => s.PasswordHash = "AHYvI4ctMM2uaLhgi9yEBO/XdF5soAp+zk9pnV7zWumed56TMU9K0k2Y2q+KPtw9Uw==") .With(s => s.SecurityStamp = "417d9850-177a-486c-9e08-4be21bad60f7") .With(s => s.UserName = Faker.Internet.UserName() + "_student") .With(s => s.FirstName = Faker.Name.First()) .With(s => s.LastName = Faker.Name.Last()) .With(s => s.PhoneNumber = Faker.Phone.Number()) .With(s => s.TwoFactorEnabled = false) .Build(); context.Users.AddOrUpdate(s => s.Id, students.ToArray()); context.SaveChanges(); foreach (ApplicationUser student in students) { manager.AddToRole(student.Id, "Student"); } var enrollment = new List <Enrollment> { new Enrollment { CourseId = 1, ApplicationUserId = "4", }, new Enrollment { CourseId = 2, ApplicationUserId = "4", }, new Enrollment { CourseId = 3, ApplicationUserId = "4", } }; context.Enrollment.AddOrUpdate(e => e.EnrollmentId, enrollment.ToArray()); context.SaveChanges(); var attendances = new List <Attendance> { new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 38, 00), ApplicationUserId = "6", LectureId = 2 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 38, 00), ApplicationUserId = "7", LectureId = 2 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 46, 00), ApplicationUserId = "8", LectureId = 2 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 46, 00), ApplicationUserId = "6", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 38, 00), ApplicationUserId = "9", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 55, 00), ApplicationUserId = "10", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 55, 00), ApplicationUserId = "12", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 8, 38, 00), ApplicationUserId = "6", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 10, 38, 00), ApplicationUserId = "10", LectureId = 1 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 09, 38, 00), ApplicationUserId = "6", LectureId = 5 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 08, 38, 00), ApplicationUserId = "25", LectureId = 5 }, new Attendance { ArrivalTime = new DateTime(2017, 11, 12, 09, 38, 00), ApplicationUserId = "26", LectureId = 5 }, }; context.Attendance.AddOrUpdate(l => l.AttendanceId, attendances.ToArray()); // context.SaveChanges(); int[] CoursesIds = { 1, 2, 3, 4 }; var iDGenerator = new RandomGenerator(); /* * var enrollments = Builder<Enrollment>.CreateListOfSize(100) * .All() * .With(e => e.UserId = iDGenerator.Next(2, 60)) * .With(e => e.CourseId = iDGenerator.Next(1, 4)) * .Build(); * * context.SaveChanges(); */ }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var UserAddresses = new List <UserAddress>() { new UserAddress() { IsDeleted = false, Address = new Address() { IsDeleted = false, City = model.City, Zip = model.Zip, State = model.State, MainAddress = model.MainAddress, DeliveryAddress = model.DeliveryAddress, Country = model.Country } } }; var user = new data.Entities.User() { Email = model.Email, FName = model.FName, LName = model.LName, Individually = model.Individually, IsDeleted = false, MName = model.MName, NationalId = model.NationalId, Phone = model.Phone, UserAddresses = UserAddresses, }; var corporateDetails = new CorporateDetails(); if (model.Individually == 2) { corporateDetails = new CorporateDetails() { CorporateName = model.CorporateName, CorporateSite = model.CorporateSite, RegistrationNo = model.RegistrationNo, user = user }; db.CorporatesDetails.Add(corporateDetails); db.SaveChanges(); } else { db.SaveChanges(); } var ASPUser = new ApplicationUser { user = user, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(ASPUser, model.Password); if (result.Succeeded) { UserManager.AddToRole(ASPUser.Id, "User"); await SignInManager.SignInAsync(ASPUser, isPersistent : false, rememberBrowser : false); EmailTemplate Email = new EmailTemplate(); string path = @"~/Common/WelcomeEmailTemplate.html"; var emailHtml = Email.ReadTemplateEmail(user, path); try { GmailSender.SendEmail("*****@*****.**", "Serious!1", new List <string>() { model.Email }, "Welcome", emailHtml, null); } catch (Exception e) { db.CorporatesDetails.Remove(corporateDetails); var logins = ASPUser.Logins; var rolesForUser = await _userManager.GetRolesAsync(ASPUser.Id); using (var transaction = context.Database.BeginTransaction()) { foreach (var login in logins.ToList()) { await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey)); } if (rolesForUser.Count() > 0) { foreach (var item in rolesForUser.ToList()) { await _userManager.RemoveFromRoleAsync(ASPUser.Id, item); } } await _userManager.DeleteAsync(ASPUser); transaction.Commit(); } db.SaveChanges(); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
protected override void Seed(ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var adminRole = new IdentityRole { Name = "Admin" }; var userRole = new IdentityRole { Name = "User" }; roleManager.Create(adminRole); roleManager.Create(userRole); var admin = new ApplicationUser { Email = "*****@*****.**", UserName = "******", FirstName = "Dmitry", LastName = "Panaev", City = "Ufa", Country = "Russia", House = 222, Street = "Odesskaya" }; string password = "******"; var result = userManager.Create(admin, password); if (result.Succeeded) { userManager.AddToRole(admin.Id, userRole.Name); userManager.AddToRole(admin.Id, adminRole.Name); } for (int i = 0; i < 16; i++) { ProductModel product; if (i < 5) { product = new ProductModel() { Category = "Медицина", CountInStore = 100, Description = "None", Name = "Product" + i, Price = 100 * i, Subcategory = "Расходные материалы" }; } else { product = new ProductModel() { Category = "Электроника", CountInStore = 100, Description = "None", Name = "Product" + i, Price = 5000 * i, Subcategory = "Телефоны" }; } context.Products.Add(product); } base.Seed(context); }
public async Task <ActionResult> Register(AlphaTestingViewModel model) { using (var context = new ApplicationDbContext()) { if (ModelState.IsValid) { Service service = new Service(); PayPalService ppService = new PayPalService(); var currentTesters = service.GetCurrentAlphaTesters(model.AlphaCode); var codeCount = service.GetCodeCount(model.AlphaCode); var codeId = service.GetCodeId(model.AlphaCode); if (currentTesters.Count == codeCount) { ModelState.AddModelError("", "Invite Code is either invalid or has been used the maximum allowed times."); } else { model.CodeId = codeId; var user = new ApplicationUser { UserName = model.Username, Email = model.Email, CodeId = model.CodeId }; var result = await UserManager.CreateAsync(user, model.Password); var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); var startDate = DateTime.Now; if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); service.CreateMembership(user.Id); service.CreateSettings(user.Id); var defaultImage = Image.FromFile(Server.MapPath("~/Images/JeepStar.jpg")); var stream = new MemoryStream(); defaultImage.Save(stream, ImageFormat.Jpeg); var imageData = ConvertToBytes(stream); service.CreateProfile(user.Id, imageData); //this creates the paypal customer-then on success creates the membership and the free subscription. ppService.PayPalCreateCustomer(user.Email, user.Id, user.UserName, startDate, startDate.AddYears(100)); UserManager.AddToRole(user.Id, "Basic"); return(RedirectToAction("AlphaTesting", "Home")); } AddErrors(result); } } // If we got this far, something failed, redisplay form return(View(model)); } }
protected override void Seed(BlogMVC.Models.ApplicationDbContext context) { if (!context.Roles.Any(x => x.Name == "admin")) { var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); roleManager.Create(new IdentityRole("admin")); } if (!context.Users.Any(x => x.UserName == "*****@*****.**")) { var userStore = new UserStore <ApplicationUser>(context); var userManager = new ApplicationUserManager(userStore); var user = new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, NickName = "Admin01" }; userManager.Create(user, "1234.Lol"); userManager.AddToRole(user.Id, "admin"); } if (!context.Categories.Any()) { context.Categories.AddRange(new List <Category> { new Category { Name = "Sports", Description = "Sport (or sports) is all forms of usually competitive physical activity which, through casual or organised participation, aim to use, maintain or improve physical ability and skills while providing entertainment to participants, and in some cases, spectators." }, new Category { Name = "Politic", Description = "Politics is the set of activities that are associated with making decisions in groups, or other forms of power relations between individuals, such as the distribution of resources or status. The academic study of politics is referred to as political science." }, new Category { Name = "Politics", Description = "Politics is the set of activities that are associated with making decisions in groups, or other forms of power relations between individuals, such as the distribution of resources or status. The academic study of politics is referred to as political science." }, new Category { Name = "Software", Description = "Software, instructions that tell a computer what to do. Software comprises the entire set of programs, procedures, and routines associated with the operation of a computer system. The term was coined to differentiate these instructions from hardware, the physical components of a computer system." }, new Category { Name = "Future", Description = "Future studies, futures research or futurology is the systematic, interdisciplinary and holistic study of social and technological advancement, and other environmental trends, often for the purpose of exploring how people will live and work in the future. " }, new Category { Name = "Movie", Description = "Movies, or films, are a type of visual communication which uses moving pictures and sound to tell stories or teach people something. Most people watch (view) movies as a type of entertainment or a way to have fun." }, new Category { Name = "Science", Description = "Movies, or films, are a type of visual communication which uses moving pictures and sound to tell stories or teach people something. Most people watch (view) movies as a type of entertainment or a way to have fun." }, new Category { Name = "Research", Description = "Movies, or films, are a type of visual communication which uses moving pictures and sound to tell stories or teach people something. Most people watch (view) movies as a type of entertainment or a way to have fun." }, new Category { Name = "Lifestyle", Description = "Movies, or films, are a type of visual communication which uses moving pictures and sound to tell stories or teach people something. Most people watch (view) movies as a type of entertainment or a way to have fun." } }); } if (!context.ReportCategories.Any()) { ReportCategory reportCategory1 = new ReportCategory(); reportCategory1.Name = "Spam"; ReportCategory reportCategory2 = new ReportCategory(); reportCategory2.Name = "Harassment"; ReportCategory reportCategory3 = new ReportCategory(); reportCategory3.Name = "Rules Violation"; context.ReportCategories.Add(reportCategory1); context.ReportCategories.Add(reportCategory2); context.ReportCategories.Add(reportCategory3); } }
public async Task <ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(View("Error")); } var newUser = await UserManager.FindByIdAsync(userId); if (!(await UserManager.IsEmailConfirmedAsync(newUser.Id))) { var result = await UserManager.ConfirmEmailAsync(userId, code); if (result.Succeeded) { var result1 = UserManager.AddToRole(userId, "Monitor"); var context = new ApplicationDbContext(); var userGroup = context.Users.FirstOrDefault(u => u.Id.Equals(userId)).GroupId; var coordinatorRole = context.Roles .Where(m => m.Name.Equals("Coordinator")) .Select(m => m.Id).ToList(); var coordinatorUsers = context.Users .Where(m => m.Roles .Any(r => coordinatorRole.Contains(r.RoleId))); if (coordinatorUsers.Any(u => u.GroupId.Equals(userGroup))) { var userCoordinatorEmails = coordinatorUsers.Where( u => u.GroupId.Equals(userGroup) && u.Status == true).Select(m => m.Id).ToList(); foreach (var uce in userCoordinatorEmails) { await UserManager.SendEmailAsync(uce, "You have a new user", "A new user, " + newUser.FirstName + " " + newUser.LastName + ", in your group that has registered for access to the CMC Data Portal. " + "Please login to the Chesapeake Monitoring Cooperative website " + "and activate the new user."); } } else { var memberRole = context.Roles .Where(m => m.Name.Equals("Member")) .Select(m => m.Id).ToList(); var memberUsers = context.Users .Where(m => m.Roles .Any(r => memberRole.Contains(r.RoleId))); var userMemberEmail = memberUsers.Select(m => m.Id).ToListAsync(); foreach (var m in await userMemberEmail) { await UserManager.SendEmailAsync(m, "You have a new user", "A new user, " + newUser.FirstName + " " + newUser.LastName + ", has registered for access to the CMC Data Portal. " + "Please login to the Chesapeake Monitoring Cooperative website " + "and activate the new user."); } } var adminRole = context.Roles .Where(m => m.Name.Equals("Admin") | m.Name.Equals("Officer")) .Select(m => m.Id).ToList(); var memberAdminUsers = context.Users .Where(m => m.Roles .Any(r => adminRole.Contains(r.RoleId))); var adminMemberEmail = memberAdminUsers.Select(m => m.Id).ToListAsync(); foreach (var m in await adminMemberEmail) { await UserManager.SendEmailAsync(m, "You have a new user", "A new user, " + newUser.FirstName + " " + newUser.LastName + ", has registered for access to the CMC Data Portal. " + "Please login to the Chesapeake Monitoring Cooperative website " + "and activate the new user."); } } return(View(result.Succeeded ? "ConfirmEmail" : "Error")); } return(View("ConfirmEmail")); }
protected override void Seed(ShopRosKvartal.Models.ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); //============================================================ //инициализация ролей if (!context.Roles.Any()) { // создание роли var role = new IdentityRole { Name = "Администратор" }; // добавление роли в бд roleManager.Create(role); role = new IdentityRole { Name = "Модератор" }; roleManager.Create(role); role = new IdentityRole { Name = "Покупатель" }; roleManager.Create(role); } //============================================================ //============================================================ //создание админа для пустой БД var admin = userManager.FindByName("Admin"); if (admin == null || !context.Users.Any()) { // создание админа admin = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var result = userManager.Create(admin, password); // если создание пользователя прошло успешно if (result.Succeeded) { var role = roleManager.FindByName("Администратор"); if (role != null) { // добавляем для пользователя роль userManager.AddToRole(admin.Id, role.Name); } else { // создание роли role = new IdentityRole { Name = "Администратор" }; // добавление роли в бд roleManager.Create(role); // добавляем для пользователя роль userManager.AddToRole(admin.Id, role.Name); } } } //============================================================ //============================================================ //инициализация SMTP сервера if (!context.ToolsSMTPSettings.Any()) { ToolsSMTPSetting smtp = new ToolsSMTPSetting(); smtp.EmailFrom = "*****@*****.**"; smtp.UserName = "******"; smtp.Password = "******"; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; context.ToolsSMTPSettings.Add(smtp); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы полов пользователей if (!context.UserGenders.Any()) { UserGender gender = new UserGender(); gender.Gender = "Мужской"; context.UserGenders.Add(gender); context.SaveChanges(); gender.Gender = "Женский"; context.UserGenders.Add(gender); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы категории if (!context.ShopCategories.Any()) { ShopCategory parent = new ShopCategory(); parent.Name = "Спортивное питание"; parent.Alias = Translit.TranslitString(parent.Name); context.ShopCategories.Add(parent); context.SaveChanges(); //----------------------------------------------- ShopCategory child = new ShopCategory { Name = "Протеины", ParentId = parent.Id }; child.Alias = Translit.TranslitString(child.Name); context.ShopCategories.Add(child); context.SaveChanges(); //----------------------------------------------- child = new ShopCategory { Name = "Гейнеры", ParentId = parent.Id }; child.Alias = Translit.TranslitString(child.Name); context.ShopCategories.Add(child); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы вкус товара if (!context.ShopProductsTastes.Any()) { string[] tastes = { "Ваниль", "Клубника", "Шоколад", "Карамель-ваниль", "Малина-шоколад", "Миндаль-шоколад", "Малина", "Банан", "Вишня", "Абрикос", "Персик", "Апельсин" }; for (int i = 0; i < tastes.Length; i++) { ShopProductsTaste taste = new ShopProductsTaste { Name = tastes[i] }; context.ShopProductsTastes.Add(taste); context.SaveChanges(); } } //============================================================ //============================================================ //инициализация таблицы брэнды if (!context.ShopProductsBrands.Any()) { string[] brands = { "Optimum Nutrition", "Multipower", "BSN", "Dymatize", "MuscleTech", "Weider", "Sponser", "Twinlab", "Gaspari Nutrition", "Universal Nutrition" }; for (int i = 0; i < brands.Length; i++) { ShopProductsBrand brand = new ShopProductsBrand { Name = brands[i], Alias = brands[i].Replace(" ", "-") }; context.ShopProductsBrands.Add(brand); context.SaveChanges(); } } //============================================================ }
protected override void Seed(LMS.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. var courses = new[] { new Course { Id = 1, Name = ".Net", Description = "Fullstack course", StartDate = DateTime.Now.AddDays(10) }, new Course { Id = 2, Name = "Java", Description = "Java Course", StartDate = DateTime.Now.AddDays(10) }, new Course { Id = 3, Name = "C++", Description = "Fundamentals in C++", StartDate = DateTime.Now.AddDays(10) } }; context.Courses.AddOrUpdate(c => c.Name, courses); context.SaveChanges(); var modules = new[] { new Module { Name = "C#", Description = "Going POCO", StartDate = DateTime.Now.AddDays(10), CourseId = 1, EndDate = DateTime.Now.AddDays(110) }, new Module { Name = "EntityFramwork", Description = "Working with Entity", StartDate = DateTime.Now.AddDays(10), CourseId = 2, EndDate = DateTime.Now.AddDays(110) }, new Module { Name = "Identity", Description = "Working with Identity", StartDate = DateTime.Now.AddDays(10), CourseId = 3, EndDate = DateTime.Now.AddDays(110) }, //new Module {Name ="Search", Description = "Learning how to ask google the right questions", StartDate = DateTime.Now.AddDays(10), CourseId=1, EndDate = DateTime.Now.AddDays(80)}, }; context.Modules.AddOrUpdate(m => m.Name, modules); context.SaveChanges(); var activities = new[] { new Activity { Name = "Listen and learn", Type = "E-Learning", Description = "Watch video 'Entityframwork'", StartTime = DateTime.Now.AddDays(10), EndTime = DateTime.Now.AddDays(110), ModuleId = 1 }, new Activity { Name = "Writing the Matrix", Type = "CodeALong", Description = "Codeing a long with John", StartTime = DateTime.Now.AddDays(10), EndTime = DateTime.Now.AddDays(110), ModuleId = 1 }, new Activity { Name = "Zoo animals and there unatural habitat", Type = "Lecture", Description = "Adrian will talk about the animals at the zoo", StartTime = DateTime.Now.AddDays(10), EndTime = DateTime.Now.AddDays(110), ModuleId = 1 }, new Activity { Name = "Garage", Type = "Exercise", Description = "You will be given an exerices to code a garage", StartTime = DateTime.Now.AddDays(10), EndTime = DateTime.Now.AddDays(110), ModuleId = 1 }, }; context.Activities.AddOrUpdate(a => a.Name, activities); context.SaveChanges(); var userStore = new UserStore <ApplicationUser>(context); var userManager = new ApplicationUserManager(userStore); var studs = new[] { new ApplicationUser { FirstName = "Erik", LastName = "Eriksson", Email = "*****@*****.**", CourseId = 1, UserName = "******" }, new ApplicationUser { FirstName = "Fredrik", LastName = "Fredriksson", Email = "*****@*****.**", CourseId = 1, UserName = "******" }, new ApplicationUser { FirstName = "David", LastName = "Davidsson", Email = "*****@*****.**", CourseId = 1, UserName = "******" }, new ApplicationUser { FirstName = "Ahmed", LastName = "Gazawi", Email = "*****@*****.**", CourseId = 1, UserName = "******" }, new ApplicationUser { FirstName = "Borg", LastName = "Birkasson", Email = "*****@*****.**", CourseId = 2, UserName = "******" }, new ApplicationUser { FirstName = "John", LastName = "Hellman", Email = "*****@*****.**", UserName = "******" }, }; foreach (var stud in studs) { if (context.Users.Any(u => u.UserName == stud.UserName)) { continue; } //var user = new ApplicationUser { UserName = stud., Email = stud, FirstName = stud, LastName = stud}; var result = userManager.Create(stud, "lexicon"); if (!result.Succeeded) { throw new Exception(string.Join("\n", result.Errors)); } } context.Users.AddOrUpdate(u => u.UserName, studs); context.SaveChanges(); var emails = new[] { "*****@*****.**", "*****@*****.**" }; foreach (var email in emails) { if (context.Users.Any(u => u.UserName == email)) { continue; } var user = new ApplicationUser { UserName = email, Email = email }; var result = userManager.Create(user, "lexicon"); if (!result.Succeeded) { throw new Exception(string.Join("\n", result.Errors)); } context.Users.AddOrUpdate(u => u.UserName, studs); context.SaveChanges(); } var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); var roleNames = new[] { "Teacher", "Student" }; foreach (var roleName in roleNames) { if (context.Roles.Any(r => r.Name == roleName)) { continue; } var role = new IdentityRole { Name = roleName }; var result = roleManager.Create(role); if (!result.Succeeded) { throw new Exception(string.Join("\n", result.Errors)); } } var erikUser = userManager.FindByName("*****@*****.**"); userManager.AddToRole(erikUser.Id, "Student"); var fredrikUser = userManager.FindByName("*****@*****.**"); userManager.AddToRole(fredrikUser.Id, "Student"); var davidUser = userManager.FindByName("*****@*****.**"); userManager.AddToRole(davidUser.Id, "Student"); var teacherUser = userManager.FindByName("*****@*****.**"); userManager.AddToRole(teacherUser.Id, "Teacher"); }
public async Task <ActionResult> Create(ExpandedUserDTO paramExpandedUserDTO) { GetCurrentUserInViewBag(); try { if (paramExpandedUserDTO == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var college = GetAllCollege(); paramExpandedUserDTO.Programm = GetSelectListItems(college); var Email = paramExpandedUserDTO.Email.Trim(); var UserName = paramExpandedUserDTO.Email.Trim(); var Password = paramExpandedUserDTO.Password.Trim(); var LastName = paramExpandedUserDTO.StudentLastName.Trim(); var FirstName = paramExpandedUserDTO.StudentFirstName.Trim(); var MiddleName = paramExpandedUserDTO.StudentMiddleName.Trim(); var Program = paramExpandedUserDTO.Program.Trim(); var YrLevel = paramExpandedUserDTO.YearLevel; var StudentID = paramExpandedUserDTO.StudentID; //var IsActive = paramExpandedUserDTO.IsActive.Trim(); if (Email == "") { throw new Exception("No Email"); } if (Password == "") { throw new Exception("No Password"); } if (LastName == "") { throw new Exception("No LastName"); } if (FirstName == "") { throw new Exception("No FirstName"); } if (MiddleName == "") { throw new Exception("No MiddleName"); } if (Program == "") { throw new Exception("No Program"); } if (YrLevel == null) { throw new Exception("No YrLevel"); } if (StudentID == "") { throw new Exception("No StudentID"); } // UserName is LowerCase of the Email UserName = Email.ToLower(); // Create user var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email }; var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password); if (AdminUserCreateResult.Succeeded == true) { string strNewRole = Convert.ToString(Request.Form["Roles"]); if (strNewRole != "0") { // Put user in role UserManager.AddToRole(objNewAdminUser.Id, strNewRole); //Put user in student table if (strNewRole == "Student") { var newid = db.Students.FirstOrDefault(d => d.UserID == objNewAdminUser.Id); if (newid == null) { newid = db.Students.Create(); newid.UserID = objNewAdminUser.Id; newid.StudentEmail = objNewAdminUser.Email; newid.StudentLastName = LastName; newid.StudentFirstName = FirstName; newid.StudentMiddleName = MiddleName; newid.StudentID = StudentID; newid.Program = Program; newid.YearLevel = YrLevel; db.Students.Add(newid); db.SaveChanges(); } } //Put user in counselor table if (strNewRole == "Counselor") { var newid = db.Counsellor.FirstOrDefault(d => d.UserID == objNewAdminUser.Id); if (newid == null) { newid = db.Counsellor.Create(); newid.UserID = objNewAdminUser.Id; newid.CounsellorEmail = objNewAdminUser.Email; db.Counsellor.Add(newid); db.SaveChanges(); } } } string code = await UserManager.GenerateEmailConfirmationTokenAsync(objNewAdminUser.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = objNewAdminUser.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(objNewAdminUser.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(Redirect("~/Admin")); } else { ViewBag.Roles = GetAllRolesAsSelectList(); ModelState.AddModelError(string.Empty, "Error: User " + Email + " already exists!"); return(View(paramExpandedUserDTO)); } } catch (Exception ex) { ViewBag.Roles = GetAllRolesAsSelectList(); ExpandedUserDTO objExpandedUserDTO = new ExpandedUserDTO(); var college = GetAllCollege(); objExpandedUserDTO.Programm = GetSelectListItems(college); ModelState.AddModelError(string.Empty, "Error: " + ex); return(View(paramExpandedUserDTO)); } }
protected override void Seed(Context.ApplicationDbContext context) { //Creacion de los Roles var roleStore = new RoleStore <ApplicationRole>(context); var RoleManager = new RoleManager <ApplicationRole>(roleStore); if (!context.Roles.Any(r => r.Name == "admin")) { var AdminRole = new ApplicationRole("admin"); RoleManager.Create(AdminRole); } if (!context.Roles.Any(r => r.Name == "autor")) { var AutorRole = new ApplicationRole("autor"); RoleManager.Create(AutorRole); } if (!context.Roles.Any(r => r.Name == "MiembroComite")) { var MiembroRole = new ApplicationRole("MiembroComite"); RoleManager.Create(MiembroRole); } if (!context.Roles.Any(r => r.Name == "presidente")) { var presidente = new ApplicationRole("presidente"); RoleManager.Create(presidente); } //Creacion de los usuarios var store = new UserStore <ApplicationUser>(context); var UserManager = new ApplicationUserManager(store); if (!context.Users.Any(u => u.UserName == "*****@*****.**")) { var AdminUser = new ApplicationUser { UserName = "******" }; AdminUser.Email = AdminUser.UserName; UserManager.Create(AdminUser, "Password@123"); UserManager.AddToRole(AdminUser.Id, "admin"); } if (!context.Users.Any(u => u.UserName == "*****@*****.**")) { var AutorUser = new ApplicationUser { UserName = "******" }; AutorUser.Email = AutorUser.UserName; UserManager.Create(AutorUser, "Password@123"); UserManager.AddToRole(AutorUser.Id, "autor"); } //Creacion de papers context.Papers.AddOrUpdate(p => p.Nombre, new Paper() { Nombre = "Microsoft Student Partner", Fecha = DateTime.Now, AreaCientifica = "Informatica", Path = "", Descripcion = "un paper" }, new Paper() { Nombre = "Defusion del CIAA", Fecha = DateTime.Now, AreaCientifica = "Informatica", Path = "", Descripcion = "un paper" }, new Paper() { Nombre = "Arduino: Ventajas y desventajas", Fecha = DateTime.Now, AreaCientifica = "Informatica", Path = "", Descripcion = "un paper" } ); context.SaveChanges(); //Creacion de Autores context.Autores.AddOrUpdate(p => p.Nombre, new Autor() { Nombre = "Fernando Asulay", Papers = new List <Paper>() { context.Papers.First() }, Usuario = UserManager.FindByName("*****@*****.**") } ); }
internal static void Initilize(ApplicationDbContext db) { //var userManager = HttpContext // .Current.GetOwinContext() // .GetUserManager<ApplicationUserManager>(); //var roleManager = HttpContext.Current // .GetOwinContext() // .Get<ApplicationRoleManager>(); var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(db)); var roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(db)); const string roleAdmin = "Admin"; const string roleBroadcast = "BroadCastMessage"; const string AdminName = "*****@*****.**"; const string AdminPassword = "******"; const string BroadCastMessageName = "*****@*****.**"; const string BroadCastMessagePassword = "******"; //Create Role Admin if it does not exist var role = roleManager.FindByName(roleAdmin); if (role == null) { role = new IdentityRole(roleAdmin); var roleresult = roleManager.Create(role); } //Create Role BroadCast if it does not exist role = roleManager.FindByName(roleBroadcast); if (role == null) { role = new IdentityRole(roleBroadcast); var roleresult = roleManager.Create(role); } //Create Default Users var user = userManager.FindByName(AdminName); if (user == null) { user = new ApplicationUser { UserName = AdminName, Email = AdminName }; var result = userManager.Create(user, AdminPassword); result = userManager.SetLockoutEnabled(user.Id, false); } // Add user admin to Role Admin if not already added var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(roleAdmin)) { var result = userManager.AddToRole(user.Id, roleAdmin); } user = userManager.FindByName(BroadCastMessageName); if (user == null) { user = new ApplicationUser { UserName = BroadCastMessageName, Email = BroadCastMessageName }; var result = userManager.Create(user, BroadCastMessagePassword); result = userManager.SetLockoutEnabled(user.Id, false); } // Add user BroadCastMessage to Role BroadCastMessage if not already added rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(roleBroadcast)) { var result = userManager.AddToRole(user.Id, roleBroadcast); } SecurityRoleEntity sRole = new SecurityRoleEntity(); sRole.Name = "BUILTIN\\Users"; sRole.IdentityRole = roleAdmin; db.SecurityRoles.Add(sRole); }
protected override void Seed(ApplicationDbContext context) { #region Seed the roles var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var startupRoles = ConfigurationManager.AppSettings["startupRoles"].Split(';'); foreach (var role in startupRoles) { roleManager.Create(new IdentityRole { Name = role }); } PositionsController sysmgr = new PositionsController(); List <string> employeeroles = sysmgr.Positions_GetList(); foreach (var role in employeeroles) { roleManager.Create(new IdentityRole { Name = role }); } #endregion #region Seed the users string adminUser = ConfigurationManager.AppSettings["adminUserName"]; string adminRole = ConfigurationManager.AppSettings["adminRole"]; string adminEmail = ConfigurationManager.AppSettings["adminEmail"]; string adminPassword = ConfigurationManager.AppSettings["adminPassword"]; var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var result = userManager.Create(new ApplicationUser { UserName = adminUser, Email = adminEmail }, adminPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(adminUser).Id, adminRole); } string userPassword = ConfigurationManager.AppSettings["customerPassword"]; //result = userManager.Create(new ApplicationUser //{ // UserName = "******", // Email = "*****@*****.**", // CustomerId = 4 //}, userPassword); //if (result.Succeeded) // userManager.AddToRole(userManager.FindByName("HansenB").Id, "Customers"); EmployeeController sysmgremp = new EmployeeController(); List <EmployeeList> employeeusernames = sysmgremp.ListOfEmployees(); foreach (var username in employeeusernames) { result = userManager.Create(new ApplicationUser { UserName = username.UserName, Email = username.Email, EmployeeId = username.EmployeeId }, userPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(username.UserName).Id, username.Role); } } #endregion // ... etc. ... base.Seed(context); }
public IdentityResult AssignToRole(string userid, string rolename) { IdentityResult result = manager.AddToRole(userid, rolename); return(result); }
public static void Seed(MedSimDbContext context) { #if !DEBUG throw new NotImplementedException("this should not be being used in a production environment - security changes required"); #endif try { if (!context.Roles.Any()) { //not in production //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, // "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate"); // var roleStore = new RoleStore<AspNetRole, Guid, AspNetUserRole>(context); var roleManager = new RoleManager<AspNetRole, Guid>(roleStore); var role = new AspNetRole { Id = Guid.NewGuid(), Name = RoleConstants.Admin }; roleManager.Create(role); } if (!context.Users.Any()) { var userStore = new CustomUserStore(context); var userManager = new ApplicationUserManager(userStore); var user = new AspNetUser { Email = "*****@*****.**", UserName = "******" }; var result = userManager.Create(user, password: "******"); if (result.Succeeded) { userManager.AddToRole(user.Id, RoleConstants.Admin); } else { throw new DbSeedException(result.Errors); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } }
public async Task <ActionResult> Register(RegisterViewModel model, string[] nombre, string numero_control) { foreach (var texto in nombre) { if (String.IsNullOrEmpty(texto) || String.IsNullOrWhiteSpace(texto)) { ViewBag.Error = "Porfavor no dejes ningun campo sin llenar"; return(View(model)); } } if (String.IsNullOrEmpty(numero_control) || String.IsNullOrWhiteSpace(numero_control)) { ViewBag.Error = "Porfavor no dejes ningun campo sin llenar"; return(View(model)); } var persona_numeroControl = context.Persona.Where(x => x.Numero_control.Equals(numero_control)).FirstOrDefault(); if (persona_numeroControl == null) { ViewBag.Error = "Porfavor verifica el número de control que proporcionaste"; return(View(model)); } else { if (persona_numeroControl.Id_usuario != null) { ViewBag.Error = "El numero de control ya está siendo utilizado por otro usuario"; return(View(model)); } } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FullName = model.FullName + " " + nombre[0] + " " + nombre[1] }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); string rolname = "Alumno"; result = UserManager.AddToRole(user.Id, rolname); persona_numeroControl.Nombre = model.FullName; persona_numeroControl.Apellido_paterno = nombre[0]; persona_numeroControl.Apellido_materno = nombre[1]; persona_numeroControl.Email = model.Email; persona_numeroControl.Id_usuario = user.Id; context.Entry(persona_numeroControl).State = EntityState.Modified; context.SaveChanges(); // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar correo electrónico con este vínculo // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>"); ViewBag.Success = "Registrado correctamente"; return(View()); } AddErrors(result); } // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario return(View(model)); }
public async Task <ActionResult> Tutor(TutorRegisterViewModel model) { if (ModelState.IsValid) { var _existUser = await UserManager.FindByEmailAsync(model.Email); if (_existUser != null) { await UserManager.UpdateAsync(_existUser); ViewBag.Message = "Email Already Exists."; ModelState.AddModelError("", "Email Already Exists."); return(View(model)); } //profile upload if (model.File != null) { //var supportedTypes = new[] { "jpg", "jpeg", "png", "gif" }; //var fileExt = System.IO.Path.GetExtension(model.File.FileName).Substring(1); try { var supportedTypes = new[] { "jpg", "jpeg", "png", "gif", "tif" }; var fileExt = System.IO.Path.GetExtension(model.File.FileName).Substring(1); if (supportedTypes.Contains(fileExt.ToLower())) { var profileImage = Guid.NewGuid() + Path.GetExtension(model.File.FileName); model.File.SaveAs(HttpContext.Server.MapPath("~/Content/images/tutor/") + profileImage); model.ProfileImage = profileImage; } } catch (Exception exi) { } } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Title = model.Title, Gender = model.Gender, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.Mobile, Address = model.Address == null ? model.City + " " + model.Country + " " + model.Zip : model.Address, City = model.City, TimeZone = model.TimeZone, Country = model.Country, Zip = model.Zip, Bio = model.Bio, //summary Hobbies = model.Hobbies, ProfileImage = model.ProfileImage, //DOB = DateTime.Now.AddYears(-29), CreatedDate = DateTime.Now, //UpdatedDate = DateTime.Now }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, "Tutor"); var __tutor = await this._accountService.CreateTutorsAsync(new Tutors { UserId = user.Id, Experience = model.Experience, GradeLevel = model.GradeLevel, NameOfSchool = model.GradeLevel, //Concerns PreviousSubjects = model.GradeLevel }); try { if (model.TuitionSubjects != null && __tutor.Id > 0) { await this._accountService.AddTutorSubjectAsync(model.TuitionSubjects, __tutor.Id); } } catch (Exception ex) { } //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Hi " + model.FirstName + ",<br/><br/>" + "Thanks for registering with us.<br/>" + "Please confirm your tutor account by clicking <a href=\"" + callbackUrl + "\">" + callbackUrl + "</a><br/><br/>" + "Regards, <br/><a href='http://instanttutors.org/' target='_blank'>Instant Tutors Team</a>"); //await EmailSender.SendEmailAsync("Confirm your account", "Hi " + model.FirstName + ",<br/><br/>" // + "Thanks for registering with us.<br/>" // + "Please confirm your student account by clicking <a href=\"" + callbackUrl + "\">" + callbackUrl + "</a><br/><br/>" // + "Regards, <br/><a href='http://instanttutors.org/' target='_blank'>Instant Tutors @" + DateTime.Now.Year + "</a>", user.Email, true); try { var _subject = "New Tutor Signup | instanttutors.org"; var _body = "<h5>New Tutor Signup</h5>" + ",<br/><br/>" + "<b>Fullname:</b> " + model.FirstName + " " + model.LastName + "<br/>" + "<b>Email Address:</b> " + model.Email + "<br/>" + "<b>Mobile:</b> " + model.Mobile + "<br/><br/>" + "<a href='http://instanttutors.org/' target='_blank'>Instant Tutors</a> @ " + DateTime.Now.Year; await EmailSender.SendEmailAsync(_subject, _body); await SMSSender.SMSSenderAsync("Thanks! Please verify your tutor a/c " + callbackUrl + " <br>Instant Tutors Team", user.PhoneNumber); await SMSSender.SMSSenderAsync("New Tutor Registration - Name: " + user.FirstName + " " + user.LastName + ", M: " + user.PhoneNumber + ", Email: " + user.Email); } catch { } ModelState.Clear(); ViewBag.success = "<ul><li><p style='color:green'>Successfully registered!! An email has been sent to your email address, Please verify.</p></li></ul>"; return(View(model)); } AddErrors(result); } //var error = ModelState.FirstOrDefault(x => x.Value.Errors.Count > 0).Value.Errors.First().ErrorMessage; // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// When the user clicks the Save button, save the changes to the user /// </summary> /// <param name="sender">The submitUser control</param> /// <param name="e">The Click event</param> protected void submitUser_Click(object sender, EventArgs e) { //Make sure the current user is correct currentUser = manager.FindById(currentUser.Id); //Whether or not the email changed bool emailChanged = false; //Only continue if the page is valid if (ASPxEdit.AreEditorsValid(this, submitUser.ValidationGroup)) { //Check to see if the user's email changed if (currentUser.Email != Convert.ToString(txtEmail.Value)) { //The email changed emailChanged = true; } //Only de-confirm the user's phone if it changed if (txtPhoneNumber.Value == null || (currentUser.PhoneNumber != txtPhoneNumber.Value.ToString())) { currentUser.PhoneNumberConfirmed = false; } //Update the user's role if (currentUser.Roles.FirstOrDefault().RoleId != Convert.ToString(ddIdentityRole.Value)) { //Get the old role and new role string oldRole = appContext.Roles.Find(currentUser.Roles.FirstOrDefault().RoleId).Name; string newRole = appContext.Roles.Find(Convert.ToString(ddIdentityRole.Value)).Name; //Change the role manager.RemoveFromRole(currentUser.Id, oldRole); manager.AddToRole(currentUser.Id, newRole); } //Set the user's information currentUser.EmailConfirmed = !emailChanged; currentUser.PhoneNumber = (txtPhoneNumber.Value == null ? null : txtPhoneNumber.Value.ToString()); currentUser.Email = txtEmail.Value.ToString(); currentUser.FirstName = txtFirstName.Value.ToString(); currentUser.LastName = txtLastName.Value.ToString(); currentUser.LockoutEndDateUtc = (String.IsNullOrWhiteSpace(Convert.ToString(deLockoutEndDate.Value)) ? (DateTime?)null : Convert.ToDateTime(deLockoutEndDate.Value)); currentUser.UpdateTime = DateTime.Now; //Update the user in the database IdentityResult result = manager.Update(currentUser); if (result.Succeeded) { //Send an email if the email changed if (emailChanged) { //Generate the confirmation token and url string code = manager.GenerateEmailConfirmationToken(currentUser.Id); string callbackUrl = IdentityHelper.GetEmailConfirmationRedirectUrl(code, currentUser.Id, Request); //Send the confirmation email to the user via email manager.SendEmail(currentUser.Id, "Confirm your email address change", Utilities.GetEmailHTML(callbackUrl, "Confirm Email", true, "Email Updated", "Please confirm your email address change by clicking the Confirm Email link below.", Request)); } //Redirect the user to the user management page Response.Redirect("/Admin/UserManagement.aspx?message=EditUserSuccess"); } else { //Show the user an error message msgSys.ShowMessageToUser("danger", "Error", result.Errors.FirstOrDefault(), 120000); } } }
protected override void Seed(ApplicationDbContext context) { #region Seed the Roles var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var startupRoles = ConfigurationManager.AppSettings["startupRoles"].Split(';'); foreach (var role in startupRoles) { roleManager.Create(new IdentityRole { Name = role }); } #endregion #region Seed the Users //Administrators string adminUserName = ConfigurationManager.AppSettings["adminUserName"]; string adminRole = ConfigurationManager.AppSettings["adminRole"]; string adminEmail = ConfigurationManager.AppSettings["adminEmail"]; string adminPassword = ConfigurationManager.AppSettings["adminPassword"]; var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var result = userManager.Create(new ApplicationUser { UserName = adminUserName, Email = adminEmail }, adminPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(adminUserName).Id, adminRole); } //CrewLeaders string crewLeaderUserName = ConfigurationManager.AppSettings["crewLeaderUserName"]; string crewLeaderRole = ConfigurationManager.AppSettings["crewLeaderRole"]; string crewLeaderEmail = ConfigurationManager.AppSettings["crewLeaderEmail"]; string crewLeaderPassword = ConfigurationManager.AppSettings["crewLeaderPassword"]; result = userManager.Create(new ApplicationUser { UserName = crewLeaderUserName, Email = crewLeaderEmail, EmployeeId = 36 }, crewLeaderPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(crewLeaderUserName).Id, crewLeaderRole); } //Procurement //FieldEmployee //Gardener //TeamLeader string teamLeaderUserName = ConfigurationManager.AppSettings["teamLeaderUserName"]; string teamLeaderPassword = ConfigurationManager.AppSettings["teamLeaderPassword"]; string teamLeaderRole = ConfigurationManager.AppSettings["teamLeaderRole"]; string teamLeaderEmail = ConfigurationManager.AppSettings["teamLeaderEmail"]; result = userManager.Create(new ApplicationUser { UserName = teamLeaderUserName, Email = teamLeaderEmail }, teamLeaderPassword); if (result.Succeeded) { userManager.AddToRole(userManager.FindByName(teamLeaderUserName).Id, teamLeaderRole); } #endregion }
public void CreateRolesAndUsers() { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>()); var appDbContext = new ApplicationDbContext(); var appUserStore = new ApplicationUserStore(appDbContext); var userManager = new ApplicationUserManager(appUserStore); //Create Admin Role if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); } //Create Admin User if (userManager.FindByName("admin") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Admin"); } } //-------------------------------------------------------------- //Create Manager Role if (!roleManager.RoleExists("Agent")) { var role = new IdentityRole(); role.Name = "Agent"; roleManager.Create(role); } //Create Manager User if (userManager.FindByName("agent") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Agent"); } } //------------------------------------------------------------------- //Create Business Owner Role if (!roleManager.RoleExists("Business Onwer")) { var role = new IdentityRole(); role.Name = "Business Owner"; roleManager.Create(role); } //Create Business owner User if (userManager.FindByName("business") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Business Owner"); } } //------------------------------------------------------------------- //Create Investor Role if (!roleManager.RoleExists("Investor")) { var role = new IdentityRole(); role.Name = "Investor"; roleManager.Create(role); } //Create Business owner User if (userManager.FindByName("business") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Investor"); } } //------------------------------------------------------------------- //Create Auditor Role if (!roleManager.RoleExists("Auditor")) { var role = new IdentityRole(); role.Name = "Auditor"; roleManager.Create(role); } //Create Business owner User if (userManager.FindByName("auditor") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Auditor"); } } //------------------------------------------------------------------- //Create accountant Role if (!roleManager.RoleExists("Accountant")) { var role = new IdentityRole(); role.Name = "Accountant"; roleManager.Create(role); } //Create Business owner User if (userManager.FindByName("accountant") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Accountant"); } } //------------------------------------------------------------------- //Create recoverer Role if (!roleManager.RoleExists("Recoverer")) { var role = new IdentityRole(); role.Name = "Recoverer"; roleManager.Create(role); } //Create recoverer User if (userManager.FindByName("recoverer") == null) { var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPassword = "******"; var chkUser = userManager.Create(user, userPassword); if (chkUser.Succeeded) { userManager.AddToRole(user.Id, "Recoverer"); } } }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); var user = new ApplicationUser { UserName = model.Email, Email = model.Email}; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { manager.AddToRole(user.Id, "Default"); if(User.IsInRole("Admin")) { TempData["ValidationMessage"] = ("Success: " + " " + user.UserName + " " + "Was Created"); return RedirectToAction("Index", "User"); } else { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToAction("Index", "Home"); } } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }