I need to provide an Active Directory search using filters such as Display name, Telephone and Department. Displaying the name and phone number is easy, but I'm stuck in the ward. 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 I could just add something like:
DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry; if (ddlDepartment.SelectedValue != "") userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue;
But that does not work. Does anyone know how I can do this?
Edit: I am an idiot, changed my search query and found an answer. Additional fields are called attributes. Thanks to Raymund Macaalay for your renewal blog article .
My advanced 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); } } }
Andrew Merritt
source share