I have discussed this topic also in Deep Dive into the SharePoint Content Deployment and Migration API - Part 7 but as this is an important topic for everyone - not only people coding against the Content Deployment and Migration API I though to post it also using a headline that will catch the eyes of people developing Event Handlers and Feature Activation code.
In MOSS 2007 we often had support calls where content deployment failed due to event handlers firing and updating content during import.
Event handlers or feature activation code which modifies site content on the target system can cause all kind of issues:
- Can cause deadlocks with conflicting with the import operation
- Might create new items which will are also included in the package being imported causing import to fail later with GUID conflicts.
To overcome this problem developers had the challenge to either detect that the event handler was fired in context of an import operation (which was not trivial) or a different version of the event handler code had to be installed on the target system to avoid performing the operations.
With SharePoint 2010 there is now a new class available (SPImportContext) which allows an event handler or feature activation code to detect easily if they are fired in context of an import operation or not.
On SharePoint 2010 all event handlers and feature activation code which modify content in the database can now (and should) implement a check of SPImportContext.Current.IsRunning to detect if the code execution is a side effect of an import operation or not.
That allows a developer to implement a separate code path in the event handler which avoids problems during import.
SPImportContext provides the executing code access to the following information:
- If the current method is called as side effect of an import operation (IsRunning)
- If the import is performed with RetainObjectIdentity (RetainObjectIdentity)
- If the import operation is currently in the process to fix broken lookup columns (FixingBrokenLookups)
- The status of the Import operation (Status)
Be aware that SPImportContext can only work for event handlers which execute on the same thread as the import operation. Asynchronous event handlers which are executed on a different thread cannot detect that they were invoked from an import operation. This affects especially the default "after events" which execute after a change has been performed. These event usually fire asynchronously on a different thread. "Before events" which fire before a change is done will always execute on the same thread.
There are two workaround for this issue:
- Disable after events completely during import (see details)
- Configure the required after events to execute synchronously (see details)