I do the extension of the UserPrincipal class to retrieve some missing properties that i need:
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class UserPrincipalExt : UserPrincipal
{
public UserPrincipalExt(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);
}
}
[DirectoryProperty("company")]
public string Company
{
get
{
if (ExtensionGet("company").Length != 1)
return null;
return (string)ExtensionGet("company")[0];
}
set
{
this.ExtensionSet("company", value);
}
}
[DirectoryProperty("c")]
public string CountryAbbreviation
{
get
{
if (ExtensionGet("c").Length != 1)
return null;
return (string)ExtensionGet("c")[0];
}
set
{
this.ExtensionSet("c", value);
}
}
}
Then, i can search easily like this:
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, myDomain);
UserPrincipalExt userExt = new UserPrincipalExt(principalContext);
PrincipalSearcher searcher = new PrincipalSearcher(userExt);
userExt.GivenName = "blabla";
userExt.EmailAddress ="text here";
PrincipalSearchResult<Principal> searchTmp = null;
searcher.QueryFilter = userExt;
searchTmp = searcher.FindAll();
So, my new task, and my current problem, is this: for the searched Group in ActiveDirectory, it is necessary get the list of the users, using the extended class, of course.
GroupPrincipal group = (GroupPrincipal)collection.FirstOrDefault();
foreach (Principal pRes in group.GetMembers())
{
//This doesnt work of course.
// return null value.
UserPrincipalExt user = pRes as UserPrincipalExt;
}
How can I achieve the goal?
As workaround i have made a function to retrieve the properties anyway :
private string GetExtendedProperty(Principal principal, string propertyTo)
{
string property = "";
try
{
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
if (directoryEntry.Properties.Contains(propertyTo))
{
property = directoryEntry.Properties[propertyTo].Value.ToString();
}
else
{
property = "";
}
}
catch (Exception ex)
{
Logger.ScriviLog(4, this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message);
}
return property;
}
Thank you in advance.