kwizcom banner advertisement

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);
            Controls.Add(lblCurrentUser);

            //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;
            oSPListItem.Update();

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

            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
What is SPContext in SharePoint What is SPContext in SharePoint Reviewed by Salaudeen Rajack on 6:48 PM Rating: 5

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.