And*_*itt 8 c# asp.net active-directory
我需要使用显示名称,电话和部门等过滤器在Active Directory上提供搜索.显示名称和电话很容易,但我被困在部门.这是有效的:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
UserPrincipal userPrincipal = new UserPrincipal(context);
if (txtDisplayName.Text != "")
userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*";
using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))
{
foreach (Principal result in searcher.FindAll())
{
DirectoryEntry directoryEntry = result.GetUnderlyingObject() as DirectoryEntry;
DataRow drName = dtProfile.NewRow();
drName["displayName"] = directoryEntry.Properties["displayName"].Value;
drName["department"] = directoryEntry.Properties["department"].Value;
dtProfile.Rows.Add(drName);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望我可以添加如下内容:
DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;
if (ddlDepartment.SelectedValue != "")
userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue;
Run Code Online (Sandbox Code Playgroud)
但这不起作用.谁知道我怎么做到这一点?
编辑:我是个白痴,改变了搜索词,找到了答案.额外的字段称为attibutes.感谢Raymund Macaalay关于扩展校长的博客文章.
我扩展的UserPrincipal:
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
public class UserPrincipalExtended : UserPrincipal
{
public UserPrincipalExtended(PrincipalContext context) : base(context)
{
}
[DirectoryProperty("department")]
public string department
{
get
{
if (ExtensionGet("department").Length != 1)
return null;
return (string)ExtensionGet("department")[0];
}
set { this.ExtensionSet("department", value); }
}
}
Run Code Online (Sandbox Code Playgroud)
由于您已经扩展了UserPrincipal包含Department属性,因此当您想要搜索时,您需要使用该扩展版本的用户主体.
试试这个:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
UserPrincipalExtended userPrincipal = new UserPrincipalExtended(context);
if (txtDisplayName.Text != "")
{
userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*";
}
if (!string.IsNullOrEmpty(txtDepartment.Text.Trim())
{
userPrincipal.department = txtDepartment.Text.Trim();
}
using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))
{
foreach (Principal result in searcher.FindAll())
{
UserPrincipalExtended upe = result as UserPrincipalExtended;
if (upe != null)
{
DataRow drName = dtProfile.NewRow();
drName["displayName"] = upe.DisplayName;
drName["department"] = upe.department;
dtProfile.Rows.Add(drName);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6205 次 |
| 最近记录: |