简体   繁体   中英

Get Principal Context object using LDAP path

I am working on a module where I need to fetch members of an Active Directory group. This functionality already exists in the project but it was built for .Net3.5. The same is not working for .Net4.5. After some googling I found that I need to use "Principal Context" object to get the Directory entry object.

The problem here is, I need to do the testing in Test AD, which is different from my production AD. The old way I used was allowing me to specify the test AD server path,

DirectoryEntry entry = new DirectoryEntry(ADLdapPath, ADAdminUser, ADAdminPassword, AuthenticationTypes.Secure);

Can anyone please help me find a way to specify LDAP path(AD server path) while creating "Principal Context" so that I can do the testing in Test environment.

I've used the following helper (modified) which is part of my AD tool belt to create PrincipalContext for working with AD. This should get you started. Modify it to suit your needs. Hope it helps.

public class ADHelper {
    public static PrincipalContext CreatePrincipalContext(string domain = null) {
        string container = null;
        if (IsNullOrWhiteSpace(domain)) {
            domain = GetCurrentDnsSuffix();
            if (domain != null && domain.EndsWith(".com", StringComparison.InvariantCultureIgnoreCase)) {
                container = GetContainers(domain);
            } else {
                domain = null;
            }
        }

        var hostName = GetHostName();
        if (IsNullOrWhiteSpace(domain)) {
            domain = hostName;
        }

        ContextType contextType;
        if (domain.Equals(hostName, StringComparison.InvariantCultureIgnoreCase) &&
            domain.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) {
            contextType = ContextType.Machine;
        } else {
            contextType = ContextType.Domain;
        }

        PrincipalContext principalContext = null;
        if (contextType == ContextType.Machine) {
            principalContext = new PrincipalContext(contextType, domain);
        } else {
            principalContext = new PrincipalContext(contextType, domain, container, Constants.LDAPUser, Constants.LDAPPassword);
        }

        return principalContext;
    }

    public static string GetCurrentDnsSuffix() {
        string dnsHostName = null;
        if (NetworkInterface.GetIsNetworkAvailable()) {
            var nics = NetworkInterface.GetAllNetworkInterfaces()
                .Where(ni => ni.OperationalStatus == OperationalStatus.Up);

            foreach (var ni in nics) {
                var networkConfiguration = ni.GetIPProperties();

                var dnsSuffix = networkConfiguration.DnsSuffix;
                if (dnsSuffix != null) {
                    dnsHostName = dnsSuffix;
                    break;
                }

                var address = networkConfiguration.DnsAddresses.FirstOrDefault();
                if (address != null) {
                    try {
                        var dnsHost = Dns.GetHostEntry(address.ToString());
                        dnsHostName = dnsHost.HostName;
                    } catch (System.Net.Sockets.SocketException e) {
                        traceError(e);
                    } catch (Exception e) {
                        traceError(e);
                    }
                }
            }
        }
        return dnsHostName;
    }

    private static string GetContainers(string ADServer) {
        string[] LDAPDC = ADServer.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < LDAPDC.GetUpperBound(0) + 1; i++) {
            LDAPDC[i] = string.Format("DC={0}", LDAPDC[i]);
        }
        String ldapdomain = Join(",", LDAPDC);
        return ldapdomain;
    }
    public static string GetHostName() {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        return ipProperties.HostName;
    }
}

I can then use it in something like this

public static List<string> GetAllUserNames(string domain = null) {
    List<string> userNames = new List<string>();
    using (var principalContext = createPrincipalContext(domain)) {
        //Get a list of user names in MyDomain that match filter
        using (UserPrincipal userPrincipal = new UserPrincipal(principalContext)) {
            using (PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal)) {

                var results = principalSearcher
                    .FindAll()
                    .Where(c =>
                        (c is UserPrincipal) &&
                        (c as UserPrincipal).Enabled.GetValueOrDefault(false) &&
                        !string.IsNullOrEmpty(c.DisplayName)
                        );
                foreach (UserPrincipal p in results) {
                    var temp = p.StructuralObjectClass;
                    string value = string.Format("{0} ({1})", p.DisplayName, p.EmailAddress ?? Join("\\", p.Context.Name, p.SamAccountName));
                    userNames.Add(value);
                }
            }
        }
    }
    return userNames;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM