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..
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s