2014-11-20 79 views
1

Principal類只有幾個廣告屬性表示:如何使用廣告屬性不是在主體類

enter image description here

的問題是我需要閱讀的屬性,是不是在Principal類。 ..

這是我如何查詢AD對象:

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain,ConfigurationManager.AppSettings["ADDomain"].ToString(), ConfigurationManager.AppSettings["ADUser"].ToString(), ConfigurationManager.AppSettings["ADPassword"].ToString()); 

// define a "query-by-example" principal - here, we search for all users 
UserPrincipalEXT qbeUser = new UserPrincipalEXT(ctx); 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach (var found in srch.FindAll()) //FOUND represent the AD object 
{ 
    ... 
} 

有沒有辦法延長Principal類獲取更多AD屬性?

回答

2

您可以使用GetUnderlyingObject()來訪問附加屬性:

if (found.GetUnderlyingObjectType() == typeof(DirectoryEntry)) 
{ 
    DirectoryEntry de = (DirectoryEntry)principal.GetUnderlyingObject(); 
    // Use de.Properties to access additional information 
} 
3

如果你在.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); } 
    } 
} 

現在,你可以使用的「擴展」版本在您的代碼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

真的很好的答案。謝謝!! – Shiva 2014-11-20 21:08:06

相關問題