Error Querying Active Directory in C#

Just wanted to pass along this issue/solution I found when querying Active Directory for users in a group. 

We have a utility which queries Active Directory for users in groups and outputs a file with related information.  Here is the code we used to query AD:

var domain="mydomain";
var controller="DC=mydomain";
var groupName="Share_AcmeDivision-ReadWrite"

var context = new PrincipalContext(ContextType.Domain, domain, controller);
var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName);

foreach(var member in group.GetMembers(false)) {
	member.Name.Dump();
}

This worked without issue for many months until we added a new group to query and then it started bombing with the following error:

PrincipalOperationException - The specified directory service attribute or value does not exist. 

InnerException - COMException - The specified directory service attribute or value does not exist. 

RuntimeMethodInfo - ADStoreCtx.ResolveCrossStoreRefToPrincipal (Object o) 
 

The old groups and other new groups worked fine but one particular group always threw this error.  Even more interesting was the error was thrown midway through iterating the list of members.  Meaning you could receive the first 10 users without issue but then the error would be thrown. 

After a couple days of troubleshooting I couldn’t find a solution to this error using this API.  So instead I decided to try the DirectoryEntry API and LDAP:

void Main()
{
	GetMembers("CN=Share_AcmeDivision-ReadWrite,OU=Share Groups,OU=Utah,DC=mydomain");
}
void GetMembers(string ldap) {
	var entry = new DirectoryEntry("LDAP://" + ldap);
	if (entry.Properties.Contains("member"))
	{
		var members = entry.Properties["member"];
		foreach(var member in members) 
		{
			GetMembers(member.ToString());
		}
	}
	else
	{
		GetUser(ldap);
	}
}
void GetUser(string ldap) {
	var entry = new DirectoryEntry("LDAP://" + ldap);
	entry.Properties["name"].Value.Dump();
	entry.Properties["mail"].Value.Dump();
}

For whatever reason this code was able to traverse the group(s) and user(s). I suspect the group or users were corrupted in AD somehow and the GroupPrincipal API wasn’t handling it well.

Hope this helps others.  If so please remember to leave a comment below.  Thanks!

Leave a Reply