Tag Archives: spuser objects

All Kinds of Things You Can Do With SPUser Objects

The SPUser object is a really useful tool, but sadly not very intuitive. Here are some of my favorite SPUser snippets.

People picker list columns don’t return a user object, which is frustrating, but not foreign to those of us with picker experience. An ID is generally returned by a lookup field. Not so for people pickers, which return a domain\user string that is frequently pre-pended by nonsense.

This is how you get a user directly from the list item:

protected SPUser GetUserfromItem(SPListItem userItem)

{

SPFieldUser userField = (SPFieldUser)userItem.Fields.GetField(“User”);

SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(userItem[userField.Id].ToString());

return fieldValue.User;

}

Now let’s look at a neat little method that grabs some properties by current user! As a side note, there are a lot of issues that are purportedly resolved by setting the context to null – I have never found this helpful. Never. In my lifetime.

//User Properties by user

private bool GetProperty(string userName)

{

//Your return value is a bool

bool found = false;

//Create a profile manager

UserProfileManager profMan;

//Get your site in a “using” so there’s no disposing

using (SPSite site = new SPSite(SPContext.Current.Site.ID))

{

//Make everything unsafe. Just kidding. This is so that you have permissions to edit the profile property.

//If you don’t plan on making changes, you can access the property without this.

Web.AllowUnsafeUpdates = true;

//Okay. Get your web on!

using (SPWeb newWeb = site.OpenWeb())

{

//Get the context and set the profile manager

SPServiceContext context = SPServiceContext.GetContext(site);

profMan = new UserProfileManager(context);

//Get your user profile object

UserProfile prof = profMan.GetUserProfile(userName);

//This is important. Remember to check the Property.Value. Otherwise you are checking to see

//if the property itself is null. And since you know it exists – guess what? It isn’t null. Continue reading All Kinds of Things You Can Do With SPUser Objects