Checking connectivity to your server using silverlight and javascript (synchronous)

In general, checking connectivity to your server using silverlight and javascript is not a very complex task. A normal service call or a web client can do this. However, there may be situations when these are not sufficient. For instance, there may be a situation when you need to connect to the server synchronously. Since service calls and web clients only allow you to connect asynchronously, you will need to do something extra to accomplish what you want. The trick here is to let javascript check for connectivity and the reply back to silverlight as shown:


java script
function checkConnectivity(query) {
// alert(query);
var x = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP")
var s;
x.open("HEAD",query,false);
try
{
x.send();
s = x.status;
//alert(s);
return (s >= 200 && s < 300 || s == 304 || s==400);
}
catch (e)
{
return false;
}
}

This is what you need to do in silverlight:

public bool CheckConnectivity()
{
string uri = string.Format("http://google.com?rand={0}", DateTime.Now.ToString("ddMMyyyyhhmmss"));
try
{
var t = System.Windows.Browser.HtmlPage.Window.Invoke("checkConnectivity", uri).ToString();
bool connected = true;
bool.TryParse(t, out connected);
return connected;
}
catch { return false; }
}

Leave a Reply

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


three + 7 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>