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


C# AccountManagement.UserPrincipal类代码示例

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


UserPrincipal类属于System.DirectoryServices.AccountManagement命名空间,在下文中一共展示了UserPrincipal类的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: 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

示例4: ListAllAccounts

        /// <summary>
        /// List all accounts in the Active Directory
        /// </summary>
        /// <param name="domain">Domain</param>
        private static void ListAllAccounts(string domain) {

            try {

                // Construct context to query your Active Directory
                using (var context = new PrincipalContext(ContextType.Domain, domain)) {

                    // Construct UserPrincipal object for this context
                    var userPrincipal = new UserPrincipal(context);

                    // Search and find every user in the system – PrincipalSearcher instance for what we need!
                    using (var searcher = new PrincipalSearcher(userPrincipal)) {

                        var counter = 0u;

                        // Iterate for all users in AD
                        foreach (var result in searcher.FindAll()) {

                            counter++;
                            var de = result.GetUnderlyingObject() as DirectoryEntry;
                            var samAccountName = de.Properties["samAccountName"].Value;
                            var active = IsUserActiveInAD(de);
                            Console.WriteLine("{0}: {1} - {2}", counter, samAccountName, active ? "Yes" : "No");
                        }
                    }
                }
            } catch (PrincipalServerDownException ex) {
                Console.WriteLine(string.Format("Unable to lookup domain: {0}\r\n{1}", domain, ex.ToString()));
            }
        }
开发者ID:p8cakes,项目名称:ActiveDirectoryQuery,代码行数:34,代码来源:Program.cs

示例5: CreateUserPrincipal

        public bool CreateUserPrincipal()
        {
            // Create connection to domain and do a search for the user
            try
            {
                context = new PrincipalContext(ContextType.Domain, givenDomain);

                    UserPrincipal tempUserPrincipal = new UserPrincipal(context);
                    tempUserPrincipal.SamAccountName = givenUserName;

                    // Search for user
                    PrincipalSearcher searchUser = new PrincipalSearcher();
                    searchUser.QueryFilter = tempUserPrincipal;

                    UserPrincipal foundUser = (UserPrincipal)searchUser.FindOne();

                    userPrincipal = foundUser;
                    userGroups = userPrincipal.GetGroups();
                    return true;

            }
            catch (PrincipalServerDownException)
            {
                System.Windows.Forms.MessageBox.Show("Cannot contact the server.");
                return false;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, "Unknown Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
        }
开发者ID:rtjust,项目名称:PastProjects,代码行数:32,代码来源:WinUserInfo.cs

示例6: 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

示例7: 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

示例8: Main

 private static void Main(string[] args)
 {
     var repository = new Repository();
     repository.CreateDatabase();
     using (var context = new PrincipalContext(ContextType.Domain, "infotecs-nt", "lr.knowledge.base", ",jrcnfgjx"))
     {
         UserPrincipal u = new UserPrincipal(context);
         PrincipalSearcher search = new PrincipalSearcher(u);
         foreach (UserPrincipal result in search.FindAll())
         {
             repository.AddUsers(new[]
             {
                 new User()
                 {
                     FirstName = result.DisplayName ?? string.Empty,
                     LastName = string.Empty,
                     MiddleName = string.Empty,
                     ActiveDirectoryId = @"infotecs-nt\" + result.SamAccountName,
                     IsManager = result.IsManager()
                 }
             });
             Console.WriteLine(string.Format("Добавлен пользователь: {0}", result.DisplayName));
             repository.Save();
         }
     }
 }
开发者ID:Sufflavus,项目名称:HaHaton,代码行数:26,代码来源:Program.cs

示例9: GetEnabledUsers

        /// <summary>
        /// Gets a list of enabled users in Active Directory
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static List<Users> GetEnabledUsers()
        {
            List<Users> enabledUsers = new List<Users>(6000);

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Config.ServiceSettings.PrimaryDC, Config.ServiceSettings.Username, Config.ServiceSettings.Password))
            {
                using (UserPrincipal up = new UserPrincipal(pc))
                {
                    up.Enabled = false;

                    using (PrincipalSearcher ps = new PrincipalSearcher(up))
                    {
                        PrincipalSearchResult<Principal> results = ps.FindAll();
                        foreach (Principal r in results)
                        {
                            enabledUsers.Add(new Users()
                            {
                                UserGuid = (Guid)r.Guid,
                                DisplayName = r.DisplayName,
                                UserPrincipalName = r.UserPrincipalName,
                                SamAccountName = r.SamAccountName,
                                DistinguishedName = r.DistinguishedName,
                                IsEnabled = false
                            });
                        }
                    }
                }
            }

            return enabledUsers;
        }
