Example #1
1
File: AD.cs Project: tillys/SPDG
        public static void createUsers(string domain, string ou, int numOfUsers)
        {
            ContextType contextType = ContextType.Domain;

            using (PrincipalContext ctx = new PrincipalContext(contextType, domain, ou))
            {
                for(int i=0; i<numOfUsers; i++)
                {
                    try
                    {
                        UserPrincipal userPrincipal = new UserPrincipal(ctx);
                        userPrincipal.Surname = SampleData.GetSampleValueRandom(SampleData.LastNames);
                        userPrincipal.GivenName = SampleData.GetSampleValueRandom(SampleData.FirstNames); ;
                        userPrincipal.SamAccountName = userPrincipal.GivenName.ToLower() + "." + userPrincipal.Surname.ToLower();
                        userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname;
                        userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname;

                        string pwdOfNewlyCreatedUser = "******";

                        userPrincipal.SetPassword(pwdOfNewlyCreatedUser);
                        userPrincipal.Enabled = true;
                        userPrincipal.PasswordNeverExpires = true;
                        userPrincipal.Save();
                    }
                    catch (Exception ex)
                    {
                        Errors.Log(ex);
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// To Create users
        /// </summary>
        /// <param name="txt">textbox to warnings</param>
        /// <param name="userLogonName">username</param>
        /// <param name="userPassword"></param>
        /// <param name="datetime">account expiration date</param>
        /// <returns>true if users if deleted sucessfully </returns>
        public void CreateUser(StringBuilder sb, string userLogonName, string userPassword)
        {
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;
            principalContext = context;

            // Check if user object already exists in the store
            UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName);
            if (usr == null){
                // Create the new UserPrincipal object
                UserPrincipal userPrincipal = new UserPrincipal(context);
                // username
                userPrincipal.SamAccountName = userLogonName;
                // Expiring date
                // userPrincipal.AccountExpirationDate = datetime;
                //Password
                userPrincipal.SetPassword(userPassword);
                //Activate the account
                userPrincipal.Enabled = true;
                //cant change the password
                userPrincipal.UserCannotChangePassword = true;

                userPrincipal.Save();

            }
        }
Example #3
0
        public static void AddUser(SBSUser user)
        {
            UserPrincipal userPrincipal = new UserPrincipal(Context);
            //if (lastName != null && lastName.Length > 0)
            userPrincipal.Surname = user.UserName;

            //if (firstName != null && firstName.Length > 0)
            userPrincipal.GivenName = user.UserName;

            //if (employeeID != null && employeeID.Length > 0)
            //    userPrincipal.EmployeeId = employeeID;

            //if (emailAddress != null && emailAddress.Length > 0)
            userPrincipal.EmailAddress = user.Email;

            //if (telephone != null && telephone.Length > 0)
            //    userPrincipal.VoiceTelephoneNumber = telephone;

            //if (userLogonName != null && userLogonName.Length > 0)
            userPrincipal.SamAccountName = user.UserName;

            string pwdOfNewlyCreatedUser = user.PassWord;
            userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

            userPrincipal.Enabled = true;
            userPrincipal.ExpirePasswordNow();

            userPrincipal.Save();
        }
Example #4
0
        public void When_Creating_Home_Directory__Then_It_Should_Have_The_Appropriate_Rights()
        {
            var username = string.Format("testUser{0}", DateTime.Now.Millisecond);
            var administration = new AdministrationService();
            var context = new PrincipalContext(ContextType.Machine);
            var user = new UserPrincipal(context)
                           {
                               Name = username,
                               UserCannotChangePassword = false,
                               PasswordNeverExpires = true,
                           };
            user.SetPassword("!Password123");
            user.Save();

            GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS");
            if (grp != null)
            {
                grp.Members.Add(user);
                grp.Save();
            }

            Assert.IsNotNull(grp);
            string dir = Path.Combine(ConfigurationManager.AppSettings["HomeDirectory"], username);
            administration.MkDir(username, dir);

            bool exists = Directory.Exists(dir);
            Assert.IsTrue(exists);

            Directory.Delete(dir);
            user.Delete();
        }
Example #5
0
 /// <summary>
 /// Create a local user on the machine
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="password"></param>
 /// <remarks>Has to be run as an Admin</remarks>
 public static void CreateLocalUser(string userName, string password)
 {
     DeleteLocalUser(userName);
     UserPrincipal newUser = new UserPrincipal(new PrincipalContext(ContextType.Machine));
     newUser.SetPassword(password);
     newUser.Name = userName;
     newUser.Description = "New test User";
     newUser.UserCannotChangePassword = true;
     newUser.PasswordNeverExpires = false;
     newUser.Save();
 }
 public UserAuthenticatorFixture()
 {
     var identity = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine), IdentityType.SamAccountName, "adtest");
     if (identity == null)
     {
         var principal = new UserPrincipal(new PrincipalContext(ContextType.Machine));
         principal.SamAccountName = "adtest";
         principal.DisplayName = "ad test";
         principal.Save();
         principal.SetPassword("password");
     }
 }
 /// <summary>
 /// Создать пользователя, с указанным именем и паролем.
 /// </summary>
 /// <param name="username">Имя пользователя</param>
 /// <param name="password">Пароль</param>
 public void Create(string username, string password)
 {
     using (UserPrincipal user = new UserPrincipal(new PrincipalContext(ContextType.Machine)))
     {
         user.SamAccountName = username;
         if (password.Length == 0)
         {
             user.PasswordNotRequired = true;
         }
         else
         {
             user.SetPassword(password);
             user.PasswordNeverExpires = true;
         }
         user.Enabled = true;
         user.Save();
     }
 }
Example #8
0
 public void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool disablePWChange, bool pwdNeverExpires, UserPrincipal user)
 {
     try
     {
         user.SetPassword(password);
         user.DisplayName = displayName;
         user.Name = username;
         user.Description = description;
         user.UserCannotChangePassword = disablePWChange;
         user.PasswordNeverExpires = pwdNeverExpires;
         user.Save();
         BatchState.State = UserProcessState.WIN_USER_OK;
     }
     catch (Exception)
     {
         BatchState.State = UserProcessState.WIN_USER_ERROR;
         throw;
     }
 }
 // Adapted from http://www.snippetdirectory.com/csharp/changing-password-of-a-local-or-domain-user/
 public bool ChangePassword(string username, string oldpass, string newpass)
 {
     PrincipalContext insPrincipalContext = null;
     if (this.options.Keys.Contains("location") && this.options["location"] == "local")
     {
         insPrincipalContext = new PrincipalContext(ContextType.Machine);//Connecting to local computer.
     }
     else if (this.options.Keys.Contains("location") && this.options["location"] == "domain")
     {
         insPrincipalContext = new PrincipalContext(ContextType.Domain, this.options["domain"], this.options["ads"]);//Connecting to Active Directory
     }
     UserPrincipal insUserPrincipal = new UserPrincipal(insPrincipalContext);
     insUserPrincipal.Name = username;
     PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
     insUserPrincipal = insPrincipalSearcher.FindOne() as UserPrincipal;
     insUserPrincipal.SetPassword(newpass);
     insUserPrincipal.Save();
     insUserPrincipal.Dispose();
     return true;
 }
 /// <summary>
 /// Creates an Active Directory user using a firstName.lastName convention in the default Users container for the domain 
 /// </summary>
 /// <param name="firstName"></param>
 /// <param name="lastName"></param>
 /// <returns>UserPrincipal</returns>
 public static UserPrincipal createUser(string firstName, string lastName, string password)
 {
     try
     {
         PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.domain, Properties.Settings.Default.domainLDAPbase);
         UserPrincipal newUser = new UserPrincipal(domainContext);
         newUser.GivenName = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName);
         newUser.Surname = new CultureInfo("en-US").TextInfo.ToTitleCase(lastName);
         string display = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName + " " + lastName);
         newUser.Name = display;
         newUser.DisplayName = display;
         newUser.SamAccountName = firstName.ToLowerInvariant() + "." + lastName.ToLowerInvariant();
         newUser.Save();
         newUser.SetPassword(password);
         newUser.ExpirePasswordNow();
         newUser.Enabled = true;
         return newUser;
     }
     catch (System.DirectoryServices.DirectoryServicesCOMException ex)
     {
         throw ex;
     }
 }
        private void CreateUserIfNotPresent()
        {
            using (var context = new PrincipalContext(ContextType.Machine, Localhost))
            {
                if (UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser) != null)
                    return;

                var user = new UserPrincipal(context);
                user.SetPassword(NLogTestUserPassword);
                user.Name = NLogTestUser;
                user.Save();

                var group = GroupPrincipal.FindByIdentity(context, "Users");
                group.Members.Add(user);
                group.Save();
            }
        }
