次の方法で共有


Find the Latest Employee ID

The application creates a new user principal object for the query, since persisted principal objects cannot be used in queries. The PrincipalSearcher object is created to search for the latest employee ID. The underlying searcher object, DirectorySearcher, is retrieved to perform more complex search operations. Using the DirectorySearcher object, the application is able to sort the directory entries on employees ID before retrieving the latest employee ID with the FindAll method.

        internal static int FindTheLatestEmployeeID()
        {
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }

            //Retrieve the user with latest employee number.
            UserPrincipal userQuery = new UserPrincipal(principalContext);
            userQuery.EmployeeId = "*";
            PrincipalSearcher principalSearcher = new PrincipalSearcher(userQuery);
            if (principalSearcher.GetUnderlyingSearcherType() == typeof(DirectorySearcher))
            {
                DirectorySearcher directorySearcher = (DirectorySearcher)principalSearcher.GetUnderlyingSearcher();
                directorySearcher.Sort.Direction = SortDirection.Descending;
                directorySearcher.Sort.PropertyName = "employeeID";
            }
            
            UserPrincipal userPrincipal = null;
            
            foreach (UserPrincipal usr in principalSearcher.FindAll())
            {
                userPrincipal = usr;
                break;
            }
            
            int employeeID = 0;
            if (userPrincipal != null)
                Int32.TryParse(userPrincipal.EmployeeId, out employeeID);

            return employeeID;
        }

See Also

Reference

System.DirectoryServices.AccountManagement

Concepts

About System.DirectoryServices.AccountManagement
Using System.DirectoryServices.AccountManagement

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.