2012-09-11 108 views
8

我需要使用過濾器(如顯示名稱,電話和部門)在Active Directory上提供搜索。顯示名稱和電話很容易,但我被困在部門。這是一個工作位:如何通過屬性(例如部門)從Active Directory獲取用戶列表

using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) 
{ 
    UserPrincipal userPrincipal = new UserPrincipal(context); 

    if (txtDisplayName.Text != "") 
     userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*"; 

    using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal)) 
    { 
     foreach (Principal result in searcher.FindAll()) 
     { 
      DirectoryEntry directoryEntry = result.GetUnderlyingObject() as DirectoryEntry; 
      DataRow drName = dtProfile.NewRow(); 
      drName["displayName"] = directoryEntry.Properties["displayName"].Value; 
      drName["department"] = directoryEntry.Properties["department"].Value; 
      dtProfile.Rows.Add(drName); 
     } 
    } 
} 

我希望我可以只添加類似:

DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry; 
if (ddlDepartment.SelectedValue != "") 
    userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue; 

但是,這並不工作。任何人都知道我可以做到這一點?

編輯: 我是一個白癡,改變了搜索詞,並找到答案。額外的字段被稱爲attibutes。 Thanks Raymund Macaalay for your blog article on extending Principals

我的擴展UserPrincipal:

[DirectoryObjectClass("user")] 
[DirectoryRdnPrefix("CN")] 

public class UserPrincipalExtended : UserPrincipal 
{  
    public UserPrincipalExtended(PrincipalContext context) : base(context) 
    { 
    } 
    [DirectoryProperty("department")] 
    public string department 
    { 
     get 
     { 
      if (ExtensionGet("department").Length != 1) 
       return null; 
      return (string)ExtensionGet("department")[0]; 
     } 
     set { this.ExtensionSet("department", value); } 
    } 
} 

回答

5

既然你已經擴展到UserPrincipal包括Department屬性,你需要使用擴展版本的用戶主要的,當你想搜索。

試試這個:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) 
{ 
    UserPrincipalExtended userPrincipal = new UserPrincipalExtended(context); 

    if (txtDisplayName.Text != "") 
    { 
     userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*"; 
    } 

    if (!string.IsNullOrEmpty(txtDepartment.Text.Trim()) 
    { 
     userPrincipal.department = txtDepartment.Text.Trim(); 
    } 

    using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal)) 
    { 
     foreach (Principal result in searcher.FindAll()) 
     { 
      UserPrincipalExtended upe = result as UserPrincipalExtended; 

      if (upe != null) 
      { 
       DataRow drName = dtProfile.NewRow(); 
       drName["displayName"] = upe.DisplayName; 
       drName["department"] = upe.department; 
       dtProfile.Rows.Add(drName); 
      } 
     } 
    } 
} 
相關問題