Monday, December 3, 2012

How to display live server side processing/messages in a browser

How to display live server side processing/messages in browser.

Use this in case the webpart/application invokes a long running processes. This way the user will continuously be updated on the progression of code execution. In my particular case I'm using a textbox to pass messages onto but feel free to replace it with any other type of control, such as a progression bar. You can make it as fancy as you want, sky's the limit. The trick is to create an iframe, in which you embed the application page that actually calls the long running process. So you'll need a few things here

- A parent .aspx page with a textbox ('txtLogs')
- An 'child' .aspx page ('LongRunningOp.aspx') which will execute the code. The page itself will not contain any controls, just code behind
- An iframe to embed that child .aspx within the parent page
- An update function to update the textbox, which will be called through the child .aspx page

Creating the iframe will be accomplished by using the following piece of code

function BeginLongRunningOp() {

       var iframe = document.createElement("iframe");

       // set the source to the .aspx, in this example it can be found in the layouts folder of the 14
       // hyve as i created this for a SP2010 webpart
       iframe.src = "/_layouts/CodingNCrap/LongRunningOp.aspx";
       iframe.style.display = "none";
       document.body.appendChild(iframe);
}

Calling this function from the parent page will open the child page and start the execution. You will also need an additional function to update the textbox as code is execution:

function UpdateProgress(Message) {
       var logWindow = document.getElementById('<%= txtLogs.ClientID %>');
       logWindow.value = logWindow.value + Message;
}

Last thing needed to make this work is to go to the code of the child .aspx page and add the following line to your method that will make the update:

protected void UpdateProgress(string Message)
{
       try
       {
              Response.Write(String.Format("< script>parent.UpdateProgress({0});< / script>", Message));
       }

       catch (Exception exc)
       {
              // your exception handling logics here
       }
}