Ben Coffman Ben Coffman - 1 year ago 284
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())
if (found.DisplayName == null)
Console.WriteLine("found.Dispalyname is null");
Console.Write("Dispalyname: ");
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName);
Console.Write("looking for user: ");
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 Source

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.


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download