2014-07-21 38 views
0

是否有可能爲「按示例查詢」主體設置條件爲而不是而不是如同c#PrincipalSearcher條件不相似

類似方法:

UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.Name= "Mario"; 

這將返回所有用戶名爲 「馬里奧」。

是否可以創建一個條件來獲取所有未命名爲「Mario」的用戶?

事情是這樣的:

UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.Name != "Mario"; 

所有用戶提供了一個其他的名字不是 「馬里奧」。

回答

1

不,但是您可以獲得所有用戶。然後使用linq來過濾它們。

UserPrincipal qbeUser = new UserPrincipal(ctx); 
PrincipalSearcher pSearch = new PrincipalSearcher(qbeUser); 
PrincipalSearchResult<Principal> pResult = pSearch.FindAll(); 
var notMario = (from u in pResult 
       where u.Name != "Mario" 
       select u); 

然後根據你想要做

foreach (Principal p in notMario) { 
    // Do Somthing 
} 
+0

是的,它是可能的,我找到了解決的類! –

1

這可以通過擴展UserPrincipal類中取得的成就:

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

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

    // Create the "employeeType" property with the "!" for NOT LIKE.  
    [DirectoryProperty("!employeeType")] 
    public string NotLikeEmployeeType 
    { 
     get 
     { 
      if (ExtensionGet("!employeeType").Length != 1) 
       return string.Empty; 

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

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

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

重要的是要了解是在這裏:

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

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

鑑於t他使用ExtensionGet和ExtensionSet創建了「DirectoryProperty」屬性(此例中的NotLikeEmployeeType)不爲空時,可以添加「!」在AD屬性(在這種情況下爲employeeType)之前。

這是我們如何能夠使用擴展:

UserPrincipalEXT qbeUser = new UserPrincipalEXT(ctx); 
qbeUser.NotLikeEmployeeType = "exclude"; 

現在的條件返回值將是:

!employeeType = exclude 

而這正是我們想要的!不喜歡 ! :)

而且,關於延長偉大的事情,是你可以添加廣告屬性,他們通常不會暴露(如employeeType)