Add/Update "sealed" properties in SharePoint lists
There’s always a question about updating properties in a list in SharePoint. Specifically, properties like “Modified By”, “Modified” etc., WSS 3.0 provides greater flexibility for enabling developers to do this with ease. Usually, this scenario would be required when users with “Read” rights need to be able to perform certain updates to a list and we’d like to know “who” they are. Also, this requirement is mostly when the custom code run in a web platform (web part, ASP.NET web application etc.,)
Naturally, in a web scenario, we’d use SPSecurity.RunWithElevatedPrivileges. However, this will not work when our SPSite and SPWeb are instantiated from the context object. More information on it can be found in Running Commands with Elevated Privileges in Windows SharePoint Services 3.0.
Below is the code snippet that does the property updates for us.
SPSite site = SPControl.GetContextSite(Context);
SPWeb web = site.OpenWeb();
SPUser user = web.CurrentUser;
lbl.Text = "";
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite csite = new SPSite(site.ID);
SPWeb cweb = csite.OpenWeb(web.ID);
csite.AllowUnsafeUpdates = true;
cweb.AllowUnsafeUpdates = true;
SPListItemCollection listItems = cweb.Lists["Ann"].Items;
SPListItem listItem = listItems.Add();
listItem["Title"] = "read-only user added this";
listItem["Author"] = user;
listItem["Editor"] = user;
listItem["Created"] = DateTime.Now.AddDays(2);
listItem["Modified"] = DateTime.Now.AddDays(3);
listItem.Update();
lbl.Text = "Updated successfully!";
});
}
catch (Exception _e)
{
lbl.Text = "";
lbl.Text = "Error: " + _e.Message + "\n\nStack Trace: " + _e.StackTrace;
}
The same syntax as above should work in every other scenario where property update by a less privileges user is required AND persisting user information & meshing up date time stamp is a necessity.
Hope this is helpful!
Comments
- Anonymous
January 08, 2009
This is really a useful information. Earlier, I was using a separate column with versioning enabled to track the user who modified the record. Thanks for the useful post.