Principal Already Exist LDAP C#

218 Views Asked by At

I am trying to update a user on Active Directory using MVC C# LDAP, if a user is already in groups I remove him first from the group and add him again using Principal context. I tried to commit changes at the end of my remove loop but this did not help

Here is my code remove code:

PropertyValueCollection groups = result.GetDirectoryEntry().Properties["memberOf"];
                if (groups != null)
                {
                    for (int i = 0; i < groups.Count; i++)
                    {
                        string groupDn = (string)groups[i];

                        DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDn, null, null);
                        if (group != null)
                        {
                            group.Invoke("Remove", new object[] { result.Path });
                        }
                        group.CommitChanges();
                    }
                }

code to add user to groups

    //DirectoryEntry dirEntry = new DirectoryEntry(groupDirectoryEntry);
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, AD_Address))// "10.125.153.30"))
                {
                    foreach (var rights in accessGroupList)
                    {
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, rights);
                        group.Members.Add(pc, IdentityType.UserPrincipalName, model.validPersalNumber); //this is where is failes
                        group.Save();
                    }
                }
1

There are 1 best solutions below

0
Tumelo Manamela On

on remove group code after commit change, I had to close group

 PropertyValueCollection groups = result.GetDirectoryEntry().Properties["memberOf"];
                if (groups != null)
                {
                    for (int i = 0; i < groups.Count; i++)
                    {
                        string groupDn = (string)groups[i];

                        DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDn, null, null);
                        if (group != null)
                        {
                            group.Invoke("Remove", new object[] { result.Path });
                        }
                        group.CommitChanges();
                        group.Close();
                    }