Tuesday, April 19, 2011

Understanding The SharePoint SPContext Class

When developing new functionality for your SharePoint site the SPContext class is pretty much critical. Whenever you want to get your hands on objects in your current context you will need SPContext. As the name implies it helps you get information and objects regarding the context you're working in. It shouldn't be hard for any developer to see the use of that.

SharePoint Get Current Web


So, if the task at hand requires you to get information regarding the web your are currently working with you will use the SPContext. That could look something like this:
SPWeb oWeb = SPContext.Current.Web;

That line of code is off course blatantly borrowed from the MSDN article mentioned below. However, that's the way to get your current
SPWeb
object and from then on you can start working with the object.

What Can I Get With SPContext?


According to the MSDN article on SPContext you can work with web applications, site collections, sites, lists and list items. That's more or less anything you would want to get your hands on in the current context. Also it's worth taking a look at the members list I link to below. This gives you a pretty solid overview of the information you can get out of the SPContext class.

SPContext Members At A Glance


All SPContext members are listed in the SPContext Members article. I think it's fair to say that
Current
is the most notable. Off course, That is often used in conjunction with the
Site
and
Web
members. Looking at the list you can certainly fint many uses.

It's definitely worth it familiarizing yourself with the SharePoint SPContext class as there is no doubt you will be using it frequently. Also make sure you know when and when not to dispose your SPSite and SPWeb objects. In the long run those undisposed sites and webs will cost you a lot of unnecessary server resources if you don't handle them correctly.