Sunday, December 7, 2008

Preserving/Updating CreatedBy and ModifiedBy

You might have a scenario where by you want to migrate the list data from one site another site list manually instead of .STP file
Or you use Run With Elevated Privileges ( with delegate()) to insert a record into library where by normal user don't have contribute rights but only READ access Or you need to update one or more fields in a library and you want to preserve Created By and Modified By data.

Here is the Pseudocode:
If Current User is Super user OR Preserver user details is false
Normal Insert
Else
Run the Code With Elevated Privileges to Insert
Then Restore User Details
End If

Code for Restore User Details (C#):

private void RestoreUserDetails(string sitename, string libname, int itemId, int sharePointUserID, string UserLoginName)
{
using (SPSite siteColl = new SPSite(sitename))
{
using (SPWeb web = siteColl.OpenWeb())
{
SPList Legal = web.Lists[libname];
SPListItem LegalItem = Legal.GetItemById(itemId);

//SPFieldUserValue oUser = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);
SPFieldUserValue oUser = new SPFieldUserValue(web, sharePointUserID, UserLoginName);

LegalItem["Author"] = oUser.User.ID;
LegalItem["Editor"] = oUser.User.ID;
LegalItem.Update();

}
}
}

No comments: