Find User's Internet Connectivity Using ASP.NET 2.0 Client Callback
By AzamSharp
Views: 2591

Introduction:

 

AJAX technology allows you to call the server side methods without causing the server postbacks. In AJAX applications it is very important for the user to know that the application is connected to the internet since there are no postbacks. In this article I will demonstrate a very easy technique to find out if the user is connected to the internet.

 

The Idea:

 

The idea is to start polling from the client side which will download a simple webpage. If the page is downloaded successfully then user is connected to the internet else he is not connected. Your dummy page (The page that you are going to download) should be very small to get good performance.

 

ASP.NET Client Callbacks: 

 

I will be using ASP.NET 2.0 Client Callbacks in this article but you can use any AJAX framework that you like. The first step is to register the callbacks. I have demonstrated this procedure in most of my Client Callback articles hence I am simply going to paste the code for the RegisterCallbacks method.

 

private void RegisterCallbacks()

        {

            string sbReference = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");

 

            string cbScript = String.Empty;

 

            // check if the script is already registered or not

 

            if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))

            {

 

                cbScript = @" function CallServer(arg,context) { " + sbReference + "}";

 

                ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

 

            }

        }

 

Your page class must implement the ICallbackEventHandler interface in order to use the Client Callback feature.

 

Next, we need to implement the code which is used to download the dummy page.

 

  public string GetCallbackResult()

        {

            if (CanDownloadData())

                return "Connected";

            else return "Not Connected";

        }

 

        private bool CanDownloadData()

        {

            WebClient client = new WebClient();

 

            byte[] data = null;

 

            try

            {

                data = client.DownloadData("http://www.google.com");

            }

            catch (Exception ex)

            {

 

            }

           

            if (data != null && data.Length > 0) return true;

           

            else return false;

        }

 

The method CanDownloadData is used to download the data from the URL. I am using www.google.com as my dummy page but you can use any custom page with very small amount of data. The GetCallbackResult method returns the status of the download.

 

JavaScript Implementation:

 

Now, let’s check out the JavaScript. First, we need to start a polling mechanism that will call a server side method at regular intervals. The polling is initiated when the page loads as shown below:

 

<body onload="startPolling()">

 

We have placed a DIV element which is used to show the status of the connectivity.

 

<div id="divStatus" style="position:absolute; top:30%; left:40%; display:none; border:2px solid; font-family:Verdana; padding:1em">

 

And here is the rest of the JavaScript.

 

<script language="javascript" type="text/javascript">

 

function startPolling()

{

   window.setInterval("CallServer('','')",5000);

}

 

function ReceiveServerData(response)

{

      

    if(response == 'Connected')

    {

   

    document.getElementById("divStatus").style.display = 'block';

    document.getElementById("divStatus").innerHTML = 'You are connected to the internet';      

    }

   

    else if(response == 'Not Connected')

    {

    document.getElementById("divStatus").style.display = 'block';

    document.getElementById("divStatus").innerHTML = 'You are not connected to the internet';     

    }

}

 

</script>

 

The server method is called every 5 seconds which tries to download a dummy page. If the server was able to download the page then we displays “Connected” else “Not Connected”.

 

I hope you liked this article, happy programming!

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: You are testing what?
Name: Wesley
Date: 10/28/2007 8:03:25 AM
Comment:
You're testing if the server can download from google.com? What use is that?

If the client isn't connected he will not be able to request your page in the first place so...

What's your point?
Subject: RE: You are testing what
Name: AzamSharp
Date: 10/28/2007 9:20:15 AM
Comment:
Hi Wesley,

You are missing the point. The page is AJAX based and there is no postback hence there is no way for the client/user to know that if he is connected to the server or not. This is a common problem in AJAX applications. Build an AJAX page and test it out yourself. The page will remain there on your screen even if the internet is disconnected. This is because there is no refresh and hence the page is not rendered again and again like other sync web application pages.
Subject: Return Status
Name: Mark Smith
Date: 10/28/2007 12:41:02 PM
Comment:
If the client has no internet connection, then they will not be able to make the AJAX request to your server. If they can't make the request, your server cannot return the "Not Connected" message. As your javascript code specifically looks for a string which is equal to "Not Connected", surely when no internet connection exists this will never be set to "Not Connected"?
Subject: Not well thought out
Name: Mike
Date: 10/28/2007 2:32:26 PM
Comment:
What happens if for some reason the page you are downloading isn't available? Why don't you simply recursively check the readyState of the clientside request object every ten seconds or so instead?
Subject: RE: RE: You are testing what
Name: Thomas
Date: 10/28/2007 6:10:23 PM
Comment:
Hi,

I don't think he missed the point.

Since GetCallbackResult() is implemented server side you are checking if the server is connected to the internet.

I don't think this is intended as you say you want to test the connectivity of the client.








Subject: Wrong idea
Name: neo
Date: 10/29/2007 6:21:08 AM
Comment:
Your scenario solves the problem of testing if the server is on the internet. Why do you care? All you care about is if you can reach the server.

Two possible questions?

1. Check if client is connected to server?
2. Check is server is online(available)?

Both can be answered using your approach and a dummy funtion call:

public string GetCallbackResult()
{return "Connected";}

Not you know both parties are communicating with each other.



Subject: Dont get it
Name: Josh Stodola
Date: 10/29/2007 7:10:19 AM
Comment:
I dont understand the practical purpose in this. What do you plan to do when you find out they are not connected? Redirect them to another page?! Save the changes they just made on your server?! Seems useless to me.

Best regards...
Subject: RE: You are testing what?
Name: AzamSharp
Date: 10/29/2007 7:41:22 AM
Comment:
Hi,

You guys are right! I missed the point duhhh. If you are not connected to the internet then you cannot talk to the server period. This is what happens when you are coding late night with no idea what is going on the screen.

Thanks for the feedback,
Azam
Subject: How?
Name: PJ
Date: 10/29/2007 9:17:16 AM
Comment:
How the user will be able to postback if he is not connected to internet even with AJAX?
Subject: Maybe Righ Idea
Name: Tom
Date: 10/29/2007 9:18:51 AM
Comment:
This can be used in intranet but the application still wants to check user's internet connection.
Subject: testing
Name: Michael
Date: 10/30/2007 12:16:40 AM
Comment:
testing
Subject: I wouldnt use body onload (Old School way of doing things)
Name: Rob
Date: 11/1/2007 7:20:27 AM
Comment:
Here is a better and NEW schoold way of doing that:

How to call scripts - Unobtrusive Javascript
http://tinyurl.com/38ynnf

OR even better

Top 10 custom JavaScript functions of all time
http://tinyurl.com/ftuff
Subject: Sessin Problem
Name: Pushkar
Date: 12/28/2007 3:30:17 AM
Comment:
hii thanx for the post...well i have one issue that i want to check that After Login user is still connected or not in ASP.NET...My website is Hosted.Actually i have already given session.timeout = 30 in web.config but it Logiut before 30 mins automatically....so can you pls give me solution for that...Give me example.
Subject: RE: Session Problem
Name: AzamSharp
Date: 12/29/2007 6:27:19 PM
Comment:
Hi Pushkar, You might be confusing with Session and Cookie. I think you should increase your Cookie timeout i.e if you are using FormsAuthentication to create a cookie. Session timeout is different and is used for the timeout of the objects residing inside the Session bag.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008