Blue Theme Orange Theme Green Theme Red Theme
 
ASP.Net 4 Hosting is here
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Mobile .NET » Monitor Internet Connection State

Monitor Internet Connection State


This article describes an easy approach to building two controls used to monitor the status of an internet connection and provide the user with some indication of that status. Within the attached project, there are two controls, one shows the user what the connection type is and whether or not the machine is connected or offline, the other one is used to show some indication of the quality of the connection in terms of whether or not the connection is good, intermittent, or offline.

Author Rank:
Total page views :  30834
Total downloads :  1213
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConnectStatusCode.zip
 
Become a Sponsor

Introduction: 

This article describes an easy approach to building two controls used to monitor the status of an internet connection and provide the user with some indication of that status.  Within the attached project, there are two controls, one shows the user what the connection type is and whether or not the machine is connected or offline, the other one is used to show some indication of the quality of the connection in terms of whether or not the connection is good, intermittent, or offline.

The purpose of the controls was to provide a mobile user of a smart client application some status information regarding the internet connection; in this instance, there were many forms within the application and I wanted a simple control to drop on each form to provide that status.

Figure 1:  Both Connection Status Controls In Use

Getting Started:

In order to get started, unzip the attachment and load the solution into Visual Studio 2005.  Examine the solution explorer and note the files contained each of the two projects:

Figure 2:  The Solution Explorer Showing the Project Files

The "ConnectStatus" project contains the two controls used to display internet connection status to the user;  the "ConnectQualityView" displays an indication of the quality of the status based upon how well that connection is maintained over time.  The "ConnectStateView" control shows the type of connection and provides a graphic indicating whether or not the connection is active or offline.

The second project, "TestAppForInetConnect" contains a simple form used to display both controls at the same time.  This second project is not necessary as with Visual Studio 2005, the user may display the controls in the control test container.  There is no code associated with this second project, the main form has one of each type of control loaded into it and it serves only as a container for those controls.

The Code:  ConnectStateView.

The control is quite simple; the visual elements include only a group box and a single label.  Aside from the visual elements, there is a single timer which is used to check the status of the internet connection repeatedly and there is a single image list which is used to hold a couple of images used to place an icon adjacent to the label control.

If you care to open the class, you will note that there are no imports.  The control's code is pretty easy to read and is as follows:

Public Class ConnectStateView

 

#Region "Declarations"

 

    Private ConnectionStateString As String

 

    Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef _

    lpSFlags As Int32, ByVal dwReserved As Int32) As Boolean

 

    Public Enum InetConnState

        modem = &H1

        lan = &H2

        proxy = &H4

        ras = &H10

        offline = &H20

        configured = &H40

    End Enum

 

#End Region 

 

#Region "Control Methods"

 

    Private Sub ConnectStateView_Load(ByVal sender As Object, ByVal e As

    System.EventArgs) Handles Me.Load

 

        Timer1.Enabled = True

 

    End Sub 

 

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As

    System.EventArgs) Handles Timer1.Tick

 

        Dim blnState As Boolean

        blnState = CheckInetConnection()

        lblConnectStatus.Text = "          Connection Type:  " &

        ConnectionStateString

 

    End Sub 

 

    Function CheckInetConnection() As Boolean

 

        Dim lngFlags As Long

 

        If InternetGetConnectedState(lngFlags, 0) Then

            ' True

            If lngFlags And InetConnState.lan Then

                ConnectionStateString = "LAN."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.modem Then

                ConnectionStateString = "Modem."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.configured Then

                ConnectionStateString = "Configured."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.proxy Then

                ConnectionStateString = "Proxy"

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.ras Then

                ConnectionStateString = "RAS."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.offline Then

                ConnectionStateString = "Offline."

                Me.lblConnectStatus.Image = ImageList1.Images(2)

            End If

        Else

            ' False

            ConnectionStateString = "Not Connected."

            lblConnectStatus.Image = ImageList1.Images(3)

        End If

 

    End Function 

 

#End Region 

End Class

In the beginning of the code, note that there is a region called "Declarations" defined and within that region there are three declarations.  The first declaration defines a string value that is used to keep track of the connection type used by the client's machine. 

The next declaration is the most important part of the code, it is the code that exposes a function from the wininet.dll to the application; that function is called "InternetGetConnectedState".  This function accepts two arguments which in this case are two 32 bit integers; these could be longs but integers work fine here; the function returns a boolean but also could be set up to return a long integer as well.  In use, empty values of the specified data types are passed to this function and the function then sets their values.  To use the control, these set values are evaluated in code to determine the type and status of the current internet connection.

The last declaration is of an enumeration used to contain representatives of each connection type exposed by the previous function.  The flags identified in the enumeration are representative of each connection type that may be returned from making a call to the wininet.dll function declared previously.

After the declarations region is closed, a new region entitled "Control Methods" is defined.  The first item in this section is the control load event handler; in this section, the timer is enabled and process of polling the internet connection of the timer's interval is initialized.

