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

Friday, 19 November 2010

SharePoint - How to get an SPUser Object based on a Person Field in a SharePoint List

I had a question today about how to determine the email address of the user who is mentioned in the "Responsible Field" of a SharePoint list. He was trying to develop an event receiver that would email a particular user if they were mentioned in that field. To this end, here is a tiny method I wrote to get an SPUser based on a Person field in a SharePoint list. The code has to first obtain a reference to the relevant SPField and then use the "GetFieldValue" method of the SPField to get the SPFieldUserValue. The SPFieldUserValue is really just an SPUser:

        /// 
        /// Gets the SP User object from a person field (e.g. the Modified By field) 
        /// so we can determine the email address or other details of that user.
        /// 
        /// e.g. the SPItem with the Person field obtained 
        /// from web.Lists[0].Items[0]         /// e.g. a person field e.g. "Modified By"
        public static SPUser GetSPUserFromPersonField(SPListItem listItem, string fieldName)
        {
            var personField = listItem.Fields[fieldName];
            return ((SPFieldUserValue)personField.GetFieldValue(listItem[fieldName].ToString())).User;
        }

DDK

Wednesday, 3 December 2008

How can I set the Modified By, Created By, Date Modified, Date Updated fields via the MOSS object model? (without making an new version)

There are a few problems with the MOSS object model when adding new files using the SPFileCollection.Add() method. In particular, there is no overload that accepts both the "bool overwrite" parameter AND the details of the user who did the update at the same time.



Consequently, the upload of a file to a versioned list in SharePoint requires that you separately add the file with overwrite on and then update the User and Time stamps at a later stage.

Unfortuntately, the "Author" and "Editor" fields accessible via the SPFile Object are read-only. You can however take advantage of the UpdateOverwriteVersion(); available on list items to update these stamps manually. See the code below:



//The authenticating user needs to be service account as it uses database access,
// so we must pass in current user as parameter when adding file.
SPUser updatingUser = EnsureUser(HttpContext.Current.User.Identity.Name, web);
currentFile = fileCollection.Add(newDocument.Name, contents, fileProperties, addAsNewVersionToExistingFiles);

//Get list item from SPFile object
SPListItem listItem = currentFile.Item;

//Overwrite with correct values as the object model doesn't allow us
// to both specify overwrite=true and the specific user names.
listItem["Author"] = updatingUser;
listItem["Editor"] = updatingUser;
listItem.UpdateOverwriteVersion();