Example #12
0
        //BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD
        //Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/
        /// <summary>
        /// Método que se encarga de crear un usuario estudiante en Active Directory
        /// </summary>
        /// <param name="estudiante">
        /// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory
        /// </param>
        public Boolean crearEstudiante2(Usuario estudiante)
        {
            String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera;
            try	{

            PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS);
            UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true);
            usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000
            usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio
            usuario.GivenName = estudiante.Nombre;
            usuario.Surname = estudiante.Apellidos;
            usuario.DisplayName = nombre_completo;
            usuario.Description = "Estudiante";
            usuario.HomeDirectory = getHomeDirectoryAD(estudiante);
            usuario.EmailAddress = estudiante.Correo;
            usuario.HomeDrive = "M";
            usuario.PasswordNeverExpires = true;
            usuario.Save();
            usuario.SetPassword(estudiante.Contrasena);
            usuario.Save();
            return true;
            }
            catch (Exception e)
            {
                _conexionBD = new ManejoBD();
                _conexionBD.insertarBitacoraError(e.ToString(), "");
                return false;
            }
        }
Example #13
0
        public static string CreateSimpleAdUser(string username, string password, string name, string description, string adPath = "OU=Users,OU=UNIT,DC=UN1T,DC=GROUP")
        {
            using (WindowsImpersonationContextFacade impersonationContext
               = new WindowsImpersonationContextFacade(
                   nc))
            {
                bool userIsExist = false;
                DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);

                using (directoryEntry)
                {
                    //Если пользователь существует
                    DirectorySearcher search = new DirectorySearcher(directoryEntry);
                    search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
                    SearchResult resultUser = search.FindOne();
                    userIsExist = resultUser != null && resultUser.Properties.Contains("sAMAccountName");
                }

                if (!userIsExist)
                {
                    //Создаем аккаунт в AD
                    using (
                        var pc = new PrincipalContext(ContextType.Domain, "UN1T", adPath))
                    {
                        using (var up = new UserPrincipal(pc))
                        {
                            up.SamAccountName = username;
                            up.UserPrincipalName = username + "@unitgroup.ru";

                            up.SetPassword(password);
                            up.Enabled = true;
                            up.PasswordNeverExpires = true;
                            up.UserCannotChangePassword = true;
                            up.Description = description;
                            //up.DistinguishedName = "DC=unitgroup.ru";
                            try
                            {
                                up.Save();
                            }
                            catch (PrincipalOperationException ex)
                            {

                            }
                            up.UnlockAccount();
                        }
                    }
                }

                directoryEntry = new DirectoryEntry(DomainPath);
                using (directoryEntry)
                {

                    //DirectoryEntry user = directoryEntry.Children.Add("CN=" + username, "user");
                    DirectorySearcher search = new DirectorySearcher(directoryEntry);
                    search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
                    search.PropertiesToLoad.Add("objectsid");
                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("userPrincipalName");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("usergroup");
                    search.PropertiesToLoad.Add("displayname");
                    search.PropertiesToLoad.Add("givenName");
                    search.PropertiesToLoad.Add("sn");
                    search.PropertiesToLoad.Add("title");
                    search.PropertiesToLoad.Add("telephonenumber");
                    search.PropertiesToLoad.Add("homephone");
                    search.PropertiesToLoad.Add("mobile");
                    search.PropertiesToLoad.Add("manager");
                    search.PropertiesToLoad.Add("l");
                    search.PropertiesToLoad.Add("company");
                    search.PropertiesToLoad.Add("department");

                    SearchResult resultUser = search.FindOne();

                    if (resultUser == null) return String.Empty;

                    DirectoryEntry user = resultUser.GetDirectoryEntry();
                    //SetProp(ref user, ref resultUser, "mail", mail);
                    SetProp(ref user, ref resultUser, "displayname", name);
                    SetProp(ref user, ref resultUser, "givenName", username);
                    SetProp(ref user, ref resultUser, "sn", name);
                    SetProp(ref user, ref resultUser, "title", description);
                    //SetProp(ref user, ref resultUser, "telephonenumber", workNum);
                    //SetProp(ref user, ref resultUser, "mobile", mobilNum);
                    SetProp(ref user, ref resultUser, "l", description);
                    SetProp(ref user, ref resultUser, "company", name);
                    SetProp(ref user, ref resultUser, "department", "-");
                    //SetProp(ref user, ref resultUser, "manager", "");
                    //user.Properties["jpegPhoto"].Clear();
                    //SetProp(ref user, ref resultUser, "jpegPhoto", photo);
                    user.CommitChanges();

                    SecurityIdentifier sid = new SecurityIdentifier((byte[])resultUser.Properties["objectsid"][0],
                        0);

                    return sid.Value;

                }
                return String.Empty;
            }
        }
