Thursday, August 11, 2011

How to programmatically ensure full permission to the list, document etc.

Sometimes we need to grant full permission to the list, library etc. even user has not access to that list. Let's imagine this situation. You have Site A with list "Orders" on it and also you have site B. On site B is web part which shows data in "Orders" list, but if user has no-permission to the Site A or "Orders" list you can't use code below because you wold get an error that user has no-permission to the site:

                   SPSite site = new SPSite("http://spsite/siteA");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Orders"];


                    foreach (SPItem i in list.Items)
                    {
                        someTable.Add(i["Name"].toString());
                    }

Solution for this is more than simple. All you have to do is use SPSecurity class and RunWithElevatedPrivileges method. This method will grant you full control rights. Using this method and code above would look like this:

                SPSecurity.RunWithElevatedPrivileges(delegate()
               {      

                    SPSite site = new SPSite("http://spsite/siteA");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Orders"];


                    foreach (SPItem i in list.Items)
                    {
                        someTable.Add(i["Name"].toString());
                    }
              });

Easy, isn't it? Here is the link to the source to get more informations: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

No comments:

Post a Comment