07 August 2012

SharePoint Fundamentals – How do I programmatically get a reference to a SharePoint site following Best Practices using C#



This is one of the most fundamental building blocks for all SharePoint developers. We get references to SPWeb and SPSite objects all the time without ever giving a second thought to how it’s done. I’ve decided to document the recommended way to do this, combining guidance I frequently provide to SharePoint admins with regard to dealing with developer code via the Developer Dashboard. This little snippet is thus intended to start guiding developers towards making it a habit to wrap sections of code in the SPMonitoredScope class. I have provided the complete namespace of objects for completeness sake.

A reference to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.dll is required.

Here’s the code:

using (new Microsoft.SharePoint.Utilities.SPMonitoredScope("ScopeName"))
{
  using (Microsoft.SharePoint.SPSite sps = new Microsoft.SharePoint.SPSite("SiteURL"))
  {
    using (Microsoft.SharePoint.SPWeb spw = sps.OpenWeb())
    {
      //Do something
    }
  }
}

Cheers
C

No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...