private int AddNewUsers() { int nUsers = 0; // Process each row, create new user int row; string[] colData; bool skip = false; row = Start-1; UserRolesHelper helper = new UserRolesHelper(); var store = new UserStore<ApplicationUser>(db); UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(store); string defaultPassword = "******"; while (++row < (Count + Start)) { skip = false; if (Source[row][0] != ';') { // Valid row to process, so get columns // // DON'T TRIM THE ROW!! If it's trimmed, the column positions will NOT line up with // what is expected, resulting in a crash! // colData = Source[row].Split('\t'); // Create a new User object, fill in the data int nRequireds = 0; // Used to show all required fields exist string data; ApplicationUser user = new ApplicationUser(); // FirstName if (this.HeadingOffsets[(int)H.U_FirstName] >= 0) { if ((user.FirstName = colData[HeadingOffsets[(int)H.U_FirstName]]) != "") { nRequireds++; } } // LastName if (this.HeadingOffsets[(int)H.U_LastName] >= 0) { if ((user.LastName = colData[HeadingOffsets[(int)H.U_LastName]]) != "") { nRequireds++; } } // If we don't have either a First or Last name, show error.. if (nRequireds == 0) { Section.LogErr(db, "Row " + (row+1) + " needs either FirstName or LastName -- cannot process this row"); skip = false; } // UserName if (this.HeadingOffsets[(int)H.U_UserName] >= 0) { if ((user.UserName = colData[HeadingOffsets[(int)H.U_UserName]]) == "") { // If there's no UserName, exit now! Section.LogErr(db, "Row " + row + " must have a unique UserName -- cannot process this row"); skip = false; } } // DisplayName if (this.HeadingOffsets[(int)H.U_DisplayName] >= 0) { // If no display name, use UserName if ((data = colData[HeadingOffsets[(int)H.U_DisplayName]]) == "") data = user.UserName; user.DisplayName = data; } // SkillLevel if (this.HeadingOffsets[(int)H.U_SkillLevel] >= 0) { // Setup SkillLevel data = colData[HeadingOffsets[(int)H.U_SkillLevel]]; int pos = FindPos(data, Skills.ToList()); if (pos < 0) { // Not valid, show error Section.LogAlert(db, "Row " + (row+1) + ": setting default SkillLevel to Junior"); pos = 0; } user.SkillLevelId = pos + 1; } else user.SkillLevelId = 1; // Email if (this.HeadingOffsets[(int)H.U_Email] >= 0) { if ((user.Email = colData[HeadingOffsets[(int)H.U_Email]]) == "") { Section.LogErr(db, "Row " + (row+1) + " must have a valid Email -- cannot process this row"); skip = true; } } // PhoneNumber if (this.HeadingOffsets[(int)H.U_Phone] >= 0) { user.PhoneNumber = user.TextMsgNumber = colData[HeadingOffsets[(int)H.U_Phone]]; } // User is complete, so save if unique if (!skip) { // Before creating an account, see if this user name is already being used var x2 = db.Users.FirstOrDefault(u => u.UserName == user.UserName); if (x2 == null) { // OK to continue, this will be a new user bool addedUser = false; try { manager.Create(user, defaultPassword); addedUser = true; } catch (Exception e) { skip = true; addedUser = false; } // Need to ensure the user was created try { // See if user is in the db... if not, save again! var x = db.Users.FirstOrDefault(u => u.UserName == user.UserName); if (x == null) { var u = db.Users.Add(user); db.SaveChanges(); addedUser = true; } } catch (Exception e) { string msg = "Row " + (row + 1) + " could not be processed"; LogErr(db, msg); skip = true; addedUser = false; } if (addedUser) nUsers++; // Now add any user roles specified... if (!skip) { LogSuccess(db, "Added User [" + user.UserName + "] from row " + (row + 1)); int nRoles = 0; // Admin if (this.HeadingOffsets[(int)H.U_RoleAdmin] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleAdmin]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Admin)) { helper.AddUserToRole(user.Id, R.Admin); nRoles++; } } } // PM if (this.HeadingOffsets[(int)H.U_RoleProjectManager] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleProjectManager]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.PM)) { helper.AddUserToRole(user.Id, R.PM); nRoles++; } } } // Dev if (this.HeadingOffsets[(int)H.U_RoleDeveloper] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleDeveloper]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Dev)) { helper.AddUserToRole(user.Id, R.Dev); nRoles++; } } } // Submitter if (this.HeadingOffsets[(int)H.U_RoleSubmitter] > 0) { data = colData[HeadingOffsets[(int)H.U_RoleSubmitter]].ToUpper(); if (data == "Y") { if (!helper.IsUserInRole(user.Id, R.Submitter)) { helper.AddUserToRole(user.Id, R.Submitter); nRoles++; } } } // If no roles, add Submitter if (nRoles == 0) if (!helper.IsUserInRole(user.Id, R.Submitter)) helper.AddUserToRole(user.Id, R.Submitter); } } else { Section.LogAlert(db, "UserName [" + user.UserName + "] on row " + (row + 1) + " already in database, will be skipped"); } } } } return nUsers; }
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) { // Let's make this user a Submitter... UserRolesHelper helper = new UserRolesHelper(); helper.AddUserToRole(user.Id, R.Submitter); 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>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult ManageUsers(string submit, string[] Select) { if (submit == "Cancel") return RedirectToAction("Index"); if (ModelState.IsValid) { // Make sure there is still somebody with Admin privileges!! // So, scoop everything up first and recreate the original model if (Select != null) { // The first string should be the actions, to parse it string[] roles = Select[0].Split('~'); // Find where Admin is so we can make sure somebody is still Admin! int posAdmin = Array.IndexOf(roles, R.Admin); int nRoles; List<ManageUsersData> muList = new List<ManageUsersData>(); bool isAdminChecked = false; if (posAdmin > -1) { // We found the Admin role, assume at this point the list of roles is correct nRoles = roles.Count() - 1; // Now, each User is represented by his Id, followed by a T or F for each role he is // currently enrolled in. So now, reconvert all the data back to the original mode, with // the new int index = 1; while (index < Select.Length) { // Scoop up all the returned data ManageUsersData mu = new ManageUsersData(nRoles); // Get the user Id mu.Id = Select[index++]; // Now get all the original settings for roles... for (int z = 0; z < nRoles; z++) { mu.OrigRoles[z] = Select[index][z] == 'T' ? true : false; } index++; // Advance to next line // Now get any checked roles... int num; while (index < Select.Length && Select[index].Length < 32) { // The next char is an index represented a selected role if (Int32.TryParse(Select[index], out num)) { mu.NewRoles[num] = true; index++; } else { break; } } if (mu.NewRoles[posAdmin]) { isAdminChecked = true; } // Add this mu to the list muList.Add(mu); } if (!isAdminChecked) { // Need to keep an Admin! return RedirectToAction("NeedAdmin"); } // Now, we are ready to update all the roles for each user UserRolesHelper helper = new UserRolesHelper(); foreach (var mu in muList) { // See if any role changed... for (int i = 0; i < nRoles; i++) { if (mu.NewRoles[i] != mu.OrigRoles[i]) { // Role changed... if (mu.NewRoles[i]) { helper.AddUserToRole(mu.Id, roles[i]); } else { helper.RemoveUserFromRole(mu.Id, roles[i]); } } } } // All went according to plan, so return to Main Menu! return RedirectToAction("Index"); } } } return RedirectToAction("UsersPostError"); }