vrijdag 25 april 2008

modify SPListItem fields with vars from the Session in the itemAdding or itemAdded events

Yesterday, a colleague of me and I tried to alter a field of a SPListItem right after the moment that the item has been created. We stored a var in the sessionState and tried to read that one, so we could use that variable to alter the newly created SPListItem.

We found out that this was not as easy as we thought.

When using the itemAdded event, the httpContext is not available, so it's not possible to get the vars out of the HttpContext.Current.Session

When using the itemAdding event, the HttpContext is available, but the properties.ListItem is null then. This is expected behaviour, because the SPListItem is only filled with data from the database and in the itemAdding event, no write actions to the database have been executed yet.

In this case, the properties.AfterProperties can be used to modify a field on creation.

below is an example that shows whether the HttpContext and properties.ListItem are null or not shows how to modify properties when an item is added.



1 opmerking:

Mohammed Barakat zei

The HttpContext.Current Is Always Null When uploading multiple docs at the same time .

I faced the same issue when I was tring to update some custom fields of my document library when uploading new documents, the field was ( ProjectID ) which I put it inside a session in my webpart ( the step before uploading the document).

What I did is : I put the projectID into the cache ( per user ) inside the custom webpart which acts as a session as follows :

if (Request.QueryString["ProjectID"] != null)
{
HttpRuntime.Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName);
HttpRuntime.Cache.Add(SPContext.Current.Web.CurrentUser.LoginName, ProjectID, null, DateTime.UtcNow.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}

then I implemented the ItemAdded event and I get the value of the cached projectId through :



public override void ItemAdded(SPItemEventProperties properties)
{
try
{

string ProjID = "";

string CreatedBy = null;
if (properties.ListItem["Created By"] != null)
CreatedBy = properties.ListItem["Created By"].ToString().Split(';')[1].Replace("#","");

if (HttpRuntime.Cache[CreatedBy] != null)
{
//SPContext.Current.Web.CurrentUser.LoginName;
ProjID = HttpRuntime.Cache[CreatedBy].ToString();

if (properties.ListItem["Project"] == null)
{
properties.ListItem["Project"] = new SPFieldLookupValue(ProjID);
properties.ListItem.SystemUpdate();
}


base.ItemAdded(properties);

}

}
catch (Exception ex)
{ }


}