Thursday, May 28, 2009

Performing Long Running Tasks in SharePoint

Occasionally you may have a custom action that takes a while to run. On one of my recent projects we had just this need. Basically we wanted to convert an ordinary out of the box document library into a 'Projects' Document library. This involved setting the properties of the library (e.g. versioning, content types, enforce checkout etc), adding new content types to the library, setting up workflows for the library and applying event handlers.
The way that we did this was to create an Application page (under layouts), which got called by the custom action. Within the OnLoad of this page, we had the following:

using (SPLongOperation operation = new SPLongOperation(this.Page))
{
try
{
operation.LeadingHTML = "Convert to Project Documents library";
operation.TrailingHTML = "Please wait while your document library is being prepared for project use.";
operation.Begin();

// your code goes here

operation.End(string.Format("{0}&ConversionStatus={1}", this.CurrentRequestUrlAndQuery, FormSubmitStatus.Success.ToString()));
}
catch (Exception ex)
{
// record the error
operation.End(string.Format("{0}&ConversionStatus={1}", this.CurrentRequestUrlAndQuery, FormSubmitStatus.Fail.ToString()));
}
}

How easy is that? SharePoint Rocks!

No comments: