Today I came across a situation where I had to let user input user name(s) and add them to people picker field within a list, unfortunately it has to be done using web services as user is interacting with SharePoint throw iPad.
Problem ?
User can input anything (any string) so I need to validate if user name(s) exists or not, if user with login name provided has access to site collection page and at end if all previous are true then get SPUser object and add it to people picker field of custom list.
Solution
Assuming you already got or know how to get reference to SPSite, SPWeb, SPList and SPListItem objects
SPUser user = null;
if (!string.IsNullOrEmpty(userLogin))
{
try
{
// statement below will throw exception if user doesn't exists
if (site.RootWeb.DoesUserHavePermissions(userLogin, SPBasePermissions.Open))
{
try
{
user = site.RootWeb.SiteUsers[userLogin];
}
catch (Exception ex)
{
string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't has permissions to root web", userLogin);
throw new SoapException(other, SoapException.ServerFaultCode, ex);
}
}
}
catch (Exception ex)
{
string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't exists", userLogin);
throw new SoapException(other, SoapException.ServerFaultCode, ex);
}
SPFieldUserValueCollection uvCollection = new SPFieldUserValueCollection();
SPFieldUserValue uValue = new SPFieldUserValue(web, user.ID, user.LoginName);
uvCollection.Add(uValue);
//Now update item just by item["People PIcker Field Name"] = uvCollection;
}
That's it, above code worked for me so it should work for you.
Lesson learned
I tried to use RootWeb.Users[userLogin] but it didn't worked for me as it does not return users who have access through a group whereas I had some user's given access to root web through groups only.
RootWeb.AllUsers[userLogin] is a dangerous function as it returns list of all users who ever had access to web (even ones who don't have access to web anymore now).
web.EnsureUser() method creates a user if not exists already which I couldn't use in this scenario as client input is being used to validate SPUser object.
No comments:
Post a Comment