Thursday, December 22, 2011

SPSecurity.RunWithElevatedPrivileges

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))
{
              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);
                 //Logic
           }
       }
   });
}

Wednesday, December 21, 2011

Understanding Sessions

Enabling Sessions

How to enable sessions in a SharePoint Web Application:

Open the web.config file of your web application and do the following:
Locate the <modules> section, and just below <remove name="Session" />, add a new element:
 <add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />


Then, locate the <pages> element and enable session state:
    <pages enableSessionState="true" ...
 

Enable or disable session state across the entire farm

  1. On the taskbar, click Start, point to Administrative Tools, and then click SharePoint 3.0 Central Administration.
  2. In the top navigation bar, click the Application Management tab.
  3. On the Application Management page, in the Office SharePoint Servers Shared Services section, click Configure session state.
  4. On the Configure Session State page, in the Enable Session State section, select the Enable Session State check box to enable session state for the farm.
  5. To specify the duration of sessions, in the Timeout section, enter a number (in minutes) in the Session should be timed out after (minutes) box. The default is 60 minutes.
  6. Click OK to save the session state configuration.