Reputation: 1740
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");
Upvotes: 0
Views: 1932
Reputation: 7545
In my case, I found the issue was that it wasn't connecting to the AD server. If I hovered over oPrincipalContext
, its property of ConnectedServer
showed that it threw an exception of type System.DirectoryServices.DirectoryServicesCOMException
. If this happens, a restart of services on the Domain Controller should work. We found it can happen during high-login times, since we only have 1 DC on our dev network.
Upvotes: 0
Reputation: 1680
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.
Upvotes: 1