The ideal way to Elevate Privileges:
(Code written on the run - Check for build errors)
Guid SiteID = SpWeb.Current.Site.ID;
Guid WebID = SPWeb.Current.Web.ID;
SpSecurity.RunWithElevatedPrivileges(delegate(){
using (SPSite oSite = new SPSite(sSiteID))
{
});
One thing to be kept in mind while implementing such logic is that any SP Object with is created outside of the RWEP belongs to that particular context and when that SP Object is sent inside the RWEP, the elevation is lost.
For Example, if I need to use a list within the RWEP, then I should follow these:
DoSomethingWithTheList(SPList tempList)
{
Guid SiteID = SpWeb.Current.Site.ID;
Guid WebID = SPWeb.Current.Web.ID;
string sListName = tempList.Title;
SpSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(sSiteID))
{
});
}
(Code written on the run - Check for build errors)
Guid SiteID = SpWeb.Current.Site.ID;
Guid WebID = SPWeb.Current.Web.ID;
SpSecurity.RunWithElevatedPrivileges(delegate(){
using (SPSite oSite = new SPSite(sSiteID))
{
using (SPWeb oWeb = oSite.OpenWeb(WebID))
{
//Logic
}
}});
One thing to be kept in mind while implementing such logic is that any SP Object with is created outside of the RWEP belongs to that particular context and when that SP Object is sent inside the RWEP, the elevation is lost.
For Example, if I need to use a list within the RWEP, then I should follow these:
DoSomethingWithTheList(SPList tempList)
{
Guid SiteID = SpWeb.Current.Site.ID;
Guid WebID = SPWeb.Current.Web.ID;
string sListName = tempList.Title;
SpSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(sSiteID))
{
using (SPWeb oWeb = oSite.OpenWeb(WebID))
{
SPList oList = oWeb.Lists.TryGetList(sListName);
SPList oList = oWeb.Lists.TryGetList(sListName);
//Logic
}
}});
}