Example #14
0
        //public static void GetEmployeeManager(Employee emp, out string managerUsername)
        //{
        //    managerUsername = String.Empty;
        //    if (emp.Department == null) return;
        //    if (!Department.CheckUserIsChief(emp.Department.Id, emp.Id))
        //    {
        //        managerUsername = emp.Manager != null ? GetLoginFromEmail(emp.Manager.Email) : String.Empty;
        //    }
        //    if (String.IsNullOrEmpty(managerUsername))
        //    {
        //        Department currDep = new Department(emp.Department.Id);
        //        GetParentDepChief(currDep, out managerUsername);
        //    }
        //}
        //public static void GetParentDepChief(Department dep, out string managerUsername)
        //{
        //    managerUsername = String.Empty;
        //    if (dep.ParentDepartment != null && dep.ParentDepartment.Id > 0)
        //    {
        //        var parentDep = new Department(dep.ParentDepartment.Id);
        //        var overManager = new Employee(parentDep.Chief.Id);
        //        managerUsername = GetLoginFromEmail(overManager.Email);
        //        if (String.IsNullOrEmpty(managerUsername))
        //        {
        //            GetParentDepChief(parentDep, out managerUsername);
        //        }
        //    }
        //}
        public static string SaveUser(Employee emp)
        {
            if (!emp.HasAdAccount) return String.Empty;
            using (WindowsImpersonationContextFacade impersonationContext
                = new WindowsImpersonationContextFacade(
                    nc))
            {
                string username = String.IsNullOrEmpty(emp.AdLogin) ? GetLoginFromEmail(emp.Email) : StringHelper.Trim(emp.AdLogin);

                if (String.IsNullOrEmpty(username.Trim())) return string.Empty;
                string mail = StringHelper.Trim(emp.Email);
                string fullName = StringHelper.Trim(emp.FullName);
                string surname = StringHelper.Trim(emp.Surname);
                string name = StringHelper.Trim(emp.Name);
                string position = emp.Position != null ? emp.Position.Id > 0 && String.IsNullOrEmpty(emp.Position.Name) ? new Position(emp.Position.Id).Name : emp.Position.Name : String.Empty;
                string workNum = StringHelper.Trim(emp.WorkNum);
                string mobilNum = StringHelper.Trim(emp.MobilNum);
                string city = emp.City != null ? StringHelper.Trim(emp.City.Name) : String.Empty;
                string org = emp.Organization != null ? emp.Organization.Id > 0 && String.IsNullOrEmpty(emp.Organization.Name) ? new Organization(emp.Organization.Id).Name : emp.Organization.Name : String.Empty;
                string dep = emp.Department != null ? emp.Department.Id > 0 && String.IsNullOrEmpty(emp.Department.Name) ? new Department(emp.Department.Id).Name : emp.Department.Name : String.Empty;
                var photo = emp.Photo != null && emp.Photo.Length > 0 ? emp.Photo : null;
                Employee manager = new Employee(emp.Manager.Id);
                string managerUsername = String.IsNullOrEmpty(manager.AdLogin)
                    ? GetLoginFromEmail(manager.Email)
                    : manager.AdLogin;
                //GetEmployeeManager(emp, out managerUsername);
                string managerName = String.Empty;
                bool userIsExist = false;

                DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);

                using (directoryEntry)
                {
                    //Если пользователь существует
                    DirectorySearcher search = new DirectorySearcher(directoryEntry);
                    search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
                    SearchResult resultUser = search.FindOne();
                    userIsExist = resultUser != null && resultUser.Properties.Contains("sAMAccountName");
                }

                if (!String.IsNullOrEmpty(managerUsername.Trim()))
                {
                    using (directoryEntry)
                    {
                        DirectorySearcher search = new DirectorySearcher(directoryEntry);
                        search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", managerUsername);
                        search.PropertiesToLoad.Add("DistinguishedName");
                        SearchResult resultManager = search.FindOne();
                        if (resultManager != null)
                            managerName = (string)resultManager.Properties["DistinguishedName"][0];
                    }
                }

                if (!userIsExist)
                {
                    //Создаем аккаунт в AD
                    using (
                        var pc = new PrincipalContext(ContextType.Domain, "UN1T", "OU=Users,OU=UNIT,DC=UN1T,DC=GROUP"))
                    {
                        using (var up = new UserPrincipal(pc))
                        {
                            up.SamAccountName = username;
                            up.UserPrincipalName = username + "@unitgroup.ru";
                            up.SetPassword("z-123456");
                            up.Enabled = true;
                            up.ExpirePasswordNow();

                            try
                            {
                                up.Save();
                            }
                            catch (PrincipalOperationException ex)
                            {

                            }
                        }
                    }

                    //Создаем аккаунт в Exchange

                    //Создаем аккаунт в Lync
                }

                //Еще один путь для изменения параметров
                //if (up.GetUnderlyingObjectType() == typeof(DirectoryEntry))
                //{
                //    DirectoryEntry entry = (DirectoryEntry)up.GetUnderlyingObject();
                //        entry.Properties["streetAddress"].Value = address;

                //        entry.CommitChanges();

                //}

                directoryEntry = new DirectoryEntry(DomainPath);
                using (directoryEntry)
                {

                    //DirectoryEntry user = directoryEntry.Children.Add("CN=" + username, "user");
                    DirectorySearcher search = new DirectorySearcher(directoryEntry);
                    search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
                    search.PropertiesToLoad.Add("objectsid");
                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("userPrincipalName");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("usergroup");
                    search.PropertiesToLoad.Add("displayname");
                    search.PropertiesToLoad.Add("givenName");
                    search.PropertiesToLoad.Add("sn");
                    search.PropertiesToLoad.Add("title");
                    search.PropertiesToLoad.Add("telephonenumber");
                    search.PropertiesToLoad.Add("homephone");
                    search.PropertiesToLoad.Add("mobile");
                    search.PropertiesToLoad.Add("manager");
                    search.PropertiesToLoad.Add("l");
                    search.PropertiesToLoad.Add("company");
                    search.PropertiesToLoad.Add("department");
                    //search.PropertiesToLoad.Add("modifyTimeStamp");
                    //search.PropertiesToLoad.Add("whenChanged");
                    //search.PropertiesToLoad.Add("whenCreated");

                    SearchResult resultUser = search.FindOne();

                    if (resultUser == null) return String.Empty;

                    //string s = resultUser.Properties["modifyTimeStamp"][0].ToString();
                    //string s1 = resultUser.Properties["whenChanged"][0].ToString();
                    //string s2 = resultUser.Properties["whenCreated"][0].ToString();
                    //DateTime d = DateTime.FromFileTime((Int64)resultUser.Properties["uSNChanged"][0]);

                    DirectoryEntry user = resultUser.GetDirectoryEntry();
                    //user.Properties["sAMAccountName"].Value =username;
                    //user.Properties["userPrincipalName"].Value =username;
                    SetProp(ref user, ref resultUser, "mail", mail);
                    SetProp(ref user, ref resultUser, "displayname", fullName);
                    SetProp(ref user, ref resultUser, "givenName", surname);
                    SetProp(ref user, ref resultUser, "sn", name);
                    SetProp(ref user, ref resultUser, "title", position);
                    SetProp(ref user, ref resultUser, "telephonenumber", workNum);
                    SetProp(ref user, ref resultUser, "mobile", mobilNum);
                    SetProp(ref user, ref resultUser, "l", city);
                    SetProp(ref user, ref resultUser, "company", org);
                    SetProp(ref user, ref resultUser, "department", dep);
                    SetProp(ref user, ref resultUser, "manager", managerName);
                    user.Properties["jpegPhoto"].Clear();
                    SetProp(ref user, ref resultUser, "jpegPhoto", photo);
                    //using (WindowsImpersonationContextFacade impersonationContext= new WindowsImpersonationContextFacade(nc))
                    //{
                    user.CommitChanges();
                    //}
                    SecurityIdentifier sid = new SecurityIdentifier((byte[])resultUser.Properties["objectsid"][0],
                        0);

                    return sid.Value;

                }
                return String.Empty;
            }
        }
