Pages

Tuesday 28 May 2013

Using SPLongOperation SharePoint 2010 (For long processing requests)

Sometimes the actions triggered by users can take a while to process. This can for example happen when you create a site collection, or connecting to backend services which takes time to execute.
In this case instead to keep user waiting we can show him a SP processing page.
To use SPLongOperation, you need to create a new object of the SPLongOperation type, set the LeadingHTML and TrailingHTML properties to tell user what’s going on at the moment and call the SPLongOperation.Begin method to start the process. Then run the code of the lengthy server operation. Once the operation is done, call the SPLongOperation.End method passing the URL where user will be redirected to.























Example:
private void SPOperationWithProgressIndicator()
{  
  // Determine the page to navigate to when the operation is successful   
 string successUrl = SPContext.Current.Web.Url;
 // Create a new SPLongOperation
    
SPLongOperation longOperation = new SPLongOperation(this.Page);
    // Provide the text displayed in bold
    
 longOperation.LeadingHTML = “Long running operation is being performed”;
    // Provide the normal formatted text
    
 longOperation.TrailingHTML = “Please wait while your request is being performed. This can take a couple of seconds.”;
    // Let’s start the code that takes a while from here
    
 longOperation.Begin();
    try   
 {        // The code that might take a while
       
Thread.Sleep(5000);
        //When the action is performed, the page will be redirect to this url       longOperation.End(successUrl);  
  }      
 catch (Exception ex)   
 {       
 // When an exception occurs, the page is redirected to the error page.        // Redirection to another (custom) page is also possible        SPUtility.TransferToErrorPage(ex.ToString());   
 }}
Please also note that SPLongOperation keeps connection between client and server alive and the Response stream open.
Therefore, if your long operation takes longer than the value of httpRuntime.executionTimeout defined in Web.config (or Machine.config) you will receive the ‘Request Timed Out’ exception. Therefore, to perform a really long operation (for example, longer than the default time-out value, which is 90 seconds),
you would have to refuse SPLongOperation and look for some other approach.

No comments:

Post a Comment