RSS

Monthly Archives: August 2012

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

Body:

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
{margin:0em;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .rem
{color:#008000;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .kwrd
{color:#0000ff;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .str
{color:#006080;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .op
{color:#0000c0;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .preproc
{color:#cc6633;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .asp
{background-color:#ffff00;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .html
{color:#800000;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .attr
{color:#ff0000;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .alt
{background-color:#f4f4f4;width:100%;margin:0em;}
.ExternalClassCDCA6CBBADD2495CB39CC22E1A0F191E .csharpcode .lnum
{color:#606060;}

 

image

Published: 8/7/2012 10:34 AM

via Cornelius J. van Dyk at http://www.cjvandyk.com/blog/Lists/Posts/ViewPost.aspx?ID=356

Advertisements
 
Leave a comment

Posted by on August 7, 2012 in Uncategorized