Invoking Server Side code using ASP.NET AJAX Client Callback on Web browser close

If your ASP.NET web application creates temporary data for the each session, it needs to be deleted while user logs out. If you use InProc session mode, then you can handle Session_End event in the Global Application file(Global.asax) to clear the temporary files.

Suppose if you use other than InProc session mode[i.e., StateServer, SQLServer etc.,], then you have to write custom logic to delete the temporary files while user logs out.

Till now you everything is fine, if user logs out of the using Logout option in your web application. What if User closes the browser unintentionally? The temporary files remain undeleted!

Let us discuss a solution which handles the above problem using ASP.NET AJAX with JavaScript.  First of all we need to a notification, when user closes the browser. So let us create a JavaScript function, which notifies the Web browser close.

<script type="text/javascript">
        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            return "Are you sure to close the browser?";
        }
    </script>

The above code notifies the user, if he tries to close the browser.

NOTE: User gets notification even when he traverse to other page. So you need to use a Boolean variable to check whether  the user is traversing to other page or trying to close the browser!

Now we will create Server Side Code to delete the temporary files! Implement the ICallbackEventHandler interface to call Server Side code from Client code(JavaScript).

#region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return "";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            string      strTempLoc      =  Session["TempFilesDir"].ToString();
            string[]    strTempFiles    = null;

            try
            {
                if (!string.IsNullOrEmpty(strTempLoc) &&
                    Directory.Exists(strTempLoc))
                {
                    strTempFiles = Directory.GetFiles(strTempLoc);

                    //Delete all the files in the temp location
                    foreach (string strTempFile in strTempFiles)
                    {
                        File.Delete(strTempFile);
                    }

                    Directory.Delete(strTempLoc);
                }
            }
            catch (IOException)
            {

            }

        }

        #endregion

Now register the JavaScript functions to invoke the Server Side code.

protected void Page_Load(object sender, EventArgs e)
{
//Get the Client Call back event reference
            string strCallBackRef = Page.ClientScript.GetCallbackEventReference(this, "", "DeleteStatus", "");

            //Form the callback function which is invoked in the Client side
            string strCallBackScript = "function DeleteTempFiles()" + "{" + strCallBackRef + ";}";

            //Register
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                                                        "MyServerCall",
                                                        strCallBackScript,
                                                        true);
}//end: Page_Load function

Now invoke the function on Web browser close as shown below!

 <script type="text/javascript">

        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            //Server Side Code call back
             DeleteTempFiles();
        }

       //Client Call back
        function DeleteStatus(result) {
        }

    </script>

Hope it helps u…

Happy Web Programming!!!

About roopeshreddy

I'm Software Engineer works for Rebus Technology Inc., develops web applications.
This entry was posted in ASP.NET AJAX and tagged , , , , . Bookmark the permalink.

2 Responses to Invoking Server Side code using ASP.NET AJAX Client Callback on Web browser close

  1. abaj says:

    Well explained. thanks. I found similar one with simple example and explanation
    http://techleadinsight.blogspot.com/2011/12/invoking-server-side-code-from-client.html

  2. Rumesh Srivastav says:

    That is such a good information. Well Explained. Its really helpful for me. Thanks for this precious post. This link…
    http://mindstick.com/Articles/935d6d35-4391-49e4-86dc-e0f877419bec/?Using%20the%20Callback

    also helped me to complete my task.

    Thanks everyone for your precious post, its really saved my time.

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 )

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