Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a field in the discussion list, which allows the initiator of the discussion to specify the people to share the discussion with.

This field is typed as 'Person or Group' that allows selection of both 'People and Groups'.

How can I retrieve a SPUser collection and a SPGroup collection from this field?

Im on SharePoint 2013.

share|improve this question

3 Answers 3

up vote 1 down vote accepted

You need to get the values into a collection object and then iterate through them and test it it is a group, if not assume it is a user, as follows:

SPFieldUserValueCollection objUserFieldValueCol = new SPFieldUserValueCollection(web, listitem["UserGroupField"].ToString());
for (int i = 0; i < objUserFieldValueCol.Count; i++)
{
    SPFieldUserValue singlevalue = objUserFieldValueCol[i];
    if (singlevalue.User == null) // value is a SharePoint group if User is null
    {
        SPGroup group = web.Groups[singlevalue.LookupValue];
        foreach (SPUser user in group.Users)
        {
            //do stuff with the user
        }
    }
    else // singlevalue.User value is a user
    {
        //do stuff for the singlevalue.User
    }
}

I am assuming that you will not have any AD security groups in there, otherwise you will need add some code to handle those.

share|improve this answer
    
SPGroup group = properties.OpenWeb().Groups[singlevalue.LookupValue]; This line is giving me the following error: Specified argument was out of the range of valid values. PS: Im working on a list item event receiver –  Muhammedh Mar 21 '13 at 12:06
    
What is the LookupValue returning? –  Richard Mar 21 '13 at 14:48
    
It returns a users and groups. –  Muhammedh Mar 24 '13 at 5:31
1  
I Solved the argument was out of range exception by replacing the follwing line to get the group object - SPGroup group = properties.ListItem.Web.SiteGroups[singlevalue.LookupId]; ` –  Muhammedh Mar 24 '13 at 9:47
1  
decided to use the follwing `SPGroup group = properties.ListItem.Web.SiteGroups[singlevalue.LookupValue];' –  Muhammedh Mar 25 '13 at 6:41

a shot in the dark here, you can try this that iv just put together?

        using (SPSite site = new SPSite("url goes here"))
        {
            using (SPWeb oWebsite = site.OpenWeb())
            {
                SPList oList = oWebsite.Lists["discussion list name"];
                SPListItem item = oList.GetItemById(12);
                SPUserCollection userCollNew = oWebsite.SiteUsers;;
                SPGroupCollection groupCol = oWebsite.SiteGroups;

                foreach (SPFieldUserValue userValue in item["ColumnName(groups and users)"] as SPFieldUserValue[])
                {
                    //need todo some check here if its a group or user.
                    userCollNew.Add(userValue.User.LoginName, userValue.User.Email, userValue.User.Name, userValue.User.Notes);

                }
                foreach (SPGroup group in item["ColumnName(groups and users)"] as SPGroup[])
                {
                    SPMember omem = oWebsite.Groups[group.Name];
                    groupCol.Add(group.Name, omem, null, group.Description);
                }

            }
        }

lol dont take my world on it, just did it in VS without testing! you can refer to these articles for extra help!

How to get users/usergroups from an lookup column from SPField

http://msdn.microsoft.com/en-gb/library/microsoft.sharepoint.spgroupcollection.add(v=office.15).aspx

http://msdn.microsoft.com/en-gb/library/microsoft.sharepoint.spmember.aspx http://snipplr.com/view/25015/

http://www.c-sharpcorner.com/uploadfile/anavijai/get-the-spfielduservaluecollection-values-using-client-object-model-in-sharepoint-2010/

share|improve this answer

If there is a possibility of an AD group in there and you would like to handle that, have a look at my solution:

public static List<string> GetUserLogins(SPListItem item)
{
    //create empty list of usernames
    List<string> Users = new List<string>();

    //retrieve user value collection from the "AssignedTo" field and iterate
    SPFieldUserValueCollection usersFields = new SPFieldUserValueCollection(item.Web.Site.RootWeb, item["AssignedTo"].ToString());

    foreach (SPFieldUserValue usersField in usersFields)
    {
        if (usersField.User == null)
        {
            //UserField contains a SharePoint group -> extract users from it
            SPGroup group = item.Web.Groups.GetByID(usersField.LookupId);
            Users.AddRange(from SPUser user in @group.Users select user.LoginName);
        }
        else
        {
            if (usersField.User.IsDomainGroup) 
            {
                //UserField is actually an AD group -> Extract users from AD
                Users = RetrieveADGroupUsers(usersField.User);
            }
            else
            {
                //UserField contains a single SharePoint user
                Users.Add(usersField.User.LoginName);
            }
        }
    }
    return Users.Distinct().ToList();
}

public static List<string> RetrieveADGroupUsers(SPUser user)
{
    List<string> loginNames = new List<string>();
    SPSecurity.RunWithElevatedPrivileges(() =>
    {
        var domainName = Environment.UserDomainName;
        var adDomain = string.Format("LDAP://{0}", domainName);
        var group = user.Name.Split('\\')[1];

        using (var entry = new DirectoryEntry(adDomain))
        {
            using (var dSearch = new DirectorySearcher(entry)
                                 {
                                     Filter = string.Format("(&(objectCategory=group)(cn={0}))", group)
                                 })
            {
                var result = dSearch.FindOne();
                foreach (string member in result.Properties["member"])
                {
                    var de = new DirectoryEntry(string.Concat("LDAP://", domainName, "/", member));
                    if (de.Properties["objectClass"].Contains("user") && de.Properties["samAccountName"].Count > 0)
                    {
                        var samAccName = de.Properties["samAccountName"][0].ToString();
                        loginNames.Add(samAccName);
                    }
                }
            }
        }
    });
    return loginNames;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.