网络利用率 - AccountManagement与DirectoryServices

时间:2011-03-21 10:53:22

标签: c# .net .net-3.5 ldap directoryservices

我花了一天多的时间才发现Principal对象使用的带宽比使用DirectoryServices的带宽要多。场景是这样的。我有一个包含约3000个计算机对象的组。要检查计算机是否在此组中,我检索了GroupPrincipal并搜索了ComputerPrincipal。

        Boolean _retVal = false;
        PrincipalContext _principalContext = null;
        using (_principalContext = new PrincipalContext(ContextType.Domain, domainController, srv_user, srv_password)) {
            ComputerPrincipal _computer = ComputerPrincipal.FindByIdentity(_principalContext, accountName);

            GroupPrincipal _grp = GroupPrincipal.FindByIdentity(_principalContext, groupName);
            if (_computer != null && _grp != null) {
                // get the members
                PrincipalSearchResult<Principal> _allGrps = _grp.GetMembers(false);
                if (_allGrps.Contains(_computer)) {
                    _retVal = true;
                }
                else {
                    _retVal = false;
                }
            }
        }
        return _retVal;

实际上非常好的界面,但这会为每个请求创建大约12MB的流量。如果您是域控制器在局域网中,这不是问题。如果使用WAN访问域控制器,则会终止您的连接/应用程序。

在我注意到这一点后,我使用DirectoryServices重新实现了相同的功能

Boolean _retVal = false;
DirectoryContext _ctx = null;
try {
    _ctx = new DirectoryContext(DirectoryContextType.DirectoryServer, domainController, srv_user, srv_password);
} catch (Exception ex) {
    // do something useful
}
if (_ctx != null) {
    try {
        using (DomainController _dc = DomainController.GetDomainController(_ctx)) {
            using (DirectorySearcher _search = _dc.GetDirectorySearcher()) {
                String _groupToSearchFor = String.Format("CN={0},", groupName);
                _search.PropertiesToLoad.Clear();
                _search.PropertiesToLoad.Add("memberOf");
                _search.Filter = String.Format("(&(objectCategory=computer)(name={0}))", accountName); ;
                SearchResult _one = null;
                _one = _search.FindOne();
                if (_one != null) {
                    int _count = _one.Properties["memberOf"].Count;
                    for (int i = 0; i < _count; i++) {
                        string _m = (_one.Properties["memberOf"][i] as string);
                        if (_m.Contains(groupName)) { _retVal = true; }
                    }
                }
            }
        }
    } catch (Exception ex) {
        // do something useful
    }
}
return _retVal;

此实施将使用大约12K的网络流量。这可能不是很好,但节省了很多带宽。

现在我的问题是,如果有人知道AccountManagement对象正在做什么,它使用了如此多的带宽?

谢谢!

1 个答案:

答案 0 :(得分:2)

我猜想包括以下几行会为节省带宽做很多事情:

_search.PropertiesToLoad.Clear();
_search.PropertiesToLoad.Add("memberOf");
_search.Filter = String.Format("(&(objectCategory=computer)(name={0}))", accountName);

前两个告诉DirectorySearcher只加载一个属性而不是谁知道任意大小的属性。

第二种是将过滤器传递给DirectorySearcher,我猜这可能是服务器端处理的,进一步限制了结果集的大小。

相关问题