0

I am making a TimerJob that duplicates ListItems from one SiteCollection to another. In order to do this I need to copy the Users and Groups over to the other site. I am having trouble identifying whether the SPFieldType is a user or group so that I can apply the correct logic.

Since a Person Picker field can either be a SPUser or a SPGroup I'm having difficulty. I have a hook in the logic to see if it is of SPFieldType.User like this:

if (sourceField.Type == SPFieldType.User)
{
    //need to see if it is a SPUser or SPGroup in here
    //if (SPUser) then use EnsureUser to create the user if it does not exist
    //if (SPGroup) then use some other logic to create the group if it does not exist
}

2 Answers 2

1

You can get the field value as SPFieldUserValue and check if the User property is null.

SPFieldUserValue userFieldValue = new SPFieldUserValue(yourSPListItem.Web, yourSPListItem[sourceField.Id].ToString());
if (userFieldValue.User == null) // userFieldValue is SPGroup
{
    // do group processing
}
else // userFieldValue is SPUser
{
    // do user processing
}

If your field can contain multiple values, and there could be a mix of users and groups, you can use the same idea with SPFieldUserValueCollection.

SPFieldUserValueCollection userFieldValueColl = new SPFieldUserValueCollection(yourSPListItem.Web, yourSPListItem[sourceField.Id].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueColl)
{
    if (userFieldValue.User == null) // userFieldValue is SPGroup
    {
        // do group processing
    }
    else // userFieldValue is SPUser
    {
        // do user processing
    }
}
2

You can get the field value as SPPrincipal and then check is it a user or group.

if (principal.GetType() == typeof(SPUser))
{
    SPUser user = principal as SPUser;
    //your code for SPUser
}
else if (principal.GetType() == typeof(SPGroup))
{
    SPGroup group = web.SiteGroups.GetByID(principal.ID)
    //your code for SPGroup
}
2
  • I tried assigning the listItem[field] as SPPrincipal like so: SPPrincipal principal = version[sourceField.Title] as SPPrincipal; but it returns null. the variable version is a SPListItemVersion btw. Any advice on this?
    – LukeP
    Nov 21, 2013 at 21:29
  • 2
    You can't get SPPrincipal directly by just casting the object returned from item[field]. Maybe its quicker and with fewer steps to user SPFieldUserValue as Dylan proposed. If userFieldValue.User == null then it's a group and get it with SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId). Otherwise it's a user and just get it with userFieldValue.User. Nov 22, 2013 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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