Example #15
0
        private UserPrincipal CreateOrGetUserPrincipal(UserInformation userInfo)
        {
            UserPrincipal user = null;
            if ( ! LocalAccount.UserExists(userInfo.Username) )
            {
                // See note about MS bug in CreateOrGetGroupPrincipal to understand the mix of DE/Principal here:
                using (user = new UserPrincipal(m_machinePrincipal))
                {
                    user.Name = userInfo.Username;
                    user.SetPassword(userInfo.Password);
                    user.Save();

                    // Sync via DE
                    SyncUserPrincipalInfo(user, userInfo);
                    
                    // We have to re-fetch to get changes made via underlying DE
                    return GetUserPrincipal(user.Name);
                }
            }

            user = GetUserPrincipal(userInfo.Username);
            if (user != null)
                return user;
            else
                throw new Exception(
                    String.Format("Unable to get user principal for account that apparently exists: {0}", userInfo.Username));
        }
Example #16
0
 private static void GetOrCreateUser(string username, string password)
 {
     try
     {
         var account = new NTAccount(username);
         var sid = account.Translate(typeof(SecurityIdentifier));
     }
     catch (IdentityNotMappedException)
     {
         using (var principalContext = new PrincipalContext(ContextType.Machine))
         {
             using (var userPrincipal = new UserPrincipal(principalContext))
             {
                 userPrincipal.Name = username;
                 userPrincipal.SetPassword(password);
                 userPrincipal.Save();
             }
         }
     }
 }