开发者ID:KnowMoreIT,项目名称:CloudPanel-Service,代码行数:38,代码来源:ADActions.cs

示例10: UserPrincipalToUser

        private static User UserPrincipalToUser(UserPrincipal userPrincipal)
        {
            if (userPrincipal == null)
                throw new ArgumentNullException("userPrincipal");

            // Uses most of the built-in properties available as part of the UserPrincipal Object
            // https://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal

            return new User
            {
                // ReSharper disable once PossibleInvalidOperationException
                // This should only be null when the context type is Machine
                UserId = userPrincipal.Guid.GetValueOrDefault(),
                UserPrincipalName = userPrincipal.UserPrincipalName,
                NtUserName = userPrincipal.SamAccountName,
                DistinguishedName = userPrincipal.DistinguishedName,
                AccountIsLocked = userPrincipal.IsAccountLockedOut(),
                AccountIsEnabled = userPrincipal.Enabled,
                AccountIsExpired = userPrincipal.AccountExpirationDate.HasValue && userPrincipal.AccountExpirationDate.Value <= DateTime.UtcNow,
                AccountWillExpire = userPrincipal.AccountExpirationDate.HasValue,
                AccountExpirationDate = userPrincipal.AccountExpirationDate,
                //PasswordIsExpired // TODO: Needs directory information to determine
                PasswordWillExpire = userPrincipal.PasswordNeverExpires, // TODO: This is not definitive, just a high level check
                //PasswordExpirationDate // TODO: Needs directory information to determine
                PasswordLastSetDate = userPrincipal.LastPasswordSet,
                FirstName = userPrincipal.GivenName,
                MiddleName = userPrincipal.MiddleName,
                LastName = userPrincipal.Surname,
                DisplayName = userPrincipal.DisplayName,
                Email = userPrincipal.EmailAddress
            };
        }
开发者ID:jelkinsiv,项目名称:uManage,代码行数:32,代码来源:UserPrincipalExt.cs

示例11: FindByName

        public List<User> FindByName(string pattern)
        {
            UserPrincipal filterCriteria = new UserPrincipal(context);

            filterCriteria.Name = pattern;
            return FindMatching(filterCriteria);
        }
开发者ID:kaiwren,项目名称:shaker,代码行数:7,代码来源:UserFilter.cs

示例12: CastLdapUser

        public ILdapUser CastLdapUser(UserPrincipal userPrincipal)
        {
            var _user = new LdapUser();
            
            _user.Guid = userPrincipal.Guid.Value;
            _user.Sid = userPrincipal.Sid.ToString();
            _user.Name = userPrincipal.Name;
            _user.SamAccountName = userPrincipal.SamAccountName;
            _user.DisplayName = userPrincipal.DisplayName;
            _user.Description = userPrincipal.Description;
            _user.DistingueshedName = userPrincipal.DistinguishedName;
            _user.UserPrincipalName = userPrincipal.UserPrincipalName;
            _user.EmployeeId = userPrincipal.EmployeeId;
            _user.Email = userPrincipal.EmailAddress;

            DirectoryEntry _userDE = GetDirectoryEntry(userPrincipal);
            if (_userDE != null)
            {
                var _whenCreated = GetProperty(_userDE, "whenCreated");
                _user.Created = (DateTime)GetProperty(_userDE, "whenCreated");

                var _whenChanged = GetProperty(_userDE, "whenChanged");
                _user.Updated = (DateTime)GetProperty(_userDE, "whenChanged");
            }


            return _user;
        }
开发者ID:Eugene-Ishkov,项目名称:RestService,代码行数:28,代码来源:LdapUserFabric.cs

