Tuesday, August 28, 2012

Getting References to Sites, Web Applications, and Other Key Objects


There are two methods to do this: one method applies when your code will be used in a console or Windows-based application; the other applies when your code will be used in a browser-hosted application, such as when you choose "Web Site" as the type of Microsoft Visual Studio project.

To work with a deployment of SharePoint Foundation by means of a browser-hosted application, your code must first establish the site context or site collection context for requests that are made to the server.

You must obtain the HTTP context of the request in the code. Microsoft recommends that you do this by using the Microsoft.SharePoint.SPContext class and its members. Some examples are as follows.

To return the current site collection, you can use the Current.SPContext.Site property.

SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWebSite = SPContext.Current.Web;
SPWeb oWebSite = SPControl.GetContextWeb(Context);
SPWeb oWebSite = this.Web;

To return the current top-level server farm object, use SPContext.Current.Site.WebApplication.Farm.

SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm;
SPWeb oTopSite = SPContext.Current.Site.RootWeb;


The SPContext class has no meaning in a console or Windows-based application. If you are writing code for either of those types of applications and you want to work with a specific site collection, use the SPSite constructor to instantiate an object that represents the site collection, as in the following example.
SPSite oSiteCollection = new SPSite("http://localhost");
oSitecollection.Dispose();
// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPSite oSiteCollection = new SPSite("http://localhost"))
{
   ……..
                         }

No comments:

Post a Comment