I have function that check internet connection before my application continue working, using ping sometimes my connection are limited and that make my program crash. i want to close my application when it happen. can you help me ?
this is my sample code
If My.Computer.Network.IsAvailable Then
Try
Dim pingreq As Ping = New Ping()
Dim pinging As PingReply = pingreq.Send("www.google.com")
Dim latency As Integer = pinging.RoundtripTime
Dim status = pinging.ToString
Catch err As PingException
write_log(Date.Now.ToString("dd:MM:yyyy - HH:mm:ss") & "||" & "Connection Error" & err.ToString() & err.Message)
If Not err Is Nothing Then
Timer1.Stop()
Me.Close()
constat = 0
End If
End Try
Else
Timer1.Stop()
Me.Close()
End If
Related
I made a Winforms application to work with 4 different machines by connecting with them via TCP/IP. Somehow, the connection sometimes seems disconnected and reconnecting after a short while. May I know is it I used too much TCP client and caused them congested??
Below is the function/method to connect those machine...with 4 of them different function names to connect each of the machine, but the code is more or less the same:
Public Async Sub connect_Machine_Ethernet(ByVal mainForm As Form1)
If Machine_COMPort.IsOpen Then
Machine_COMPort.Close()
End If
If (IsNothing(Machine_client)) Then
'do nothing, since obj is not created
Else
Try
Machine_client.GetStream.Close()
Machine_client.Close()
Catch exp As Exception
End Try
End If
Try
Machine_client = New TcpClient
Machine_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, True)
Dim result = Machine_client.BeginConnect(Machine_ModuleIP_txt.Text, CInt(Machine_ModulePort_txt.Text), Nothing, Nothing)
result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1))
Machine_client.GetStream.BeginRead(Machine_ethernet_buffer, 0, Machine_ethernet_buffer.Length, AddressOf Machine_TCP_read, Machine_ethernet_buffer)
DisplayMsg("Machine Ethernet connection established")
manual_connection_LED.StateIndex = 3
Machine_client_isConnected = True
Machine_TCP_Reconnect_btn.Invoke(Sub() Machine_TCP_Reconnect_btn.Visible = False)
Catch ex As Exception
DisplayMsg("Error : Unable to connect to the Machine Ethernet connection")
manual_connection_LED.StateIndex = 0
Machine_client_isConnected = False
If (IsNothing(Machine_client)) Then
'do nothing, since obj is not created
Else
Try
Machine_client.GetStream.Close()
Machine_client.Close()
Catch exp As Exception
End Try
End If
End Try
End Sub
'Read Machine TCP message
Sub Machine_TCP_read(ByVal ar As IAsyncResult)
Try
Dim buffer() As Byte = ar.AsyncState
Dim bytesRead As Integer = Machine_client.GetStream.EndRead(ar)
Dim Message As String = System.Text.Encoding.ASCII.GetString(Machine_ethernet_buffer, 0, bytesRead)
If Message = "" Then
'----check connection
If Machine_client.Connected Then
Machine_client.Close()
connect_Machine_Ethernet(Me)
End If
Else
DisplayMsg("Input Received from machine : " & Message)
Process_machine_Feedback(Message) 'perform any data logic from the message
Machine_client.GetStream.BeginRead(Machine_ethernet_buffer, 0, Machine_ethernet_buffer.Length, AddressOf Machine_TCP_read, Machine_ethernet_buffer)
End If
Catch ex As Exception
DisplaySystemMsg(ex.Message)
DisplayMsg("Marking machine Ethernet disconnected from the server")
manual_connection_LED.StateIndex = 0
Machine_client_isConnected = False
Exit Sub
End Try
End Sub
'Send message to TCP
Public Sub Machine_TCP_send(ByVal str As String)
Try
sWriter = New StreamWriter(Machine_client.GetStream)
sWriter.WriteLine(Chr(2) & str & Chr(3)) 'add prefix suffix
sWriter.Flush()
DisplayMsg("Message send to the machine via TCP: " & str)
Catch ex As Exception
DisplayMsg("Error : Message failed to send to themachine!")
End Try
End Sub
I have a script task which downloads a file using a HTTP connection object. This script task is part of a package which is called by another package. Sometimes the connection cannot be established. In these instances I want to retry the connection a number of times before finally raising an error if the connection attempts fail.
I tried to implement this. It appeared to work and the task does not fail. However an OnError event is still propagated every time an exception happens in the script task even though the script task doesn't fail. The fail occurs once control is passed from the child package back to the parent package.
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
While (True)
Try
Dim nativeObject As Object = Dts.Connections("HTTP Connection Manager").AcquireConnection(Nothing)
'Create a new HTTP client connection
Dim connection As New HttpClientConnection(nativeObject)
Dim filename As String = Dts.Variables("Working_File").Value
connection.DownloadFile(filename, True)
Dts.TaskResult = ScriptResults.Success
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Thread.Sleep(30000)
Else
MsgBox(ex.Message)
Dts.TaskResult = ScriptResults.Failure
Throw
End If
End Try
End While
End Sub
I am hoping to get a solution where the OnError event is not called unless the connection attempts fails a certain number of times.
Try writing the same code an Fire a Warning on first 4 trial and on the 5th trial fire an error, i am not sure if it will works:
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
While (True)
Try
Dim nativeObject As Object = Dts.Connections("HTTP Connection Manager").AcquireConnection(Nothing)
'Create a new HTTP client connection
Dim connection As New HttpClientConnection(nativeObject)
Dim filename As String = Dts.Variables("Working_File").Value
connection.DownloadFile(filename, True)
Dts.TaskResult = ScriptResults.Success
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Dts.Events.FireWarning(0, "Error ignored", _
"Retrying in 30 seconds", String.Empty, 0)
Thread.Sleep(30000)
Else
Dts.Events.FireError(-1, "", "Error message: " & ex2.ToString(), "", 0)
Dts.TaskResult = ScriptResults.Failure
End If
End Try
End While
End Sub
Reference
How to suppress OnError event for a specific error in a Script task (SSIS 2005)
You'll want to use a label, outside the try, and a GoTo within your catch
Public Sub Main()
Dim tryTimes As Integer = 0
Dim maxTimes As Integer = 4
RunCode: 'Label here
While (True)
Try
'your code here
Exit While
Catch ex As Exception
If (tryTimes < maxTimes) Then
tryTimes = tryTimes + 1
Thread.Sleep(30000)
GoTo RunCode 'after we catch the exception and eval tryTimes go back and retry
Else
'MsgBox(ex.Message)
Dts.Events.FireError(-1, "", "Error message: " & ex.ToString(), "", 0)
Dts.TaskResult = ScriptResults.Failure
'Throw
End If
End Try
End While
End Sub
I am writing software for a POS terminal. This terminal has a printer that is attached to a cash drawer. I need to send a code to the printer, and listen for what is returned to determine whether or not the cash drawer is open. Using MSComm, I had logic that worked in VB6, so I know the actual Hex code I am sending is correct.
This code always returns "Error: Serial Port read timed out". I do not know what I am doing wrong with the read portion. Please advise, how do I listen for what the port is sending back as a response?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim x As Integer = 0
Dim com3 As IO.Ports.SerialPort = Nothing
logfile.WriteLine("STARTCASHDRAWERSTATUSCHECK")
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.WriteLine(ChrW(&H1B) & ChrW(&H75) & ChrW(&H0))
com3.BaudRate = SetPortBaudRate(9600)
com3.Parity = IO.Ports.Parity.None
com3.DataBits = SetPortDataBits(8)
com3.StopBits = SetPortStopBits(1)
com3.Handshake = IO.Ports.Handshake.RequestToSend
com3.ReadTimeout = 10000
Do
x = x + 1
Dim Incoming As String = com3.ReadLine()
logfile.WriteLine(x & "incoming" & Incoming & "x")
If Incoming Is Nothing Then
logfile.WriteLine("Button2resultEXITDO" & x)
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
If x > 10 Then
Exit Do
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
logfile.WriteLine("Button2result:" & returnStr)
End Sub
Thanks in advance!
Guys I am having a weird problem with my vb.net application after the computer goes into hibernate mode and resumes. Before it goes into sleep mode I close all my serial ports and set it to nothing...
Private Sub SystemEvents_PowerModeChanged(ByVal sender As Object, ByVal e As PowerModeChangedEventArgs)
oEventLog.WriteEntry("Power change detected: " & e.Mode.ToString)
txtStatus.AppendText("Power change detected: " & e.Mode.ToString & vbCrLf)
If e.Mode <> PowerModes.Resume Then
Try
If Input IsNot Nothing Then
Input.Dispose()
Input.Close()
Input = Nothing
End If
If Output IsNot Nothing Then
Output.Dispose()
Output.Close()
Output = Nothing
End If
Catch
txtStatus.AppendText(Err.Description)
End Try
Else
initilizeSerialPorts()
End If
End Sub
When the computer resumes I initialize my serial ports again. The problem is when I try to open them again it says they are already in use. So I loaded up process explorer to see what has it open and it's still my application! So it seems closing them and setting them to nothing does nothing. If I close my application and re-run it everything works just fine.
Private Function initilizeSerialPorts() As Boolean
If Input IsNot Nothing Then
Input.Dispose()
Input.Close()
Input = Nothing
End If
If Output IsNot Nothing Then
Output.Dispose()
Output.Close()
Output = Nothing
End If
Input = New SerialPort(cmboInput.SelectedItem.ToString)
Output = New SerialPort(cmboOutput.SelectedItem.ToString, Input.BaudRate, Input.Parity, Input.DataBits, Input.StopBits)
Me.Refresh()
****MSGBOX HERE MAKES IT WORK?!!****
Try
If Not Input.IsOpen Then
Input.Open()
Else
MsgBox("Unable to open the serial port " & Input.PortName)
Return False
End If
Catch
MsgBox("Unable to initalize serial port " & Input.PortName & vbCrLf & "Error: " & Err.Number.ToString & " " & Err.Description)
End Try
Try
If Not Output.IsOpen Then
Output.Open()
Else
MsgBox("Unable to open the serial port " & Output.PortName)
Return False
End If
Catch
MsgBox("Unable to initalize serial port " & Output.PortName & vbCrLf & "Error: " & Err.Number.ToString & " " & Err.Description)
End Try
Return True
End Function
Ok here is the kicker...if I put a message box before I open my port again it works? No message box and I get a failed to open port message it's in use. Any ideas why this might be happening?
Thanks in advance
I took this code from a website since VS 2010 doesn't support the timeout for the TCP connections:
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
Dim wh As System.Threading.WaitHandle = ar.AsyncWaitHandle
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function
And it works fine, but everytime, it gives me this on the debug output:
"A first chance exception of type 'System.TimeoutException' occurred in"
Even if I'm catching all the exceptions. Is there a way to get rid of this exception message as it is handled?
I've tried this:
Dim connectDone As New System.Threading.AutoResetEvent(False)
TCPClient.BeginConnect(IPAddress, TCPPort, New AsyncCallback(Sub(ar As IAsyncResult)
TCPClient.EndConnect(ar)
connectDone.Set()
End Sub), TCPClient)
'client.BeginConnect("127.0.0.1", 80, new AsyncCallback(delegate( IAsyncResult ar ) { client.EndConnect( ar ); connectDone.Set(); }), client);
If Not connectDone.WaitOne(2000) Then
Debug.WriteLine("TIMEOUT")
Return False
End If
Return True
But it gives me InvalidOperationException on the beginconnect line:
BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult
Dim wh As System.Threading.WaitHandle
Try
ar = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
wh = ar.AsyncWaitHandle
Cath ex as Exception
'Code to catch exception
End Try
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function