Thursday 5 July 2007

Sharepoint Development Tips 3- Dealing with SPUser- the slippery object

Most of the time you will want to obtain the SPUser object from your sharepoint list. One thing that will defintely make you wonder is how you cast the listitem column containing user info to the SPUser object. If you go


SPUser thisUser = (SPUser)thisItem["User_Column"];




VS will not let you compile because the underlying type of your "User_Column" is just a string, so the cast will fail. So what you can do is to search & compare the user collection in your web site, and get the SPUser from the compared result like following:


private SPUser GetOwnerFromString(string _userString, SPWeb thisWeb)
{
//parse the string after the delimiter '#'
int delimIndex = _userString.IndexOf("#");
string userStr = _userString.Substring(delimIndex + 1);
SPUser owner = null;
foreach (SPUser thisUser in thisWeb.Users)
{
//if this is current user
if (thisUser.Name.ToLower().IndexOf(userStr.ToLower()) > -1)
{
owner = thisUser;
break;
}
}
return owner;
}


As you might have noticed, the delimiter to read the string is set to "#", that's because when you try to get the string from a column containing the user information, the string format will be scrambled up like "10283744#System Account". So the format is a random number + "#" + your user's display name.


This method will work if you populate the user list of sharepoint by users rather than by AD groups. I didn't try the AD group case but will do later.

No comments: