Detecting wirless network status change in .NET

987 views Asked by At

I have developed winform application using VB.NET. The application is deployed in the machine which is connected to wireless network. The machine is in the car(moving object).

The application has DataGridView loaded with the data get from MSSQL Server(in Remote machine). The data is refreshed for every 5 seconds.

I have used the NetworkAvailabilityChanged event to detect the network status. If the Network is available, then I retrieve the data from the table.

Code:

AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf NetworkStateChangeHandler

Public Sub NetworkStateChangeHandler(ByVal sender As Object, 
                                     ByVal e As NetworkAvailabilityEventArgs)
        If e.IsAvailable = True Then           
            g_bNetworkAlive = True            
        Else           
            g_bNetworkAlive = False
        End If
End Sub

private Sub GetData()
    If g_bNetworkAlive = True
        'code to get the data from table
    End If
End Sub

Issue:

If the car movers out of the out of the network, the NetworkAvailabilityChanged event is not fired. so it throws the following error for every 5 seconds and application gets crashed.

A network-related or instance-specific error occurred while establishing 
a connection to SQL Server. The server was not found or was not accessible.

Temporary fix: I have made Ping request to the SQL server machine for every 5 seconds to detect the network status. It affects the application's performance.

Note: If I manually switch off the Wifi, the NetworkAvailabilityChanged event is fired. The issue is only when the car moves out of the network.

Is there any some other feasible solution to detect the wireless network status?

4

There are 4 answers

0
Colin Raaijmakers On

You also can check if you have an internet connection by using WebRequest like this:

Private Sub GetData()

    If HasInternet AndAlso g_bNetworkAlive Then
        'code to get the data from table
    End If

End Sub

Public Shared Function HasInternet As Boolean

    Return Not (HttpGet("http://www.google.com/") = "Error")

End Function

Public Shared Function HttpGet(url As String) As String
    Dim request As WebRequest = WebRequest.Create(url)
    request.Method = "GET"
    Try
        Dim response As WebResponse = request.GetResponse()
        Dim dataStream As Stream = response.GetResponseStream()
        Dim reader As New StreamReader(dataStream)
        Dim responseFromServer As String = reader.ReadToEnd()
        reader.Close()
        dataStream.Close()
        response.Close()
        Return responseFromServer
    Catch ex As Exception
        Return "Error"
    End Try
End Function

And you can check the sql connection by using the following function:

Private Function IsDatabaseConnected() As Boolean
    Try
        Using sqlConn As New SqlConnection("YourConnectionString")
                sqlConn.Open()
                Return (sqlConn.State = ConnectionState.Open)
        End Using
    Catch e1 As SqlException
        Return False
    Catch e2 As Exception
        Return False
    End Try
End Function
0
Sarvesh Mishra On

Change your code as

Private Sub GetData()
    If My.Computer.Network.IsAvailable AndAlso g_bNetworkAlive
        ' code to get the data from table

    End If
End Sub
0
Mladen Oršolić On

I would simply use try..catch, so if you get exception, you can know, based on its id, why the code failed, and decide what to do next, and finally you can execute some more code regardless of data being retrieved or not

Private Sub GetData()
    Try 
        'code to get the data from table

    Catch ex As Exception
        ' Show the exception's message.
        MessageBox.Show(ex.Message)

        ' Show the stack trace, which is a list of methods 
        ' that are currently executing.
        MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
    Finally 
        ' This line executes whether or not the exception occurs.
        MessageBox.Show("in Finally block")
    End Try
End Sub
0
ThePravinDeshmukh On

Indeed there is.

Why send http request to some dummy website when you can check if you are connected to wifi or not locally. Use ManagedWifi APIs, This will eliminate the slowdown you are facing.

//Create object at the beginning of your application 
WlanClient wlanClient = new WlanClient();


//You this code to check wifi availability wherever you need
foreach (WlanInterface _interface in wlanClient.Interfaces)
{
    If (_interface.CurrentConnection.wlanAssociationAttributes.dot11Ssid.SSID!=null)
   {
      // You are connected to wifi
   }
}

EDIT: In case you you are not finding dll, direct link. Just reference the Dll and Voila! you are done.