SPStatefulLongOperation sample


SharePoint long operation is a great component when it comes to run lenghty operations and still give the user nice loading view.

The issue with the mostly used SPLongOperation is that it gives the user static loading message during the whole operation.

The beauty about the not so famous SPStatefulLongOperation that it extends the functionality of SPLongOperation (actually it’s drived from it) and gives us the ability to keep the user posted by the progress of the lengthy operation via the SPLongOperationState Status property.

Important!  SPContext is always null within the stateful oprtation.

Below a quick sample code (in an application page) for your reference:

.aspx

<asp:Content ID=”PageHead” ContentPlaceHolderID=”PlaceHolderAdditionalPageHead” runat=”server”>

</asp:Content>

<asp:Content ID=”Main” ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>

    <h1>SPStatefulLongOperation Demo</h1>

    <div>

        <asp:Button runat=”server” ID=”btnStart” Text=”Start” OnClick=”btnStart_Click”  />

    </div>

</asp:Content>

<asp:Content ID=”PageTitle” ContentPlaceHolderID=”PlaceHolderPageTitle” runat=”server”>

Application Page

</asp:Content>

<asp:Content ID=”PageTitleInTitleArea” ContentPlaceHolderID=”PlaceHolderPageTitleInTitleArea” runat=”server” >

My Application Page

</asp:Content>

.aspx.cs

protected void btnStart_Click(object sender, EventArgs e)

        {

            var sites = Microsoft.SharePoint.SPContext.Current.Site.WebApplication.Sites;

            Microsoft.SharePoint.SPStatefulLongOperation.Begin

                (

                  “<span id=’statusSpan’>Please wait</span>”,

                 “”,

                op =>

                {

                    op.Run(opState =>

                    {

                        opState.Status = string.Format(“{0}”, “document.getElementById(‘statusSpan’).innerHTML = ‘Starting….’;”);

                        foreach (Microsoft.SharePoint.SPSite site in sites)

                        {

                            opState.Status = string.Format(“{0}”, string.Format(“document.getElementById(‘statusSpan’).innerHTML = ‘Site Id = {0}’;”, site.ID.ToString()));

                            System.Threading.Thread.Sleep(1000);

                        }

                    });

                    op.EndScript(“document.getElementById(‘statusSpan’).innerHTML = ‘Done’;”);

                });

        }

I hope that helped

Ahmed

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s