2013-03-25 6 views
6

Начато использование пространства имен System.DirectoryServices.AccountManagement, чтобы выполнить поиск пользователя в активной директории (AD). Мне также нужен пользовательский менеджер, но я, кажется, ударил удар по дороге, используя это пространство имен. Текущий код, чтобы получить лицо:C# - Поиск менеджера пользователей в активном каталоге

class Person { 
    // Fields 
    public string GivenName = null; 
    public string Surname = null; 
    public string DistinguishedName = null; 
    public string Email = null; 
    public string MangerDistinguishedName = null; // Unable to set this 

    // Constructor 
    public Person(string userName) { 
     UserPrincipal user = null; 

     try { 
      user = GetUser(userName); 

      if (user != null) { 
       this.GivenName = user.GivenName; 
       this.Surname = user.Surname; 
       this.DistinguishedName = user.DistinguishedName; 
       this.Email = user.EmailAddress; 
       this.MangerDistinguishedName = user.<NO SUCH PROPERTY TO FIND A MANAGER'S DISTINGUISHED NAME> 
      } 
      else { 
       throw new MissingPersonException("Person not found"); 
      } 
     } 
     catch (MissingPersonException ex) { 
      MessageBox.Show(
       ex.Message 
       , ex.reason 
       , MessageBoxButtons.OK 
       , MessageBoxIcon.Error 
      ); 
     } 
     catch (Exception ex) { 
      MessageBox.Show(
       ex.Message 
       , "Error: Possible connection failure, or permissions failure to search for the username provided." 
       , MessageBoxButtons.OK 
       , MessageBoxIcon.Error 
      ); 
     } 
     finally { 
      user.Dispose(); 
     } 
    } 

Execute поиск для человека

private UserPrincipal GetUser(string userName) { 
     PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
     UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName); 

     return user; 
    } 

Что это еще один способ получить доступ непосредственно к различающемуся имени менеджера конкретного пользователя?

  • Возможный частичный ответ here в VB, но я не вижу ничего со ссылкой на менеджеров.
  • Другой возможный частичный here, опять же, ничего о менеджерах.

ответ

7

Если вы на .NET 3.5 и выше, и с помощью System.DirectoryServices.AccountManagement (S.DS.AM) пространства имен, вы можете легко расширить существующий UserPrincipal класс, чтобы получить на более продвинутых свойств, как Manager т.д.

Читайте об этом здесь:

В принципе, вы просто определить производный класс, основанный на UserPrincipal, а затем определить свои дополнительные свойства, которые вы хотите:

[DirectoryRdnPrefix("CN")] 
[DirectoryObjectClass("Person")] 
public class UserPrincipalEx : UserPrincipal 
{ 
    // Inplement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context) 
    { } 

    // Implement the constructor with initialization parameters.  
    public UserPrincipalEx(PrincipalContext context, 
         string samAccountName, 
         string password, 
         bool enabled) : base(context, samAccountName, password, enabled) 
    {} 

    // Create the "Department" property.  
    [DirectoryProperty("department")] 
    public string Department 
    { 
     get 
     { 
      if (ExtensionGet("department").Length != 1) 
       return string.Empty; 

      return (string)ExtensionGet("department")[0]; 
     } 
     set { ExtensionSet("department", value); } 
    } 

    // Create the "Manager" property.  
    [DirectoryProperty("manager")] 
    public string Manager 
    { 
     get 
     { 
      if (ExtensionGet("manager").Length != 1) 
       return string.Empty; 

      return (string)ExtensionGet("manager")[0]; 
     } 
     set { ExtensionSet("manager", value); } 
    } 

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue) 
    { 
     return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue); 
    } 

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) 
    { 
     return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue); 
    } 
} 

Теперь вы можете использовать «расширенную» версию UserPrincipalEx в коде:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
{ 
    // Search the directory for the new object. 
    UserPrincipalEx inetPerson = UserPrincipalEx.FindByIdentity(ctx, IdentityType.SamAccountName, "someuser"); 

    // you can easily access the Manager or Department now 
    string department = inetPerson.Department; 
    string manager = inetPerson.Manager; 
}   
+0

Вы пробовали это? Для меня это не работает. UserPrincipalEx.FindByIdentity не возвращает объект UserPrincipalEx, а приведение в UserPrincipalEx вызывает InvalidCastException. – Naikrovek

+1

@Naikrovek: извините - моя ошибка - я вырезал слишком много кода из моего (гораздо более длинного) образца. Я пропустил два перегруженных метода «FindByIdentity» и «FindByIdentityWithType» - я добавил их в свой фрагмент кода - и да, с помощью этого кода я просто проверил его против Active Directory Windows Server 2008 R2, и он отлично работает для меня. –

+0

Отлично работает, спасибо. – Naikrovek

Смежные вопросы