I am making an ASP.NET intranet website that uses Active Directory and I am trying to get all the groups a user belongs to, even sub groups etc ... So that means I had to make a recursive method to load all the groups in an ArrayList following the example given here : https://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C
Hence I have a method to recursively fill an ArrayList based on group membership:
public ArrayList AttributeValuesMultiString(string attributeName, string objectDn,
ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ldapConnection = new DirectoryEntry(objectDn);
PropertyValueCollection valueCollection = ldapConnection.Properties[attributeName];
IEnumerator en = valueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ldapConnection.Close();
ldapConnection.Dispose();
return valuesCollection;
}
That I call from this other method:
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn, groupMemberships, recursive);
}
Using the recursive
boolean I can build my group's arraylist, but the first method can be used for other multistring object loading. Now when I test this just by a simple call to the method
//adManager is an instance of the class containing the methods above
//groups is an ArrayList
//testChain is my distinguishedName
groups = adManager.Groups(testChain, true);
foreach (var g in groups)
Console.WriteLine(g.ToString());
I have the following exception:
System.Runtime.InteropServices.COMException : Unspecified error
And the point at which I have the exception is at the assignment:
PropertyValueCollection valueCollection = ldapConnection.Properties[attributeName];
I really don't see the problem, especially that this method was recommended on another SO thread, so I'm guessing it's functional
EDIT Seems that my problem comes from an authentication issue. I added impersonation in my test code but I still get an exception :
using (HostingEnvironment.Impersonate())
{
var domainContext = new PrincipalContext(ContextType.Domain, "radiofrance.rootad.inetrf");
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.Name, "Users");
if (groupPrincipal != null)
{
groups = adManager.Groups(testChain, true);
foreach (var g in groups)
Console.WriteLine(g.ToString());
}
else
Console.WriteLine("Fail");
}