Introduction

This blog is mainly focused on SharePoint
I will use this to store and share all the tips and tricks about SharePoint and the related products
List of all posts

SharePoint Using elevated site nearly without RunWithElevatedPrivileges


Topic Using elevated site nearly without RunWithElevatedPrivileges
OutputElevetad Site

Scenario:
User A create a listitem L1 in SharePoint,
Based on L1, he create a second listitem L2 in another list
User B have only the rights to see and modify L2, but when L2 is modified, a property of L1 need to be updated.
Step Description
1 We will create a function to get the Admin Token
Here we will use RunWithElevatedPrivileges
        public static SPUserToken GetMainSiteAdminToken(SPWeb web)
        {
            if (web == null) throw new ArgumentNullException("web");
            SPUserToken userToken = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite elevatedSite = new SPSite(web.Site.ID))
                {
                    using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
                    {
                            userToken = elevatedWeb.SiteAdministrators[0].UserToken;
                    }
                }
            });

            return userToken;
        }
2 Now that we have the SiteAdmnToken, we can create and use an "elevetad" site
        private void UpdateOriginalItem(SPWeb web) { 
            using (SPSite elevatedSite = new SPSite(web.Site.ID, GetMainSiteAdminToken(web)))
            {
                using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
                {
                    bool bUnsafe = elevatedWeb.AllowUnsafeUpdates;

                    try
                    {
   // Get L1 and update it
                    }
                    catch (Exception ex) { }
                    finally {
                        elevatedWeb.AllowUnsafeUpdates = bUnsafe;
                    }
                }
            }
        }
Made with Serge Lespagnard

No comments:

Post a Comment

by Category