Example #17
0
 /// <summary>
 /// Establece la contraseña para un usuario
 /// </summary>
 /// <param name="usuario">Usuario al que se le cambiará la contraseña</param>
 /// <param name="contraseña">Contraseña que se quiere asignar</param>
 public void EstablecerContraseña(UserPrincipal usuario, string contraseña)
 {
     usuario.SetPassword(contraseña);
     usuario.Save();
 }
        /// <summary>
        /// Creates an Active Directory user using a firstName.lastName convention in the specificied OU in the domain by making a copy of an existing user
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="password"></param>
        /// <param name="OU"></param>
        /// <param name="userToCopy"></param>
        /// <returns></returns>
        public static UserPrincipal createUser(string firstName, string lastName, string password, string OU, UserPrincipal userToCopy)
        {
            try
            {
                string LDAPpath = "OU=" + OU + "," + Properties.Settings.Default.domainLDAPbase;
                PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.domain, LDAPpath);
                UserPrincipal newUser = new UserPrincipal(domainContext);
                newUser.GivenName = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName);
                newUser.Surname = new CultureInfo("en-US").TextInfo.ToTitleCase(lastName);
                string display = new CultureInfo("en-US").TextInfo.ToTitleCase(firstName + " " + lastName);
                newUser.Name = display;
                newUser.DisplayName = display;
                newUser.SamAccountName = firstName.ToLowerInvariant() + "." + lastName.ToLowerInvariant();
                string[] upnParts = userToCopy.UserPrincipalName.Split(new Char [] {'@'});
                newUser.UserPrincipalName = newUser.SamAccountName + "@" + upnParts[1];
                newUser.Save();
                newUser.SetPassword(password);
                newUser.ExpirePasswordNow();
                PrincipalSearchResult<Principal> groups = userContext.getGroups(userToCopy.SamAccountName);
                foreach (Principal g in groups)
                {
                    GroupPrincipal group = GroupPrincipal.FindByIdentity(domainContext, g.Name);
                    group.Members.Add(domainContext, IdentityType.UserPrincipalName, newUser.SamAccountName);
                    group.Save();
                }
                string company = getProperty(userToCopy, "Company");
                if (!(string.IsNullOrEmpty(company)))
                {
                    setProperty(newUser, "Company", company);
                }
                string dept = getProperty(userToCopy, "Department");

                newUser.Enabled = true;
                return newUser;
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException ex)
            {
                throw ex;
            }
        }
        private string CreateUser(string username, string password, IEnumerable<Claim> claims)
        {
            var subjectId = Guid.NewGuid().ToString();

            if (string.IsNullOrEmpty(username))
            {
                username = subjectId;
            }

            try
            {
                using (var context = CreatePrincipalContext())
                using (var user = new UserPrincipal(context))
                {
                    user.Name = subjectId;
                    user.UserPrincipalName = username;
                    user.DisplayName = username;

                    var email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);

                    if (email != null)
                    {
                        user.EmailAddress = email.Value;
                    }

                    if (!string.IsNullOrEmpty(password))
                    {
                        user.SetPassword(password);
                    }

                    user.Save();

                    if (!string.IsNullOrEmpty(password))
                    {
                        user.Enabled = true;
                    }

                    user.Save();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error while creating user {username}, exception: {e}");
                throw;
            }

            return subjectId;
        }
Example #20
0
        public results checkMaintUser(settings st1, results rs1)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
            string str1 = "";
            bool changePass = true;
            // find a user
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, decryptByte(st1.adminName));
            if (user == null)
            {
                changePass = false;
                PrincipalContext systemContext = null;
                systemContext = new PrincipalContext(ContextType.Machine, null);
                UserPrincipal userPrincipal = new UserPrincipal(systemContext);
                userPrincipal.Name = decryptByte(st1.adminName);
                userPrincipal.DisplayName = "IT Administrative User";
                userPrincipal.PasswordNeverExpires = true;
                userPrincipal.SetPassword(decryptByte(st1.adminPass));
                userPrincipal.Enabled = true;
                userPrincipal.Save();
                GroupPrincipal groupPrincipal = null;
                groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators");
                groupPrincipal.Members.Add(userPrincipal);
                groupPrincipal.Save();
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(st1.baseKey + "\\" + st1.appKey, true);
                rk.SetValue("p1-1", st1.adminPass, RegistryValueKind.Binary);
                rk.SetValue("pC", DateTime.Now.ToString(),RegistryValueKind.String);
                rs1.Resutl_User_Pass_Changed = DateTime.Now.ToString();

                str1 =str1+ " not found Created";
            }
            else
            {
                str1 = str1 + " Found";
                PrincipalContext systemContext = null;
                systemContext = new PrincipalContext(ContextType.Machine, null);
                GroupPrincipal groupPrincipal = null;
                groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators");
                if (groupPrincipal.Members.Contains(systemContext, IdentityType.SamAccountName, decryptByte(st1.adminName)))
                {
                    str1 = str1 + " Administrator";
                }
                else
                {
                    UserPrincipal usr = UserPrincipal.FindByIdentity(systemContext, decryptByte(st1.adminName));
                    groupPrincipal.Members.Add(usr);
                    groupPrincipal.Save();

                    str1 = str1 + " not Administrator";
                }
            }
            if (ByteArrayCompare(st1.adminPass,st1.adminPass1)!=true && changePass==true)
            {
                try
                {

                    str1 = str1 + " Password does not match";
                    PrincipalContext systemContext = null;
                    systemContext = new PrincipalContext(ContextType.Machine, null);
                    UserPrincipal usr = UserPrincipal.FindByIdentity(systemContext, decryptByte(st1.adminName));
                    usr.ChangePassword(decryptByte(st1.adminPass1), decryptByte(st1.adminPass));
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(st1.baseKey + "\\" + st1.appKey, true);
                    rk.SetValue("p1-1", st1.adminPass, RegistryValueKind.Binary);
                    rk.SetValue("pC", DateTime.Now.ToString(), RegistryValueKind.String);
                    rs1.Resutl_User_Pass_Changed = DateTime.Now.ToString();
                }
                catch(Exception e)
                {
                    str1 = e.Message;
                }

            }
            else { str1 = str1 + " Password OK"; }
            rs1.Result_Maint_User = str1;
            return rs1;
        }
