I need to provide a search on Active Directory using filters such as Display name, Telephone and Department. Display name and Telephone are easy but I'm stuck on department. This is the bit that works:
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);
}
}
}
I was hoping that I could just add something like:
DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;
if (ddlDepartment.SelectedValue != "")
userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue;
But that doesn't work. Anyone know how I can do this?
Edit: I'm an idiot, changed the search term and found the answer. The extra fields are called attibutes. Thanks Raymund Macaalay for your blog article on extending Principals.
My extended 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); }
}
}
Since you've already extended the UserPrincipal
to include the Department
attribute, you'll need to use that extended version of the user principal when you want to search.
Try this:
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With