Home > Uncategorized > SPContext class in WSS V3

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.


 

Categories: Uncategorized Tags:
  1. No comments yet.