当前位置: 首页>>代码示例>>C#>>正文


C# UserPrincipal.SetPassword方法代码示例

本文整理汇总了C#中System.DirectoryServices.AccountManagement.UserPrincipal.SetPassword方法的典型用法代码示例。如果您正苦于以下问题:C# UserPrincipal.SetPassword方法的具体用法?C# UserPrincipal.SetPassword怎么用?C# UserPrincipal.SetPassword使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.DirectoryServices.AccountManagement.UserPrincipal的用法示例。


在下文中一共展示了UserPrincipal.SetPassword方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: createUsers

        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 = "Acce1234!";

                        userPrincipal.SetPassword(pwdOfNewlyCreatedUser);
                        userPrincipal.Enabled = true;
                        userPrincipal.PasswordNeverExpires = true;
                        userPrincipal.Save();
                    }
                    catch (Exception ex)
                    {
                        Errors.Log(ex);
                    }
                }
            }
        }
开发者ID:tillys,项目名称:SPDG,代码行数:31,代码来源:AD.cs

示例2: CreateUser

        /// <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();

            }
        }
开发者ID:PF2000,项目名称:AppLabRedes,代码行数:34,代码来源:ADManager.cs

示例3: AddUser

        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();
        }
开发者ID:cpm2710,项目名称:cellbank,代码行数:29,代码来源:UserHelper.cs

示例4: When_Creating_Home_Directory__Then_It_Should_Have_The_Appropriate_Rights

        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();
        }
开发者ID:bisand,项目名称:IISAdmin,代码行数:31,代码来源:FileSystemTests.cs

示例5: CreateLocalUser

 /// <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();
 }
开发者ID:Jeremiahf,项目名称:wix3,代码行数:17,代码来源:UserVerifier.cs

示例6: UserAuthenticatorFixture

 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");
     }
 }
开发者ID:AgileSight,项目名称:ActiveDirectoryForCloud,代码行数:12,代码来源:UserAuthenticatorFixture.cs

示例7: Create

 /// <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();
     }
 }
开发者ID:alexsharoff,项目名称:windows-service-toolkit,代码行数:23,代码来源:SAMUserAccounts.cs

示例8: CreateLocalWindowsAccount

 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;
     }
 }
开发者ID:rohansen,项目名称:userhelper,代码行数:19,代码来源:UserManagement.cs

示例9: ChangePassword

 // 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;
 }
开发者ID:nadams810,项目名称:accountmanagementengine,代码行数:21,代码来源:WindowsEngine.cs

示例10: createUser

 /// <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;
     }
 }
开发者ID:macnlinux,项目名称:userManagement,代码行数:29,代码来源:userManagement.cs

示例11: CreateUserIfNotPresent

        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();
            }
        }
开发者ID:bhaeussermann,项目名称:NLog,代码行数:17,代码来源:ImpersonatingTargetWrapperTests.cs

示例12: crearEstudiante2

        //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;
            }
        }
开发者ID:hrbie,项目名称:ModulosTI,代码行数:37,代码来源:ConexionAD.cs

示例13: CreateSimpleAdUser

        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;
            }
//.........这里部分代码省略.........
开发者ID:aleks19921015,项目名称:UnitApis,代码行数:101,代码来源:AdHelper.cs

示例14: SaveUser

        //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)
//.........这里部分代码省略.........
开发者ID:aleks19921015,项目名称:UnitApis,代码行数:101,代码来源:AdHelper.cs

示例15: CreateOrGetUserPrincipal

        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));
        }
开发者ID:hellyhe,项目名称:pgina,代码行数:27,代码来源:LocalAccount.cs


注:本文中的System.DirectoryServices.AccountManagement.UserPrincipal.SetPassword方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。