Get all users from SharePoint group including active directory group V2


Hello everyone,

Some time ago, I wrote about how to retrieve the list of all users of a SharePoint group, including the list of Active Directory users if an AD group was present.

The proposed solution does not appeal to me because the LDAP binding was HardCoded.

I told you about the SPPrincipalInfo class and I had used the method “SPUtility.GetPrincipalsInGroup“.

But I had underestimated this function!

I didn’t thought to pass the Active Directory group name! Indeed, this function works on SharePoint groups but also on AD groups!

So just check if the group is an active directory group with one of the following functions


If(SPUser.IsDomainGroup)


if(SPPrincipalInfo.PrincipalType == SPPrincipalType.SecurityGroup)

If this is the case just make a GetPrincipalsInGroup passing the loginname of the active directory group for a list of users!

No need the LDAP query!

Here is the full code!



DataTable dtuser = new DataTable();

dtuser.Columns.Add("Group User");

SPGroup groupToDisplay = SPContext.Current.Web.SiteGroups.GetByID(DisplayingGroup);

foreach (SPUser user in groupToDisplay.Users)

{

if (user.IsDomainGroup)

dtuser = GetUsers(user.LoginName, dtuser);

else

dtuser.Rows.Add(user.LoginName);

}




DataTable GetUsers(string userLoginName, DataTable dtuser)

{

bool reachedMaxCount;

SPPrincipalInfo[] adUsers = SPUtility.GetPrincipalsInGroup(SPContext.Current.Web, userLoginName, int.MaxValue - 1, out reachedMaxCount) ;

if (adUsers != null && adUsers.Length > 0)

{

foreach (SPPrincipalInfo principal in adUsers)

{

if (principal.PrincipalType == SPPrincipalType.SecurityGroup)

dtuser = GetUsers(principal.LoginName, dtuser);

else

dtuser.Rows.Add(principal.LoginName);

}

}

return dtuser;

}

Hope this helps!

Christopher.

Get a list of all SharePoint group’s users including active directory group

Hello everyone,

Today I’ll talk about a request I had some time ago. The client wanted a list of all members of a SharePoint group.

At first sight no worries, just use a

 
SPGroup group;            
group.Users ;

Except that later in development, the use of active directory groups has been determined to facilitate user management.
And here, it does not interest the customer to see the name of its active directory groups! (Strange isn’t it?)

So now, after some research and several tests I found the SPPrincipalInfo class and the PrincipalType attribute : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.utilities.principaltype.aspx

This class, found via the Microsoft.SharePoint.Utilities assembly, tests whether the user is a security group, in other words, if it is an Active Directory group.

So here I am with the first part of my code


SPSecurity.RunWithElevatedPrivileges(delegate
            {

                using (SPSite adminSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb adminWeb = adminSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        string myGroup = "GroupName";
                        List listeUsers = new List();
                        bool reachedMax;
                        SPPrincipalInfo[] principals = SPUtility.GetPrincipalsInGroup(adminWeb, myGroup, 500, out reachedMax);
                        foreach (SPPrincipalInfo item in principals)
                        {
                            if (item.PrincipalType == SPPrincipalType.SecurityGroup)
                            {
                                string[] temp = item.DisplayName.Split('\\');
                                listeUsers.AddRange(GetGroupMembers(temp[temp.Length - 1]));
                            }
                            else
                                //listeUsers.Add(item.LoginName.ToLower());//display the login name
                                listeUsers.Add(item.DisplayName.ToLower());//display the display name
                        }
                    }
                }
            });				
		

The distinction between users and SharePoint active directory group is made, it now remains only to query the active directory to retrieve all users in that group.



public List GetGroupMembers(string strGroup)
        {
            List groupMemebers = new List();

            try
            {
                DirectoryEntry ent = new DirectoryEntry("LDAP://DC=Test,DC=COM");// Change by your AD link

                DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");

                SearchResultCollection coll = srch.FindAll();

                foreach (SearchResult rs in coll)
                {
                    ResultPropertyCollection resultPropColl = rs.Properties;

                    foreach (Object memberColl in resultPropColl["member"])
                    {
                        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);

                        System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

                       
                        //getting user properties from AD

                        object obVal = userProps["displayName"].Value;
                        object obAcc = userProps["sAMAccountName"].Value;


                        if (null != obVal)
                        {
                            groupMemebers.Add(obVal.ToString().ToLower());//display the display name
                            //groupMemebers.Add(obAcc.ToString());//Display the login
                        }
                        else groupMemebers.AddRange(GetGroupMembers(userProps["sAMAccountName"].Value.ToString()));

                    }
                }
            }

            catch (Exception ex)
            {
            }

            return groupMemebers;

        }

And voila, we have a list of all members of our group SharePoint!

Edit : There is another way of doing this here

Christopher.