c# - C# - 目录服务 - 大约每月一次随机接收错误
问题描述
我有一个 Windows 服务,它查询 Active Directory 用户信息并将其写入数据库。随机(我会说每月一次),它会出错并且不会成功重新启动。我想知道是否有人会知道为什么会随机出现此错误?
ERROR - 发生本地错误。
在 System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
在 System.DirectoryServices.AccountManagement.ADEntriesSet.MoveNext()
在 System.DirectoryServices.AccountManagement.FindResultEnumerator1.MoveNext() at System.DirectoryServices.AccountManagement.FindResultEnumerator
1.System.Collections.IEnumerator.MoveNext()
它似乎指向最后一行错误(在遍历集合时):
int num1 = 0;
int num2 = 0;
DateTime now1 = DateTime.Now;
PrincipalContext AD = new PrincipalContext(ContextType.Domain, "ourdomain.org");
UserPrincipal userPrincipal = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(userPrincipal);
var all = search.FindAll();
int userCount = 0;
foreach (UserPrincipal result in all)
{
// some code
}
解决方案
我建议重写您的代码以使用DirectorySearcher
. 它可能会解决您的问题,但即使没有,您也应该能够获得有关可能出现问题的更多信息。你的循环会运行得更快。PrincipalSearcher
无论如何只是一个包装器DirectorySearcher
,但是您会失去很多控制和性能。
这是一个可能看起来像的示例:
var search = new DirectorySearcher(new DirectoryEntry()) {
PageSize = 1000, //this is required if you expect more than 1000 results
Filter = "(&(objectClass=user)(objectCategory=person))" //all users
};
//tell it which properties you want to return, otherwise it will return everything
search.PropertiesToLoad.Add("mail");
using (var results = search.FindAll()) {
foreach (SearchResult result in results) {
try {
// some code
// Get attributes from search results like:
// (string) result.Properties["mail"][0]
} catch (Exception e) {
// log exception
// use result.Path to show you which user it choked on
}
}
}
确保更新search.PropertiesToLoad
以包含您希望从搜索结果中看到的属性。
还要注意,您可以捕获任何异常并将其记录Path
到导致异常的用户。然后您可以检查该用户并查看它有什么不同。
我写了一篇关于在针对 AD 进行编程时获得更好性能的文章,它可以帮助您:Active Directory:更好的性能
推荐阅读
- angular - 如何在 Angular 2 中检索数据?
- django - Django 上传/下载文件
- javascript - 如何在 Odoo 中聚焦 TransientModel 表单中的字段?
- spring-boot - 如何构建 Spring Boot 无 Web 应用程序并将其部署到 TomEE?
- model-view-controller - 无法下载 PDF 文件,从 Sql 数据库中获取。已获取字节值,函数未出现任何错误,但未下载 PDF
- java - 如何在android中将任何类型的日期转换为特定格式?
- excel - 将VB的特定行复制到其他行
- python - 从 python 脚本更改目录以调用 shell
- javascript - 无法将 jwt 令牌添加到 node.js 响应
- uwp - 无法从密码库中检索存储的密码