Example #21
0
        /// <summary>
        /// Agrega un nuevo usuario
        /// </summary>
        /// <param name="nombre">Nombre del usuario</param>
        /// <param name="contraseña">Contraseña</param>
        /// <param name="descripción">Descripción de usuario</param>
        public void AgregarUsuario(string nombre, string contraseña, string descripción)
        {
            UserPrincipal nuevoUsuario = new UserPrincipal(_dominio);

            nuevoUsuario.Name = nombre;
            nuevoUsuario.SetPassword(contraseña);
            nuevoUsuario.Description = descripción;

            nuevoUsuario.Save();
            nuevoUsuario.Dispose();
        }
Example #22
0
        public AccountStatus CreateNewLdapAccount(UserInfo userInfo, out string errorText, bool pswdPolicyChk = false)
        {
            errorText = string.Empty;
            if (LdapHelper.LdapAccountExists(userInfo, RootPrincipal))
            {
                return AccountStatus.AccountAlreadyExists;
            }

            try
            {
                userInfo.FirstName = LdapHelper.EscapeChars(userInfo.FirstName);
                userInfo.LastName = LdapHelper.EscapeChars(userInfo.LastName);
                var preNewUserInfo = LdapHelper.GetUniqueFirstNameLastName(userInfo, RootPrincipal);
                var newUser = new UserPrincipal(RootPrincipal)
                {
                    SamAccountName = preNewUserInfo.SamName,
                    DisplayName = String.Format("{0} {1}", preNewUserInfo.FirstName, preNewUserInfo.LastName),
                    Surname = preNewUserInfo.LastName,
                    GivenName = preNewUserInfo.FirstName,
                    UserPrincipalName = preNewUserInfo.Email,
                    EmailAddress = preNewUserInfo.Email,
                };

                if (!String.IsNullOrEmpty(userInfo.Password))
                {
                    newUser.Enabled = true;
                    newUser.PasswordNeverExpires = true;
                    newUser.SetPassword(userInfo.Password);
                }
                else
                {
                    newUser.ExpirePasswordNow();
                }
                newUser.Save();
                return AccountStatus.NewAccount;
            }
            catch (Exception ex)
            {
                errorText = String.Format("Exception creating LDAP account for {0} with exception {1}", userInfo.Email, ex.Message);
                return AccountStatus.AccountCreationFailed;
            }
        }
Example #23
0
        public User Create(User user)
        {
            try
            {
                string ClientPrefix = GetClientPrefix();
                string ClientName = GetClientName(GetClientDN());

                user.UserName = ClientPrefix + '.' + ToASCII(user.FirstName.Split(' ')[0].ToLower()) + '.' + ToASCII(user.LastName.Split(' ')[0].ToLower());
                if (user.UserName.Length >= 20)
                {
                    user.UserName = user.UserName.Substring(0, 20);
                }
                user.Password = GeneratePassword();

                // Create a confined context using the client's Organization Unit 
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Domain"], GetClientDN()))
                {
                    // Create the user
                    UserPrincipal NewUser = new UserPrincipal(context);
                    NewUser.GivenName = user.FirstName;
                    NewUser.Surname = user.LastName;
                    NewUser.Name = user.FirstName + ' ' + user.LastName;
                    NewUser.DisplayName = user.FirstName + ' ' + user.LastName;
                    NewUser.SamAccountName = user.UserName;
                    NewUser.UserPrincipalName = user.UserName + '@' + ConfigurationManager.AppSettings["Domain"];
                    NewUser.EmailAddress = user.EmailAddress;
                    if (user.Description != "")
                    {
                        NewUser.Description = user.Description;
                    }
                    NewUser.SetPassword(user.Password);
                    NewUser.Enabled = user.IsEnabled;
                    NewUser.Save();
                    NewUser.Dispose();

                    // Add the user to the client's security group
                    GroupPrincipal ClientSecurityGroup = GroupPrincipal.FindByIdentity(context, ClientName);
                    ClientSecurityGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                    ClientSecurityGroup.Save();
                }

                // If the user has been marked as administrator, add it to the administrator group
                if (user.IsAdmin)
                {
                    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                    {
                        GroupPrincipal AdminGroup = GroupPrincipal.FindByIdentity(context, ConfigurationManager.AppSettings["AdminGroupName"]);
                        AdminGroup.Members.Add(context, IdentityType.SamAccountName, user.UserName);
                        AdminGroup.Save();
                    }
                }
                return user;
            }
            catch (Exception Error)
            {
                throw Error;
            }
        }