After the load event code, the handler for the timer is defined.  The handler is used to evoke the "InternetGetConnectedState" function through a call to the "CheckInetConnect" method.  This code calls the next method in line, "CheckInetConnection" which sets the text contained in the label based upon the value of the "ConnectionStateString" which is in turn updated by the "CheckInetConnection" method.

The "CheckInetConnection" method  calls the wininet.dll method "InternetGetConnectedState" which in turn sets the flag and connection type arguments used to determine the status of the internet connection.  At the beginning of the evaluation, the first check determines whether or not the machine is connected; if the machine is connected, each pair is evaluated to determine the type of connection and to set the label text and icon to reflect the status returned by the method.  If the connection is not active, the else block will execute and the label text and icon will update to show that the system is not connected (see bottom control in figure 3).

Figure 3:  Connection Status Controls with Failed Internet Connection

That is all there is to the code for this first control.  The next section will discuss the content of the second control as used to gauge the quality of an internet connection.

The Code:  ConnectQualityView.

This control is used to give a rough estimate as the quality of the internet connection as a function of the durability and persistence of the connection over a brief time span (3 seconds).  The code contained within this class if nearly identical to the previous class; it is as follows:

Public Class ConnectQualityView 

 

#Region "Declarations"

 

    Dim ConnectionQualityString As String = "Off"

 

    Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef _

    lpSFlags As Int32, ByVal dwReserved As Int32) As Boolean

 

    Public Enum InetConnState

        modem = &H1

        lan = &H2

        proxy = &H4

        ras = &H10

        offline = &H20

        configured = &H40

    End Enum

 

#End Region 

 

#Region "Control Methods" 

 

    Private Sub ConnectQualityView_Load(ByVal sender As Object, ByVal e As

    System.EventArgs) Handles Me.Load

 

        Timer1.Enabled = True

        Me.DoubleBuffered = True

 

    End Sub 

 

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As

    System.EventArgs) Handles Timer1.Tick

 

        lblConnectStatus.Refresh()

 

        Dim blnState As Boolean

        blnState = CheckInetConnection()

 

    End Sub 

 

    Function CheckInetConnection() As Boolean

 

        Dim lngFlags As Long

 

        If InternetGetConnectedState(lngFlags, 0) Then

            ' True

            If lngFlags And InetConnState.lan Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

                Me.Refresh()

            ElseIf lngFlags And InetConnState.modem Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.configured Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.proxy Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.ras Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.offline Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            End If

        Else

            ' False

            Select Case ConnectionQualityString

                Case "Good"

                    lblConnectStatus.ForeColor = Color.DarkOrange

                    lblConnectStatus.Text = "Connection Quality:  Intermittent"

                    ConnectionQualityString = "Intermittent"

                Case "Intermittent"

                    lblConnectStatus.ForeColor = Color.Red

                    lblConnectStatus.Text = "Connection Quality:  Off"

                    ConnectionQualityString = "Off"

                Case "Off"

                    lblConnectStatus.ForeColor = Color.Red

                    lblConnectStatus.Text = "Connection Quality:  Off"

                    ConnectionQualityString = "Off"

            End Select

        End If

 

    End Function 

 

#End Region 

End Class

In reviewing this code in contrast to the previous class described, you will see the only real difference is that the status is used to set the text and fore color of the label control used to display the status, and you will notice that the previous status message (gathered 1.5 seconds earlier) is evaluated to determine how to the display the status of the connection.  This operates under a simple notion of promoting the status of the connection for remaining active over time.  The control initializes with the connection quality string value set to "Off", when the connection state is evaluated, the initial connection state is noted and the code promotes the status to intermittent.  If the status remains active for an additional 1.5 seconds, it is promoted to "Good".    The idea here is that if the connection is dropping off and getting picked back up, the code will continually evaluate the current status against the previous status and promote or demote the status between the three available options of  Good, Intermittent, and Off.

Naturally you may alter the amount of time between status checks and in so doing, increase or decrease the amount of time necessary to promote or demote the status of the connection.

That is all there is to the second control.

Summary.

Whilst this example project demonstrates a couple of ways in which you can monitor and display status regarding a machine's internet connection, these approaches do not represent all of the ways that you may accomplish this task.  Still and all, this approach is a simple and easy way to display connection status information to your users.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDFâ„¢ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Hi... by Aamir On November 6, 2007
Cool article.... Anyway to block internet access?
Reply | Email | Delete | Modify | 
Re: Hi... by Scott On November 6, 2007
Sure.  The easiest way would be use a firewall; something like Comodo or Internet Access Controller 2007.  If you just wanted to block access when your program was running, you could block the browsers from launching.
Reply | Email | Delete | Modify | 
hoganscarpes by watches On July 11, 2010
In general Hogan are made from very flexible materials and have a rubber sole. When they first entered the market Hogan scarpe donna were quite simple but the growing popularity has increased competition and spurned a number of new designs. While other styles of hogan donna such as casual loafers or dress shoes tend to come in one generic mould, Hogan uomo are designed to support and contrast an athlete s foot.
Reply | Email | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 Â© 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.