c# - 批量获取AD自定义属性

标签 c# directoryservices account-management

是否可以使用 System.DirectoryServices.AccountManagement 库和 PrincipalSearcher 类来检索从调用 FindAll 返回的所有主体的自定义属性()

我目前正在使用这个示例:http://msdn.microsoft.com/en-us/library/bb552835%28v=vs.90%29.aspx .

但是,当访问我的自定义属性/属性时,它似乎要额外访问 AD 商店。我希望它在首次调用 FindAll() 时立即加载此属性。

最佳答案

是的,可以在初始时立即加载所有主体的自定义属性 调用 FindAll()。您只需按照描述指定自定义属性 在 Microsoft 示例中使用 [DirectoryProperty("YOUR_PROP_NAME")] 属性。

通过使用 GetUnderlyingSearcher() 方法访问底层 DirectorySearcher 的属性 PropertiesToLoad 在 UserPrincipal 类中,您可以看到您的自定义属性包含在以下集合中 要加载的属性。您可以在调试器中检查 PropertiesToLoad 集合。

在我的计算机上,该集合总共包含 68 个属性。

问题和性能损失就开始了。属性越多 包含在此集合中的数据越多,检索它们所需的 Active Directory 往返次数就越多。

我做了一些性能测试:

使用 Microsoft 示例检索 200 个 InetOrgPerson 对象大约需要 500 毫秒。

直接使用 DirectorySearcher 类并且仅请求感兴趣的属性 仅花费了 70 毫秒(参见下面的示例)。

using (DirectoryEntry e = new DirectoryEntry("LDAP://server10/CN=users,DC=treyresearch,DC=net", 
                                         "treyresearch\\administrator", "P@$$W0rd", AuthenticationTypes.FastBind | AuthenticationTypes.Secure))
  {
    using (DirectorySearcher ds = new DirectorySearcher(e, "(&(objectCategory=inetorgperson)(logonCount=0))"))
    {
      ds.SearchScope = SearchScope.OneLevel;
      ds.PropertiesToLoad.Clear();
      ds.PropertiesToLoad.Add("logonCount");
      ds.PropertiesToLoad.Add("sAMAccountName");


      Stopwatch sw = new Stopwatch();
      sw.Start();
      int countPerson = 0;
      using (SearchResultCollection searchResultCol = ds.FindAll())
      {
        foreach (SearchResult sr in searchResultCol)
        {
          ResultPropertyValueCollection propCol = sr.Properties["logonCount"];

          if (propCol.Count > 0)
          {
            countPerson++;
            object cou = propCol[0];
          }
        }
        sw.Stop();
        Console.Out.WriteLine(sw.ElapsedMilliseconds);
        Console.Out.WriteLine(countPerson);
      }
    }
  }

出于同样的原因,我在搜索过滤器中使用了 objectCategory objectClass 因为 objectCategory 是所谓的索引属性。 访问索引属性比访问非索引属性更快。

此外,我还指定了 AuthenticationTypes.FastBind 来改进 性能。

要进一步提高性能,请参阅 MSDN 上的这篇文章描述如何创建高效的搜索查询。

总而言之,使用 DirectorySearcher 类并仅指定您要的属性 对创造性地提高搜索性能(减少与 Active Directory 的往返次数)感兴趣。

希望这会有所帮助。

关于c# - 批量获取AD自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151770/

相关文章:

user-accounts - 用户名常用限制关键字的任何来源?

c# - .NET 的替代方案提供了关于 uris 和 url 的 api

c# - 在 SQL Server 中反汇编位标志枚举

c# - 使用 .NET 中的代码更改桌面墙纸

c# - 事件目录 : find details of users in group without mass search

.net - 使用 System.DirectoryServices 验证域用户

c# - Fluent NHibernate 实体 HasMany 不同子类类型的集合

c# - 使用 DirectorySearcher.FindAll() 时发生内存泄漏

.net - UserPrincipal.FindByIdentity坚持 "There is no such object on the server."

amazon-web-services - AWS cli 在账户之间切换