A lot of times there is a need to perform certain actions when a user is leaving some Silverlight control like updating database and performing some cleanup. This is a tricky situation because user may just close the browser window or hit a refresh to reload the Silverlight control without giving the control a chance to clean itself up. When this happens Silverlight application’s Exit even is raised but if you try to perform some backend action like calling a web service it won’t go through since the thread required to make the service call itself is gone so how do we fix this problem. This is where we have to rely on some java scripting. The first step in this process is to invoke a java script method in Application_Exit method.

private void Application_Exit(object sender, EventArgs e)
{
HtmlPage.Window.Invoke(“NotifyOnClose”,
string.Format(“WindowClose.aspx?value1={0}&value2={1}”, ID1, ID2));
}

Add following javascript method in your page which is hosting Silverlight control (XAP)

function NotifyOnClose(url) {
// Create HTTP request
var xmlHttp;
try {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e) {
alert(“This sample only works in browsers with AJAX support”);
return false;
}
}
}

// Build the operation URL
try {
xmlHttp.open(“GET”, url, true);
xmlHttp.send();
} catch (e) {
}

}

Now let us try to understand the code. Its pretty simple. All we do here is to send an XMLHttpRequest and call a URL. The URL can be a simple page which handles all the cleanup work for you. The reason we use XMLHttpRequest here is that it is going to execute even after the browser is closed since the java script method will be called in the event of browser exit. I have not tried calling a web service using XMLHttpRequest but that is something I plan to do in future. For now simple page call will handle all the cleanup work for me and as you can see I am passing all required information for cleanup as query parameters to the page.

How to cleanup in Silverlight on browser close

Leave a Reply

Your email address will not be published. Required fields are marked *