Monthly Archives: 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

.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode, .ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode pre
{font-size:small;color:black;font-family:consolas, "Courier New", courier, monospace;background-color:#ffffff;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode pre
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .rem
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .kwrd
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .str
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .op
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .preproc
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .asp
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .html
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .attr
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .alt
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .lnum



Published: 8/7/2012 10:34 AM

via Cornelius J. van Dyk at

Leave a comment

Posted by on August 7, 2012 in Uncategorized