Example #24
0
        /// <summary>
        /// Create AD User in a container
        /// </summary>
        /// <param name="userinfo">ADUser object</param>
        /// <returns></returns>
        public ResponseMessage AddADUser( RequestUserCreate userinfo )
        {
            ResponseMessage status = new ResponseMessage();

            status.IsSuccessful = false;
            status.Message = string.Empty;

            Session stat = ValidateSession( userinfo.DomainInfo.SessionKey );

            if ( stat.IsAuthenticated == true )
            {

                PrincipalContext principalContext = null;

                string uri = FixADURI( userinfo.DomainInfo.ADHost , userinfo.DomainInfo.ContainerPath );

                if ( string.IsNullOrWhiteSpace( uri ) )
                {
                    status.Message = status.Message = "AD Host is not allowed to be empty, kindly provide the AD Host";
                    return status;
                }

                bool isAllowWite = CheckWriteOermission( uri , userinfo.DomainInfo.BindingUserName , userinfo.DomainInfo.BindingUserPassword );

                try
                {
                    UserPrincipal usr = FindADUser( userinfo.UserLogonName , userinfo.DomainInfo );
                    if ( usr != null )
                    {
                        status.Message = " user already exists. Please use a different User Logon Name";
                        return status;
                    }
                    else
                    {
                        principalContext = new PrincipalContext( ContextType.Domain , userinfo.DomainInfo.DomainName , userinfo.DomainInfo.ContainerPath , userinfo.DomainInfo.BindingUserName , userinfo.DomainInfo.BindingUserPassword );
                    }
                }
                catch ( Exception ex )
                {
                    status.Message = @"Failed to create PrincipalContext: " + ex;
                    return status;
                }

                // Create the new UserPrincipal object
                UserPrincipal userPrincipal = new UserPrincipal( principalContext );

                if ( !string.IsNullOrWhiteSpace( userinfo.LastName ) )
                    userPrincipal.Surname = userinfo.LastName;

                if ( !string.IsNullOrWhiteSpace( userinfo.FirstName ) )
                    userPrincipal.GivenName = userinfo.FirstName;

                if ( !string.IsNullOrWhiteSpace( userinfo.LastName ) && !string.IsNullOrWhiteSpace( userinfo.FirstName ) )
                    userPrincipal.DisplayName = userinfo.FirstName + " " + userinfo.LastName;

                if ( !string.IsNullOrWhiteSpace( userinfo.Description ) )
                    userPrincipal.Description = userinfo.Description;

                if ( !string.IsNullOrWhiteSpace( userinfo.EmployeeID ) )
                    userPrincipal.EmployeeId = userinfo.EmployeeID;

                if ( !string.IsNullOrWhiteSpace( userinfo.EmailAddress ) )
                    userPrincipal.EmailAddress = userinfo.EmailAddress;

                if ( !string.IsNullOrWhiteSpace( userinfo.Telephone ) )
                    userPrincipal.VoiceTelephoneNumber = userinfo.Telephone;

                if ( !string.IsNullOrWhiteSpace( userinfo.UserLogonName ) )
                    userPrincipal.SamAccountName = userinfo.UserLogonName;

                if ( !string.IsNullOrWhiteSpace( userinfo.Password ) )
                    userPrincipal.SetPassword( userinfo.Password );

                userPrincipal.Enabled = true;
                userPrincipal.ExpirePasswordNow();

                try
                {
                    userPrincipal.Save();

                    DirectoryEntry de = (DirectoryEntry)userPrincipal.GetUnderlyingObject();

                    FillUserExtraAttributes( ref de , userinfo );

                    de.CommitChanges();
                    status.Message = "Account has been created successfuly";
                    status.IsSuccessful = true;
                }
                catch ( Exception ex )
                {
                    status.Message = "Exception creating user object. " + ex;
                    status.IsSuccessful = false;
                    return status;
                }

                return status;
            }
            else
            {
                status.Message = "Kindly authenticate first";
                return status;
            }
        }
Example #25
0
        public void When_Creating_New_Site__It_Should_Be_Present_In_IIS()
        {
            var username = string.Format("testUser{0}", DateTime.Now.Millisecond);
            const string password = "******";

            var administration = new AdministrationService();
            var context = new PrincipalContext(ContextType.Machine);
            var user = new UserPrincipal(context) {
                Name = username,
                UserCannotChangePassword = false,
                PasswordNeverExpires = true,
            };
            user.SetPassword(password);
            user.Save();

            var grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS");
            if (grp != null)
            {
                grp.Members.Add(user);
                grp.Save();
            }

            Assert.IsNotNull(grp);
            var dir = Path.Combine(ConfigurationManager.AppSettings["HomeDirectory"], username);

            var info = Directory.CreateDirectory(dir);
            var security = info.GetAccessControl();
            security.AddAccessRule(new FileSystemAccessRule(username,
                                                            FileSystemRights.Read |
                                                            FileSystemRights.Write |
                                                            FileSystemRights.Modify |
                                                            FileSystemRights.CreateDirectories |
                                                            FileSystemRights.CreateFiles |
                                                            FileSystemRights.ReadAndExecute,
                                                            InheritanceFlags.ContainerInherit |
                                                            InheritanceFlags.ObjectInherit,
                                                            PropagationFlags.None,
                                                            AccessControlType.Allow));
            info.SetAccessControl(security);

            var server = new IisServer();

            // In order to make this work, you will have to add an entry to your host file or dns...
            const string fqdn = "www.test.com";
            server.AddWebSite(username, password, fqdn, dir, "http", string.Format("*:80:{0}", fqdn));

            using (var serverManager = new ServerManager())
            {
                var site = serverManager.Sites.FirstOrDefault(x => x.Name == fqdn);
                Assert.IsNotNull(site);

                var app = site.Applications.FirstOrDefault();
                Assert.IsNotNull(app);

                var pool = serverManager.ApplicationPools.FirstOrDefault(x => x.Name == fqdn);
                Assert.IsNotNull(pool);

                // Cleaning up...
                app.Delete();
                site.Delete();
                pool.Delete();

                serverManager.CommitChanges();
            }

            // Cleaning up...
            Directory.Delete(dir, true);
            user.Delete();
        }
Example #26
0
        /// <summary>
        /// </summary>
        /// <param name="username"> </param>
        /// <param name="passwd"> </param>
        /// <param name="fqdn"> </param>
        /// <returns> </returns>
        public bool AddUser(string username, string passwd, string fqdn)
        {
            try
            {
                var server = new IisServer();

                // Check if binding allready exists. If it does, return false.
                if(server.BindingExists(fqdn))
                    return false;

                // Retrieving context from local machine.
                var context = new PrincipalContext(ContextType.Machine);

                // Check if user allready exists. Return false if it does.
                var user = UserPrincipal.FindByIdentity(context, username);
                if (user != null)
                    return false;

                // Create user an set some appropriate values.
                user = new UserPrincipal(context)
                               {
                                   Name = username,
                                   UserCannotChangePassword = false,
                                   PasswordNeverExpires = true,
                               };
                user.SetPassword(passwd);

                // Save the newly created user.
                user.Save();

                // Adding new user to the IIS_IUSRS group. Maybe we should add a separate group for each user. Maybe in some other release...
                var grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS");
                if (grp != null)
                {
                    grp.Members.Add(user);
                    grp.Save();
                }

                AddUserRemote(username, passwd);

                // Create the user's root directory.
                var rootHomeDirectory = Path.Combine(AppSettings.HomeDirectory, username);
                var mkDir = MkDir(username, rootHomeDirectory);

                // Adding a new application pool.
                var addApplicationPool = server.AddApplicationPool(username, passwd, fqdn);

                // Adding a new web site.
                var addSite = AddSite(username, fqdn);

                return mkDir & addApplicationPool & addSite;
            }
            catch (Exception ex)
            {
                // Here we could catch different exceptions, and maybe return a more sensable error response.
                Console.WriteLine("An error occured while creating the new user {0}. Exception:{1}", username, ex.Message);
                return false;
            }
        }
