Reza on blogging [MVP]

THIS BLOG HAS MOVED TO: http://blogs.devhorizon.com/reza

Subscriptions

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

News



toronto.sharepoint.camp


Navigation

Post Categories

Other Bloggers

Personal Links

SPContext class in WSS V3

Fortunately Windows SharePoint Services V3 (SharePoint 2007) Object model offers a high level of backward compatibility with its predecessor(V2) , so we expect that most of our code written for previous version just work fine in new version as well. Microsoft has introduced a new class in Windows SharePoint Services V3 (SharePoint 2007) called SPContext. I have seen that some developers are having difficulty understanding the concept of CONTEXT in web applications particularly in SharePoint. SPContext in WSS V3 is not a new concept. It basically does what we used to do using SPControl in WSS V2, except it is a cleaner way of getting an entry point to a site or site collection in V3.

WSS V2:
SPSite siteCollect= SPControl.GetContextSite(this.context);      //returns the site collection in which current site exists
SPWeb site= SPControl.GetContextWeb(this.context);             //returns the site in which your code is executing

WSS V3:
SPSite siteCollect= SPControl.GetContextSite(this.context);    //returns the site collection in which current site exists
SPSite siteCollect= SPContext.Current.Site                            //returns the site collection in which current context exists
SPWeb site= SPControl.GetContextWeb(this.context);           //returns the site in which your code is executing
SPWeb site= SPContext.Current.Web;                                  //returns the site in which current context exists

One important thing to remember is that all above statements work only if your code is running in the context of a SharePoint site. If your code is running in another IIS web site different than the IIS web site in which SharePoint site exists, none of the above statement works properly and you have to use the following piece of code in both WSS V2 and V3:
SPSite sc2= new SPSite("http://localhost");                            //returns the site collection exists in localhost virtual server(IIS WebSite)

As you see, here we have to explicitly state which context we are working with since we are outside of the SharePoint site context.

 

posted on Sunday, July 16, 2006 3:03 PM by admin

Powered by Community Server, by Telligent Systems