Extending the GroupPrincipal and Members Property
I want to extend the class GroupPrincipal
to handle some custom properties:
using System.DirectoryServices.AccountManagement;
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("group")]
public class MyGroupPrincipal : GroupPrincipal {
// ...
}
How can I override the property Members
for MyGroupPrincipal
so that if it has a member that is a group, an instance is returned MyGroupPrincipal
instead GroupPrincipal
? I would like to write for example.
MyGroupPrincipal group = GetGroup();
foreach (var m in group.Members) {
if (m is MyGroupPrincipal) { // always fails: m is a normal GroupPrincipal
// do something
}
}
a source to share
You cannot directly override the MembersGroupPrincipal property. You can use your own method instead (sorry for the lack of cleanup code, but I used parts of the below described solution through my code).
I found that many times with the AccountManagement library you just need to use the base DirectoryEntry to get things done right. You can access the underlying object with group.GetUnderlyingObject()
and then read the membership, iterate deGroup.Properties("member")
. Read each member type (remember the property name, maybe "member.SchemaClassName"?) And differName ( member.Properties("distinguishedName")(0).ToString()
). Then create a switch statement based on the type in which you create each principal using the distinguished name MyGroupPrincipal.FindByIdentity(context, distinguishedName)
and do the same for users, etc.
a source to share