Pages

Showing posts with label SPUser. Show all posts
Showing posts with label SPUser. Show all posts

Sunday, January 24, 2016

Migrate Users Across Site Collections in SharePoint Programatically

When you are working with SharePoint site collections you have experienced with managing contents in site collections from another site collection. (access root site contents from a sub site within the same web application). In this case when you need to copy user values from one site to another, then you need to ensure the user between two sites.

Using "EnsureUser"method:
SPUser currentWebUser = SPContext.Current.Web.EnsureUser(User.LoginName);

The EnsureUser method returns a valid SPUser object which can be use within site..

Ex: Add to a UserGroup:
SPGroup group = web.Groups[GroupName];
group.AddUser(currentWebUser);

Friday, January 15, 2016

Get values from Person or Group field programmatically


We are using different types of fields when working with SharePoint applications.
One of an important type among them is Person or Group field which is manage user values in site contents. This post has described that how to work with Person or Group field programmatically.

1. Get SPUser from Person or Group field in the list – (When multiple choice and groups are not allowed in the field):
//Get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());

SPUser user = userFieldValue.User;

2. Get SPUser when multiple choice is allowed and groups are not allowed:
//Multiple choices are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
{
    Console.WriteLine("     " + userFieldValue.User.LoginName);
}

3. Get SPUser when group is allowed:
//Group or User are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());

//Tries to get SPUser
if (userFieldValue.User != null)
{
   SPUser user = userFieldValue.User;
}

//if the field contain group
else
{
  SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}