Eric Brown - Cal
Eric Brown - Cal

Reputation: 14409

System.DirectoryServices.Protocol add/remove user from group

I want to Add remove a user from a group in System.DirectoryServices.Protocol namespace.

I have the samples mentioned here :

link to my other question

But can't find an exampel fo how to add and remove a user from a group using S.DS.P.

Does anyone know of any samples for this operation?

Thanks,

Cal-

Upvotes: 2

Views: 2844

Answers (3)

Eric Brown - Cal
Eric Brown - Cal

Reputation: 14409

Just for those who follow, here is how I actually solved the problem using System.DirectoryServices.AccountManagement

string adServer = "";
            string adServerUser = "";
            string adServerPassword = "";
            string adServerContainer = "";

            GetSettings( ref adServer, ref adServerUser, ref adServerPassword, ref adServerContainer );

            if ( ((!string.IsNullOrEmpty(adServer) && !string.IsNullOrEmpty(adServerUser)) && !string.IsNullOrEmpty(adServerPassword)) && !string.IsNullOrEmpty(adServerContainer))
            {
                try
                {
                    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, adServer, adServerContainer, adServerUser, adServerPassword))
                    {
                        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_GroupAdd.Text))
                        {
                            if (group == null)
                            {
                                FlexibleMessageBox.Show("group could not be found");
                                return;
                            }
                            PrincipalSearchResult<Principal> x = group.GetMembers();
                            using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                            {
                                string userSid = string.Format("<SID={0}>", ToSidString(user));
                                DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                                groupDirectoryEntry.Properties["member"].Add(userSid);
                                groupDirectoryEntry.CommitChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FlexibleMessageBox.Show(ex.ToString());
                }
                FlexibleMessageBox.Show("group add done");
            }

and here is the guts of the remove from group

                    using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                    {
                        string userSid = string.Format("<SID={0}>", ToSidString(user));
                        DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                        groupDirectoryEntry.Properties["member"].Remove(userSid);
                        groupDirectoryEntry.CommitChanges();
                    }

Upvotes: 0

Marko
Marko

Reputation: 1401

Here a example to add a object to a group.

    public static void AddObjectToGroup(string objectName, string groupName)
    {
        // var credential = new NetworkCredential();
        // var identifier = new LdapDirectoryIdentifier("");
        using (var connection = new LdapConnection("company.com"))
        {
            connection.SessionOptions.StartTransportLayerSecurity(null);
            connection.Bind();

            string objectDn = null;
            var request = new SearchRequest("DC=company,DC=com", $"Name={objectName}", SearchScope.Subtree, "distinguishedName");
            var response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    objectDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information($"object DN: {objectDn}");

            string groupDn = null;
            request = new SearchRequest("DC=company,DC=com", $"Name={groupName}", SearchScope.Subtree, "distinguishedName"); 
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    groupDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information($"group DN: {groupDn}");

            request = new SearchRequest("DC=company,DC=com", $"(&(objectCategory=Group)(distinguishedName={groupDn}))", SearchScope.Subtree);
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null && !string.IsNullOrWhiteSpace(objectDn))
            {
                var members = response.Entries[0].Attributes["member"];

                var existing = new List<string>();
                for (int i = 0; i < members.Count; i++)
                {
                    existing.Add(members[i].ToString());
                }

                if (existing.Contains(objectDn)) return;
                
                var dam = new DirectoryAttributeModification { Name = "member" };
                dam.Add(objectDn);
                dam.Operation = DirectoryAttributeOperation.Add;

                var mr = new ModifyRequest(groupDn, dam);
                var dr = connection.SendRequest(mr);
                Log.Information($"Add Response: {dr.ResultCode.ToString()}");
            }
        }
    }

Upvotes: 1

Brian Desmond
Brian Desmond

Reputation: 4503

You'd just want to send a ModifyRequest on the member attribute with a DirectoryAttributeOperation.Add. The value you should pass is the DN of the user you want to add to the group

Upvotes: 3

Related Questions