Using the new namespaces for AD stuff is really nice, but MSFT really dropped the ball when building PrincipalContext objects. PrincipalContext objects are used to encapsulate the server or domain which are going to be subject to the AD operations, so is hydrated when building UserPrincipal or GroupPrincipal objects. So, for example ,they are generally put into static methods such as:
public static PrincipalContext GetGroupPrincipalContext()
PrincipalContext principalContext = null;
SPSecurity.RunWithElevatedPrivileges(() => principalContext = new PrincipalContext(ContextType.Domain, “
so that we can use it later for user and group operations:
public static UserPrincipal GetUser(string userName)
UserPrincipal userPrincipal = null;
PrincipalContext principalContext = GetUserPrincipalContext();
userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);
public static GroupPrincipal GetGroup(string groupName)
GroupPrincipal groupPrincipal = null;
PrincipalContext principalContext = GetGroupPrincipalContext();
groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName);
However, it is important that if you experience performance issues to consider two things. I have noticed that with declarative domain controller specific rather than relying on the round-robin default fashion is pretty effective. Otherwise, you are going to be limited to using Attribute Scope Query (ASQ). This involves using the DirectoryEntry and DirectorySearcher objects.
An update to this post is available here.