2016-03-14 4 views
0

Я работаю над модулем, где мне нужно получить элементы группы Active Directory. Эта функциональность уже существует в проекте, но была построена для .Net3.5. То же самое не работает .Net4.5. После некоторого googling я обнаружил, что мне нужно использовать объект «Основной контекст», чтобы получить объект Entry Directory.Получить основной объект контекста, используя путь LDAP

Проблема здесь, мне нужно выполнить тестирование в тесте AD, которое отличается от моего производства AD. старый способ я использовал предоставленную мне возможность указать путь к серверу испытания AD,

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

Может кто-нибудь, пожалуйста, помогите мне найти способ указать путь LDAP (путь сервера AD) при создании «Principal контекста», так что я могут выполнять тестирование в тестовой среде.

ответ

0

Я использовал следующий помощник (модифицированный), который является частью моего инструментального пояса AD, чтобы создать PrincipalContext для работы с AD. Это должно заставить вас начать. Измените его в соответствии с вашими потребностями. Надеюсь, поможет.

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; 
    } 
} 

можно затем использовать его в чем-то вроде этого

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; 
} 
+0

Спасибо за ответ Нкоси, но я не могу увидеть любое место в коде, где я могу упомянуть путь LDAP. Это, вероятно, свяжет меня с сервером AD моей локальной машины, который является производством и NOT Test. – ABC