Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Runwithelevatedprivileges in Sharepoint 2010

Runwithelevatedprivileges in Sharepoint 2010

In this post you will learn how to use Runwithelevatedprivileges with LINQ in SharePoint 2010. In the code below you will see how a user who does not have permissions( not even read permissions) to a list can add an item in the list and with his user name as an author (created by) of the item. To assign a current user as an Author of the item we have first retrieved the real credentials, and then elevated the privileges.

private void CreateItem(SPList hiddenList)
{
SPUser user = ((LayoutsPageBase)Page).Web.CurrentUser;
Guid siteID = hiddenList.ParentWeb.Site.ID;
Guid webID = hiddenList.ParentWeb.ID;
Guid listID = hiddenList.ID;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList elevatedList = web.Lists[listID];
SPListItem item = elevatedList.Items.Add();
SPFieldUserValue currentUser = new SPFieldUserValue(item.ParentList.ParentWeb, user.ID, user.Name);
item["Author"] = currentUser;
item["Editor"] = currentUser;
item.Update();
}}}
);
}}

No comments:

Post a Comment