Ben Coffman Ben Coffman - 23 days ago 19
C# Question

UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName) returns null

Not sure why this happens but when I run this code it works on one server but not on another.

Both servers return a correct found.DisplayName however only one server returns a value for oUserPrincipal the other returns a null value.

Line of error:

UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName) returns null


dynamic config = _getExpandoFromXml("config.xml");

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.activeDirectory.sDomain, config.activeDirectory.sDefaultOU,config.mailServer.user, config.mailServer.pass);
UserPrincipal user = new UserPrincipal(ctx);

PrincipalSearcher search = new PrincipalSearcher(user);
Console.WriteLine("before foreach");
foreach (Principal found in search.FindAll())
{
try{
if (found.DisplayName == null)
{
Console.WriteLine("found.Dispalyname is null");
}
else
{
Console.Write("Dispalyname: ");
Console.WriteLine(found.DisplayName);
}
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName);
Console.Write("looking for user: ");
Console.WriteLine(found.DisplayName);
Console.WriteLine("after findbyidentiy");
if (oUserPrincipal == null)
{
Console.WriteLine("oUserPrinciapal is null");
}
if (oUserPrincipal.LastPasswordSet == null)
{
Console.WriteLine("lastpasswordset is null");
}
DateTime? dateOrNull = oUserPrincipal.LastPasswordSet;
Console.WriteLine("after LastPasswordSet");

Answer

FindByIdentity can only search on a handful of properties. These are "any format that is contained in the IdentityType enumeration".

Name is a valid option but DisplayName is not listed so you will probably get results where the DisplayName and Name happen to be the same and it will fail otherwise.

Using:

var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.Name);

or

var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.SamAccountName);

should work.

There is also a three parameter version of FindByIdentity that allows you to specify the property you would like to search on.

Comments