Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Display an Internet Connection status icon using .NET Framework 2.0

0.00/5 (No votes)
20 Jul 2005 1  
This article explains how to use a BackgroundWorker and a StatusStrip to display an Internet connection status icon on a StatusStrip using .NET Framework 2.0.

Sample Image - InternetConnectionStatusScreenShot.jpg

Introduction

More and more likely, applications depend on an available Internet connection to perform business-layered operations such as invoking web services, obtaining data, and so on. Usually you would like to know if the current environment is really connected. There are multiple approaches to accomplish this, you could check the state of every NetworkInterface using the System.Net namespace, but then having an Ethernet connection or similar doesn�t really tell you if there is an available Internet connection or not.

This article shows a way to get a simple icon on a StatusStrip that shows if the computer is or is not connected to the Internet.

Using the code

Basically you want to get a Timer to perform an HTTP-GET in order to see if a specific website is or is not available.

The only requirement for this kind of functionality is that we don�t want to stop the current UI thread. Therefore, I am using a BackgroundWorker object to perform the query. The BackgroundWorker object declares the DoWork method which defines a custom event handler that defines the DoWorkEventArgs class in which you pass the actual result back into the UI thread. It is very important that you don�t try to interact with any UI element at this method since this is running on a separate thread.

private void InitializeComponent()
{
    // Background Worker

    this._worker = new BackgroundWorker();
    this._worker.WorkerReportsProgress = false;
    this._worker.WorkerSupportsCancellation = false;
    this._worker.DoWork += new 
       DoWorkEventHandler(this.BackgroundWorker_DoWork);
    this._worker.RunWorkerCompleted += new 
       RunWorkerCompletedEventHandler(this.BackgroundWorker_RunWorkerCompleted);

    // Timer

    this._updateTimer = new Timer();
    this._updateTimer.Enabled = !this.DesignMode;
    // Enabled when not in design mode


    this._updateTimer.Tick += delegate { this.OnTick(); };
}

private void OnTick()
{
    if (this.DesignMode)
        return;

    // Stop the timer while the process is running

    this._updateTimer.Enabled = false;

    // Disable so we get the grayed-out look

    this.Enabled = false;
    this.Invalidate();

    // Execute the Ping Query on a separate thread...

    this._worker.RunWorkerAsync();
}

The query is really simple, I execute a simple HttpWebRequest against an URL that should be �always� available, for example your corporate website, http://www.microsoft.com, or http://www.google.com. At the end of the day this is the only way to actually know if you do or do not have an available internet connection.

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        // Create an HTTP Web request

        // to an Uri that's always available.

        HttpWebRequest request = (HttpWebRequest) 
           HttpWebRequest.Create(this._alwaysAvailableUrl);

        // Perform GET

        HttpWebResponse response = 
           (HttpWebResponse) request.GetResponse();
        if (HttpStatusCode.OK == response.StatusCode)
        {
            // HTTP = 200, close the request and return true

            response.Close();
            e.Result = true;
        }
        else
        {
            // Other status; return false

            e.Result = false;
        }
    }
    catch (WebException)
    {
        // Deffinitely offline

        e.Result = false;
    }
}

After the BackgroundWorker object has completed its work (defined in the DoWork event), it calls the RunWorkerCompleted event, which also defines a custom event handler that declares the RunWorkerCompletedEventArgs class. With this class, we will manage the way in which the ToolStripStatusLabel will render.

private void BackgroundWorker_RunWorkerCompleted(object 
                   sender, RunWorkerCompletedEventArgs e)
{
    if (null != e.Error)
    {
        // Throw the error to the User Interface...

        // This shouldn't really get to happen.

        Trace.TraceError(e.Error.Message);
        throw e.Error;
    }
    else
    {
        if ((bool) e.Result) // Online

        {
            this.Image = Properties.Resources.Online;
            this.Text = Properties.Resources.MainFormConnectionStatusOnline;
        }
        else // Offline

        {
            this.Image = Properties.Resources.Offline;
            this.Text = Properties.Resources.MainFormConnectionStatusOffline;
        }

        // Redraw

        this.Invalidate();
    }

    // Re-enable and restart timer...

    this.Enabled = true;
    this._updateTimer.Enabled = true;
}

Conclusion

.NET Framework 2.0 makes really easy using background threads, giving your UI a smooth and useful experience. Now, if you are using the April CTP of Visual Studio .NET 2005, I strongly recommend that you manually assign your delegate for the DoWork event, since there is a bug in VS.NET that when it tries to re-write the comment of not using UI code from the separate thread it can replace your actual code.

If you need an Internet connection for using a Web Service you may also want to consider using adding a GetVersion Web Method into your Web Service and trying to access this service since after all there is no point of having an available connection if your web server is down.

History

  • Demo version - 1.0.0.0 - attached to this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here