I have the following code as part of a TCP/IP Server. The program works well but I noticed that a System.IO.IOException error is thrown on the Server as a Client disconnects. (I'm literally disconnecting the client.)
Private Sub ReadAllClient()
Try
RaiseEvent getMessage(New StreamReader(listClient.GetStream).ReadLine)
listClient.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf ReadAllClient), Nothing)
Catch ex As Exception
RaiseEvent clientLogout(Me)
End Try
End Sub
(EDIT: Error message details)
System.IO.IOException: 'Unable to read data from the transport
connection: An established connection was aborted by the software in
your host machine.'
This error isn't normally a part of VS 2017 and just threw it on to find the cause and it is this Try/Catch statement. (The Catch part is definitely working... but the error is being thrown.)
Should I be concerned that this exception is being thrown? Or is it safe enough to ignore?
Related
I am writing a VB.NET add-on for Solidworks, in which I first need to connect to an already running instance of Solidworks (similarly to how such connections are made to Excel). I am using Marshal.GetActiveObject method:
Sub ConnectToSolidworks()
Const PROG_ID As String = "SldWorks.Application"
Dim progType = System.Type.GetTypeFromProgID(PROG_ID)
If progType Is Nothing Then MSG("Cannot detect a valid Solidworks installation.") : End : Application.Exit()
'connect to Solidworks
Try
swApp = TryCast(System.Runtime.InteropServices.Marshal.GetActiveObject(PROG_ID), SolidWorks.Interop.sldworks.ISldWorks)
Catch ex As Exception
printException(System.Reflection.MethodBase.GetCurrentMethod().Name, ex)
End Try
'check if connected
If swApp Is Nothing Then
MSG("Unable to connect to Solidworks.")
End
Application.Exit()
End If
End Sub
Unfortunately, there is a problem. If Solidworks is launched as an Administrator, and my application is not, or vice versa, Marshal.GetActiveObject fails with HRESULT: 0x800401E3 exception.
However, I need my application to work without administrative access, and regardless of whenever Solidworks was launched as administrator.
The reason why I'm not using Interaction.CreateObject, Interaction.GetObject or System.Activator.CreateInstance, is because these methods will launch Solidworks on their own if it is not running already, which I want to avoid at all costs.
With that in mind, how can I get Marshal.GetActiveObject to work when the elevation levels mismatch, or is there yet some another way to get this done?
EDIT: I tried Interaction.GetObject again, and it also throws an exception if elevation levels mismatch ("Cannot create ActiveX component").
Attempting to deploy updates to a .dll using WebClient.DownloadFile. If the dll is loaded/locked by the program it cannot be overwritten, so i'm trying to use a Try... Catch statement (on the following exception) to curate the Process ID and .Dispose() of it.
System.Net.WebException: 'An exception occurred during a WebClient request.'
Inner Exception
IOException: The process cannot access the file 'xyz' because it is being used by another process.
This may or may not be the best methodology... below is my code. Any pointers much appreciated!
Try
Using WC As New WebClient
WC.DownloadFile("https://urlgoeshere.com/library.dll", strLiveDLL)
End Using
Catch ex1 As System.Net.WebException
Using P As Process = ex1.WhatGoesHere 'can get the process ID here??
If MsgBox("Cannot update because dll file is locked by " & P.ProcessName & vbCr &
"Press OK to dispose of this process and continue with update.",
MsgBoxStyle.OkCancel & MsgBoxStyle.Question,
"Update Interrupted") = MsgBoxResult.Ok Then
P.Dispose()
'continue with update
Else
MsgBox("Update Aborted.")
End If
End Using
Catch ex2 As IOException
'
Catch ex3 As Exception
'
End Try
If anyone else is interested, I never figured out how to get the process ID from the exception (I don't think it's possible) but I discovered that it may not be necessary...
What I'm doing instead is just renaming the DLL if it's locked (everything seems to still run as expected even after rename). After it's renamed, the updated DLL can be downloaded to the standard location for the live DLL.
I'm currently talking to another computer to see what events they have occurring. I have setup a Wql Event query like so below:
Console.WriteLine("Polling...")
Try
Dim query As New WqlEventQuery("SELECT * FROM Lnl_AccessEvent")
Dim accessEventWatcher = New ManagementEventWatcher("SELECT * FROM Lnl_AccessEvent")
accessEventWatcher.Start()
accessEventWatcher.WaitForNextEvent()
Console.WriteLine("AccessEvent Occured.")
Catch ex As Exception
Console.WriteLine(ex.Message + " " + ex.StackTrace)
End Try
On the ".Start()" line, I get an exception stating "Invalid class" and "ManagementException". I know the connection is working since before this instance I'm able to connect and get the basic info from the remote computer's WMI, like IP address. The only solutions I have found is that has to do with my target build being only x86, but now it's at AnyCPU and still has this issue.
What is causing this error?
Below is code for how you can upload a file using ftp. My question is what happens if there is an exception in the try, will the ftp connection automatically close in the catch? Is it better to use a "using"?
thank you
Try
'connect to ftp server
Dim ftp As New FTPConnection
ftp.ServerAddress = "ftp.example.com"
ftp.UserName = "example_user"
ftp.Password = "example_pass"
ftp.Connect()
ftp.TransferType = FTPTransferType.BINARY
'upload a file
ftp.UploadFile("s:\test.txt", "test.txt")
'close the connection
ftp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
When an exception happens (whatever it is) the control flow skips everything until it arrives to a Catch instruction.
So in this case if you have an exception in the UploadFile you will not close the connection.
If the FTPConnection class is IDisposable then your best option is to use the using keyword. Otherwise use the finally statament after the Catch as Grant said.
No, it won't close if an exception occurs before ftp.Close() has finished executing. You should use a Finally block to make sure that ftp is always closed, even if an exception occurs. This means you should define ftp at a higher scope level than within the try block, so that it is accessible within the finally block. You could technically call Close from within the catch block but that A) won't cover both/all circumstances and B) might not work anyway if code in the catch throws yet another exception.
Dim ftp As New FTPConnection
Try
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
ftp.Close()
End Try
I have a server I wrote using Asynchronous sockets. In the piece that accepts new connections I am getting a problem where some users are saying that some of the times they get this error on the server when the client tries to re-connect to the server:
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"
After this error occurs the server goes dead and no new clients can connect until I physically quit the server program and start it again. So what should I do when I get this error? I tried to essentially restart the server in my code by closing the socket (listener.Close()) and then calling the same code I used to create and bind to the socket in the beginning, but then I get an error saying that I can't bind to the same port again.
So, two questions. First off, what is the proper way to handle that error and prevent it from essentially killing my server? Next, what is the proper way to restart a server through my code? Just calling .close() on the listener and then starting it again doesn't work in this case.
Thanks
Here is the code that accepts the connection request
Private Sub connectionRequest(ByVal ar As IAsyncResult)
Try
Dim thisListener As Socket = CType(ar.AsyncState, Socket)
Dim handler As Socket = thisListener.EndAccept(ar)
Dim remoteEndPoint As IPEndPoint
remoteEndPoint = handler.RemoteEndPoint
thisListener.Listen(10)
thisListener.BeginAccept(New AsyncCallback(AddressOf connectionRequest), thisListener)
thisListener.NoDelay = True
thisListener.Ttl = 32
Dim state As New StateObject
state.workSocket = handler
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf dataArrival), state)
handler.NoDelay = True
Catch ex As Exception
End Try
End Sub
Could you show us the code that you have for accepting connections?
You shouldn't have to restart your server. You should just fix the bug in your accept code in your server.
Clients can and will experience this problem when a server isn't accepting connections quickly enough, and/or if the listen backlog queue is too short for the rate at which new connections are being established and at which the server is accepting them.