public LocalPrincipalData CreateUser(string userName) { string rvUserName = null; string rvPassword = null; LocalPrincipalData rv = null; using (var context = new PrincipalContext(ContextType.Machine)) { bool userSaved = false; ushort tries = 0; UserPrincipal user = null; do { try { rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant(); user = new UserPrincipal(context, userName, rvPassword, true); user.DisplayName = "Warden User " + userName; user.Save(); userSaved = true; } catch (PasswordException ex) { log.DebugException(ex); } ++tries; } while (userSaved == false && tries < 5); if (userSaved) { rvUserName = user.SamAccountName; var groupQuery = new GroupPrincipal(context, IIS_IUSRS_NAME); var searcher = new PrincipalSearcher(groupQuery); var iisUsersGroup = searcher.FindOne() as GroupPrincipal; iisUsersGroup.Members.Add(user); iisUsersGroup.Save(); rv = new LocalPrincipalData(rvUserName, rvPassword); } } return rv; }
public LocalPrincipalData CreateUser(string userName) { string rvUserName = null; string rvPassword = null; LocalPrincipalData rv = null; using (var context = new PrincipalContext(ContextType.Machine)) { bool userSaved = false; ushort tries = 0; UserPrincipal user = null; do { try { rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant(); user = new UserPrincipal(context, userName, rvPassword, true); user.DisplayName = "Warden User " + userName; user.Save(); userSaved = true; } catch (PasswordException ex) { log.DebugException(ex); } ++tries; }while (userSaved == false && tries < 5); if (userSaved) { rvUserName = user.SamAccountName; var groupQuery = new GroupPrincipal(context, IIS_IUSRS_NAME); var searcher = new PrincipalSearcher(groupQuery); var iisUsersGroup = searcher.FindOne() as GroupPrincipal; iisUsersGroup.Members.Add(user); iisUsersGroup.Save(); rv = new LocalPrincipalData(rvUserName, rvPassword); } } return(rv); }