I am trying to search AD for a user, but it keeps throwing an exception. The application is setup to use AppPool. and I am certain that the logged in user has access to search AD.
Code:
public static UserADInfoModel ResolveUserProperties(string sam)
{
UserADInfoModel uad = new UserADInfoModel();
PrincipalContext DC = new PrincipalContext(ContextType.Domain,
"lm.lmig.com", "DC=lm,DC=lmig,DC=com,OU=LM Users");
UserPrincipal userSearch = new UserPrincipal(DC);
userSearch.SamAccountName = "(&(objectClass=user)(sam)";
PrincipalSearcher search = new PrincipalSearcher();
search.QueryFilter = userSearch;
PrincipalSearchResult<Principal> res = search.FindAll();
stack trace:
[DirectoryServicesCOMException (0x80072020): An operations error occurred.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +399003
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_SchemaEntry() +35
System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry de) +47
System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry ctxBase, Boolean ownCtxBase, String username, String password, ContextOptions options) +116
System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry) +143
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit() +244
Source Error:
Line 45: PrincipalContext DC = new PrincipalContext(ContextType.Domain, "lm.lmig.com", "DC=lm,DC=lmig,DC=com,OU=LM Users");
Line 46: UserPrincipal userSearch = new UserPrincipal(DC);
Line 47: userSearch.SamAccountName = "(&(objectClass=user)(sam)";
Line 48: PrincipalSearcher search = new PrincipalSearcher();
Line 49: search.QueryFilter = userSearch;
To me, the assignment of wrong values in
PrincipalContext
constructor and the value assigned toSamAccountName
looks suspicious, and seems the possible cause of exception.The DN should contain the path in reverse order, i.e., starting should be with an OU or CN when both OU and DC components are there. Also, SamAccountName value must be a string value which is valid.
Please try the following way: