SharePoint 2010. Long time operation with updatable status

There is SPStatefulLongOperation class in SharePoint 2010 that lets implement long time operation with updatable status.

This class based from SPLongOperation and works the same. Trick than makes browser be awaiting till the end of server-side operation is this: there is no trailing BODY tag. In contrast to the parent class SPStatefulLongOperation writes into response (body of a page) status text every second. UpdateProgress method does it:

  1. private void UpdateProgress(object state)
  2. {
  3.     SPLongOperationState state2 = state as SPLongOperationState;
  4.     string status = null;
  5.     if (state2 != null)
  6.     {
  7.         status = state2.Status;
  8.     }
  9.     if (string.IsNullOrEmpty(status))
  10.     {
  11.         status = "<!-- -->";
  12.     }
  13.     HttpContext.Current.Response.Write(status);
  14.     HttpContext.Current.Response.Flush();
  15. }

During the operation user sees page like this (if version of UI is equal 4):

As we can only append to Response, but not modify it, then best case (in my opinion) is sending to the client portion of javascript-code, which replaces LeadingHTML and TrailingHTML by the new text.

Example

Here is a simple example to use this class:

  1. SPStatefulLongOperation.Begin(
  2.     "<span id='leadingHTML'>Please wait</span>",
  3.     "<span id='trailingHTML'>First step</span>",
  4.     op =>
  5.     {
  6.         op.Run(opState =>
  7.         {
  8.             // Инициализируем пустой статус
  9.             opState.Status = string.Empty;
  10.             // Выполняем операцию
  11.             DoSomething();
  12.             // Меняем статус
  13.             opState.Status = string.Format(
  14.                     "<script type='text/javascript'>" +
  15.                     "document.all.item('leadingHTML').innerText = '{0}';" +
  16.                     "document.all.item('trailingHTML').innerText = '{1}';" +
  17.                     "</script>",
  18.                     "Please wait",
  19.                     "Second step");
  20.             // Выполняем еще какую-нибудь операцию
  21.             DoSomething2();
  22.         });
  23.         // При вызове метода End просто передаем URL для редиректа
  24.         op.End("http://blog.vitalyzhukov.ru");
  25.     });

DoSomething and DoSomething2 methods are executed as a result of above code. Before second method executing javascript code updates the status text. This lets us to alert users about current state of the operation.


Share

Comments