Friday, November 18, 2011

Running Commands with Elevated Privileges in Windows SharePoint

Microsoft Windows SharePoint Services uses impersonation so that code running within a Web Part or behind a custom application page executes with the identity and permissions of the current user. In the vast majority of cases, this behavior is exactly what you want because it prevents standard users from being able to execute commands or see information that is intended only for privileged users such as a site administrator. 

However, occasionally your code must call restricted methods within the Windows SharePoint Services object model even though the request is initiated by a nonprivileged user. In such cases you must be able to elevate the privilege of your code as it executes on the Web server.

SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
      string Visits = ElevatedsiteColl.Usage.Visits.ToString();
      string RootAuditEntries = 
          ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
    }
  }
});

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

Open Hardware Monitor A Handy Tool for System Monitoring

#Open #Hardware #Monitor: A Handy Tool for #System #Monitoring #OpenHardwareMonitor is a free, #opensource #software designed to monitor t...