Skip to main content
Go Search

Ayman El-Hattab's Blog [MVP]

Home
Ayman El-Hattab's Blog
Marwan Tarek's Blog
Mohamed Yehia's Blog
  

SharePoint 4 Arabs - Online SharePoint Training, Video Tutorials and Webcasts in Arabic > Ayman El-Hattab's Blog [MVP] > Posts > Be Careful When Using properties & SPContext
Be Careful When Using properties & SPContext
What is SPContext ?
In a nutshell, SPContext object can be used to get a reference to the site or the web from the current context, It Represents the context of an HTTP request in SharePoint .
For instance :
SPList currentList = SPContext.Current.List;
SPWeb currentSite = SPContext.Current.Web;
SPSite currentSiteCollection = SPContext.Current.Site;
SPWebApplication currentWebApplication = SPContext.Current.Site.WebApplication;
SPListItem item = (SPListItem)SPContext.Current.Item;
SPUser user = SPContext.Current.Web.CurrentUser;

What is "Properties" ?
The properties object holds information about an event. You can use it to get references to SPSite, SPWeb, SPList or SPList Item.
for instance :
SPListItem item = properties.ListItem'

However,
Be VERY careful when using properties parameter or SPContext. You CANNOT use the properties command to create your objects or your code will fail! .
You need to use properties or SPContext to locate the items, then use the items IDs to create the object references. You will never get your code to work the way it is above.
You need to get all of the Guid identifiers BEFORE entering the secure block ( RunWithElevatedPriveleges) or Impersonation, then create all the objects you need WITHIN the secure context

Guid SiteId = SPContext.Current.Site.ID;
Guid WebId = SPContext.Current.Web.ID;
Guid ListId = properties.ListId;
Guid UniqueId = properties.ListItem.UniqueId;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site= new SPSite(SiteId))
{
using (SPWeb web= site.AllWebs[WebId])
{
SPList list= web.Lists[ListId];
SPListItem listItem= list.Items[UniqueId];
// Code..
}
}
});

or to impersonate the system account using SPUserToken ( Recommended )

Guid SiteId = SPContext.Current.Site.ID;
Guid WebId = SPContext.Current.Web.ID;
Guid ListId = properties.ListId;
Guid UniqueId = properties.ListItem.UniqueId;
SPUserToken systemAccountToken = SPContext.Current.Site.SystemAccount.UserToken;
using(SPSite mySite = new SPSite(SiteId, systemAccountToken))
{
using (SPWeb myWeb = mySite.OpenWeb(WebId))
{
SPList list= web.Lists[ListId];
SPListItem listItem= list.Items[UniqueId];
// Code..
}
}

Comments

There are no comments yet for this post.
Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Attachments