What is SPContext in SharePoint

SPContext is often used with custom web parts and pages to retrieve SharePoint site objects from the context of the SharePoint site accessed. Its a good practice to use SPContext instead of creating new objects (So that we can avoid disposal of objects). SPContext object will be available for access in our coding as long as the current HttpContext is not null. Meaning, if a user is logged in to a SharePoint site, the SPContext object will always be available.

Using SPContext we can access many objects like SPWeb. There are other objects you can access using SPContext:
  • SPSite
  • SPList
  • SPListItem
  • SPFile
  • SPFIeldCollection
  • SPItem
  • SiteFeatures, etc
Here is an example of getting the current site URL and user name:

string currentWeb = "Current Site URL:" +SPContext.Current.Site.Url;
            string currentUser = "Current User Name:"+ SPContext.Current.Web.CurrentUser.Name;
            LiteralControl lblCurrentUser = new LiteralControl(currentWeb +"<br/>" + currentUser);

            //Add new List item
            SPList oSPList = SPContext.Current.Web.Lists["Tracking List"];
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            SPListItem oSPListItem= oSPList.Items.Add();
            oSPListItem["Title"] = "Created by " + currentUser;

     //Another example Using SPWeb             
            SPContext.Current.Web.Properties["SMTPServer"] = "smtp.company.com";

            SPContext.Current.Web.AllowUnsafeUpdates = false;

In same way, for event handlers, you can use, e.g. SPSite site = properties.Feature.Parent as SPSite;
SPContext is available in Sandboxed solutions also.

MSDN Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontext.aspx

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.