I'm trying to create groupA, and add it to groupB. This fails, saying groupA cannot be found (although I can verify that it really is created). There appears to be a delay between the creation of the group and the point where it can be found by a search. Here's my code:
//1) create groupA
using (var group = ou.Children.Add("CN=" + AdConnection.EscapeLdapString(groupAName), "group"))
{
group.Properties["samAccountName"].Value = groupAName;
group.CommitChanges();
}
//2) add groupA to groupB
using (var pc = new PrincipalContext(ContextType.Domain, domain.Name, domain.Username, domain.Password))
{
using (var groupB = GroupPrincipal.FindByIdentity(pc, IdentityType.Guid, Guid))
{
groupB.Members.Add(pc, IdentityType.SamAccountName, groupAName); //throws a NoMatchingPrincipalException
groupB.Save();
}
}
If I write this as two programs, and execute part 1, wait a while, and then later execute part 2, this works. I could probably repeatedly run part 2 until group A is found, but I'd like to avoid that. Is there any deterministic way to do this? For example, can I specify that groupA is a member of groupB as I create it?
Solved this by creating groupA with new GroupPrincipal(pc, groupName)
, saving it, and then looking for groupB using the same PrincipalContext.