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:
- private void UpdateProgress(object state)
- {
- SPLongOperationState state2 = state as SPLongOperationState;
- string status = null;
- if (state2 != null)
- {
- status = state2.Status;
- }
- if (string.IsNullOrEmpty(status))
- {
- status = "<!-- -->";
- }
- HttpContext.Current.Response.Write(status);
- HttpContext.Current.Response.Flush();
- }
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:
- SPStatefulLongOperation.Begin(
- "<span id='leadingHTML'>Please wait</span>",
- "<span id='trailingHTML'>First step</span>",
- op =>
- {
- op.Run(opState =>
- {
- // Инициализируем пустой статус
- opState.Status = string.Empty;
- // Выполняем операцию
- DoSomething();
- // Меняем статус
- opState.Status = string.Format(
- "<script type='text/javascript'>" +
- "document.all.item('leadingHTML').innerText = '{0}';" +
- "document.all.item('trailingHTML').innerText = '{1}';" +
- "</script>",
- "Please wait",
- "Second step");
- // Выполняем еще какую-нибудь операцию
- DoSomething2();
- });
- // При вызове метода End просто передаем URL для редиректа
- op.End("http://blog.vitalyzhukov.ru");
- });
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.