Example #27
0
        private static UserPrincipal CreateNewUser(PrincipalContext context, string username, string password, string description)
        {
            UserPrincipal existingUser = UserPrincipal.FindByIdentity(context,
                                                       IdentityType.SamAccountName,
                                                       username);

            if (existingUser != null)
            {
                return null;
            }

            var user = new UserPrincipal(context)
            {
                Name = username,
                DisplayName = username,
                Description = description,
                UserCannotChangePassword = true,
                PasswordNeverExpires = true
            };
            user.SetPassword(password);
            user.Save();
            return user;
        }
Example #28
0
        /*
         * Edit funcations
         */
        private string CreateAdUser(AdUser adUser, string container, List<string> securityGroups)
        {
            string loginId, manager = string.Empty;

            // find the supervisor
            if (!string.IsNullOrEmpty(adUser.ManagerKerb))
            {
                var supervisor = GetUserByEmployeeId(adUser.ManagerKerb);
                if (supervisor != null) manager = supervisor.DistinguishedName;
            }

            using (var upc = new PrincipalContext(ContextType.Domain, Site.ActiveDirectoryServer, container, UserName, Password))
            {
                loginId = CheckForExistingUser(adUser.FirstName, adUser.LastName, upc);

                if (loginId == null)
                {
                    throw new DuplicateNameException("Unable to determine a valid userid for the requested user.");
                }

                var user = new UserPrincipal(upc);
                AutoMapper.Mapper.Map(adUser, user);

                user.SamAccountName = loginId;
                user.UserPrincipalName = string.Format("{0}@caesdo.caes.ucdavis.edu", loginId);
                user.Enabled = true;
                if (adUser.LastName.ToLower() != loginId)
                {
                    user.Name = string.Format("{0}, {1} ({2})", adUser.LastName, adUser.FirstName, loginId);
                }

                user.SetPassword(GeneratePassword(16));

                //if (adUser.NeedsEmail)
                //{
                //    user.EmailAddress = string.Format("{0}@caes.ucdavis.edu", loginId);
                //}

                user.Save();

                foreach (var groupId in securityGroups)
                {
                    AddToGroup(user, groupId);
                }
            }

            // assign attributes that must be done after saving
            using (var ad = new PrincipalContext(ContextType.Domain, Site.ActiveDirectoryServer, container, UserName, Password))
            {
                var user = UserPrincipal.FindByIdentity(ad, loginId);

                // set the extended properties that cannot be done before first save
                user.OfficeLocation(adUser.OfficeLocation);
                user.Manager(manager);

                user.Save();
            }

            return loginId;
        }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            UserPrincipal user = GetUser(username) ?? null;

            if (user == null)
            {
                user = new UserPrincipal(GetPrincipalContext());
                //User Log on Name
                user.SamAccountName = username;
                user.SetPassword(password);
                user.Enabled = true;
                user.UserPrincipalName = username;
                user.GivenName = username;
                user.Surname = username;
                user.EmailAddress = email;
                user.UserCannotChangePassword = false;
                user.DisplayName = username;
                try
                {
                    user.Save();

                    MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now);

                    // Nos conectamos via SSH hacia el servidor de Zimbra
                    SshExec exec = new SshExec("mail.dxstudio.net", "alex");
                    exec.Password = "******";
                    exec.Connect();
                    // Una vez conectados al servidor de Zimbra
                    // estructuramos y armamos el comando Linux
                    // necesario crear el MailBox
                    string strCommand = string.Empty;
                    strCommand = "/opt/zimbra/bin/./zmprov -a admin -p Admin1234 ca " + user.SamAccountName + "@dxstudio.net SoyUnPassword";
                    // Ejecutamos el comando Linux para crear el MailBox
                    strCommand = exec.RunCommand(strCommand);
                    // Cerreamos la Conexion SSH
                    exec.Close();
                    // Enviamos Mensaje de bienvenida
                    SenMail(user.SamAccountName);

                    status = MembershipCreateStatus.Success;
                    return msUser;
                }
                catch (Exception ex)
                {
                    // verificamos que efectivamente no se cree el usuario
                    var usr = GetUser(username) ?? null;
                    if (usr != null)
                        usr.Delete();
                    status = MembershipCreateStatus.UserRejected;
                    return null;
                }
            }
            else
            {
                MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now);
                status = MembershipCreateStatus.DuplicateUserName;
                return msUser;
            }
        }
Example #30
0
        public static bool CreateLocalWindowsAccount(string username, string password, string groupName)
        {
            try
            {
                PrincipalContext context = new PrincipalContext(ContextType.Machine);
                UserPrincipal user = new UserPrincipal(context);
                user.SetPassword(password);
                user.DisplayName = username;
                user.Name = username;
                user.UserCannotChangePassword = true;
                user.PasswordNeverExpires = true;

                user.Save();
                AddUserToGroup(groupName, context, user);
                return true;
            }
            catch(Exception ex)
            {
                Console.WriteLine(@"error creating user" + ex.Message);
                return false;
            }
        }