示例13: CreateMany

        public void CreateMany(string userNamePrefix, int usernameSuffix, int teamId, string password, int port, string userGroupName, string userNames, bool disablepwchange, bool pwneverexpires)
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(context, userGroupName);

                string[] studentNames = userNames.Replace(Environment.NewLine, "").Split(',').Select(x => x.Trim()).ToArray();
                string usernamePrefix = userNamePrefix.Replace(" ", "");
                string username = usernamePrefix + usernameSuffix;
                string description = "Bruger oprettet med UserHelper";
                string physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\";
                try
                {
                    for (int i = 0; i < studentNames.Length; i++)
                    {
                        UserPrincipal user = new UserPrincipal(context);
                        UserManagement management = new UserManagement(user, group);
                        //Create Windows User
                        management.CreateLocalWindowsAccount(username, password, username, description, disablepwchange, pwneverexpires, user);
                        management.AddUserToGroup(group, user);
                        //Create IIS Website
                        iis.CreateWebsite(username, "DefaultAppPool", "*:" + port + ":", physicalPath);

                        //Create FTP Virtual Directory
                        //txtStatusMessages.Text += iis.CreateFTPVDir("localhost", username, physicalPath, username);
                        iis.CreateVirtualDirectory("_FTP", username, physicalPath);

                        //create databases
                        sql.CreateSQLLoginUserAndDatabase(username, username, password);

                        Credentials cred = new Credentials();
                        cred.DatabaseUserName = username;
                        cred.DatabasePassword = password;
                        cred.FTPUserName = username;
                        cred.FTPPassword = password;
                        cred.WebsitePort = port;
                        cred.WindowsUserGroupName = group.Name;

                        Student student = new Student();
                        student.Name = studentNames[i];
                        student.Team = db.Teams.Find(teamId);
                        student.Credentials = cred;
                        db.Students.Add(student);

                        //Change username and port for next iteration
                        usernameSuffix++;
                        username = usernamePrefix + usernameSuffix;
                        physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\";
                        port++;

                    }

                    db.SaveChanges();

                    BatchState.State = UserProcessState.INITIAL;
                    //done
                }
                catch (Exception)
                {
                    throw;
                }
        }
开发者ID:rohansen,项目名称:userhelper,代码行数:60,代码来源:UserInteraction.cs

示例14: Main

        static void Main(string[] args)
        {
            //string connectionEmployeeDatabase = "DSN=Test;Uid=walden;Pwd=walden";
            string connectionMessagingDatabase = "Server=COS-DEV01\\SQLEXPRESS;Database=Messaging;Uid=sa;Pwd=0Griswold;";

            List<EBSEmployee> employeeDataList = new List<EBSEmployee>();
            EBSEmployee employeeData = new EBSEmployee();

            var principalContext = new PrincipalContext(ContextType.Domain, "ct-ortho.com");
            UserPrincipal userPrin = new UserPrincipal(principalContext);
            var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher();
            searcher.QueryFilter = userPrin;
            var results = searcher.FindAll();
            foreach (Principal p in results)
            {

                UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, p.SamAccountName);

                employeeData = new EBSEmployee();

                if (string.IsNullOrEmpty(userPrincipal.GivenName))
                {
                    employeeData.FirstName = string.Empty;
                }
                else
                {
                    employeeData.FirstName = userPrincipal.GivenName;
                }

                if (string.IsNullOrEmpty(userPrincipal.Surname))
                {
                    employeeData.LastName = string.Empty;
                }
                else
                {
                    employeeData.LastName = userPrincipal.Surname;
                }
                if (string.IsNullOrEmpty(p.SamAccountName))
                {
                    employeeData.UserName = string.Empty;
                }
                else
                {
                    employeeData.UserName = p.SamAccountName;
                }

                employeeData.UserID = p.Guid.ToString();

                if (CheckToSeeIfUserExists(connectionMessagingDatabase, p.Guid.ToString()))
                {
                    UpdateEmployeeRecords(connectionMessagingDatabase, employeeData);
                }
                else
                {
                    InsertEmployeeRecords(connectionMessagingDatabase, employeeData);
                }
            }
        }
开发者ID:connecticutortho,项目名称:ct-ortho-repositories,代码行数:58,代码来源:Program.cs

示例15: FindAllEnabledWithEmails

        public List<User> FindAllEnabledWithEmails()
        {
            UserPrincipal filterCriteria = new UserPrincipal(context);
            filterCriteria.Enabled = true;

            List<User> users = FindMatching(filterCriteria);
            users.RemoveAll( (User user) => user.EmailAddress == null || user.EmailAddress.Trim().Length == 0 );
            return users;
        }
开发者ID:kaiwren,项目名称:shaker,代码行数:9,代码来源:UserFilter.cs


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