Passing data from socketcommunication to User Interface - vb.net

In my current project I'm sending and receiving textmessages to/from a serversocket/clientsocket (TCP), much like a chat (My project is written in VB.NET). This works as long as I'm converting the bytes sent into strings and presenting them in a msgbox().
This code handles that part:
Try
client = ar.AsyncState
client.EndReceive(ar)
client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
Try
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
MsgBox(message)
Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
Catch ex As Exception
MsgBox("Error writing received message")
End Try
Catch ex As Exception
MsgBox("Error receiving message from server")
End Try
So far so good. However when I try to change "MsgBox(message)" into label1.text = message I get the error: "Error writing received message". My questions, then, is why this happens and what can I do to correct it so that I can have my sockets receiving information that can be added to textboxes and other things in the UI?
Thanks in advance for any help that you can provide

Use a delegate and BeginInvoke() to properly marshal the call to the main UI thread:
Private Sub OnRecieve(ar As IAsyncResult)
Try
client = ar.AsyncState
client.EndReceive(ar)
Try
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
NewMessage(message)
Catch ex As Exception
MsgBox("Error writing received message")
Finally
Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
End Try
client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
Catch ex As Exception
MsgBox("Error receiving message from server")
End Try
End Sub
Private Delegate Sub MessageDelegate(ByVal msg As String)
Private Sub NewMessage(ByVal msg As String)
If Me.InvokeRequired Then
Me.BeginInvoke(New MessageDelegate(AddressOf NewMessage), New Object() {msg})
Else
Label1.Text = msg
End If
End Sub

Related

Write exception in text file application path

I would like to catch exceptions to my application startup path in a file called "log_errors" and new exceptions on a new line, instead of messagebox.show:
Try
Dim t As Thread = New Thread(New ThreadStart(AddressOf MySub))
_runningThreads.Add(t)
t.Start()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Answering your specific question, for a very basic logging feature:
Create a "logging" Sub and pass the message to it:
Public Sub LogToFile(ByVal strMessage as String)
' Will create a log_errors.txt file if it doesn't already exist; otherwise, appends to it.
File.AppendAllText(Application.StartupPath & "\log_errors.txt", strMessage)
End Sub
Then in your Catch ex As Exception, instead of:
MessageBox.Show(ex.Message)
do
LogToFile(ex.Message)

npgsql connection wait with ssl

I setup a listener for notification from postresql through npgsql in vb.net. The sub just opens a new ssl connection and starts a new thread with a loop waiting for notification. Here below is the code
Public Sub StartListening()
If mConnString Is Nothing Then
Main_Form.WriteMessage("Not connected")
End If
Try
connection = New NpgsqlConnection(mConnString) With {
.ProvideClientCertificatesCallback = New ProvideClientCertificatesCallback(AddressOf MyProvideClientCertificates)
}
connection.Open()
If connection.State = ConnectionState.Open Then
Using command = New NpgsqlCommand("listen my_notification", connection)
command.ExecuteNonQuery()
End Using
End If
AddHandler connection.Notification, New NotificationEventHandler(AddressOf OnNotification)
Dim thread As New Thread(
Sub()
While True
connection.Wait()
End While
End Sub
)
thread.Start()
Catch ex As Exception
Main_Form.WriteMessage("Error:" + ex.Message)
End Try
End Sub
Private Sub MyProvideClientCertificates(ByVal clienteCertis As X509CertificateCollection)
Dim cert As X509Certificate2 = New X509Certificate2("mycertificate.pfx")
clienteCertis.Add(cert)
End Sub
Everything was working fine until I introduced SSL connection: it fails on connection.Wait() saying
Wait() with timeout isn't supported when SSL is used, see
https://github.com/npgsql/npgsql/issues/1501
Since actually I don't need a timeout I tried setting timeout=0 and commandtimeout=0 in connection string but error still remains and this is what I see in error stacktrace
in Npgsql.NpgsqlConnector.Wait(Int32 timeout)
in Npgsql.NpgsqlConnection.Wait(Int32 timeout)
in Npgsql.NpgsqlConnection.Wait()
Could anyone help?
I found a solution. I write here just in case some else has the same problem.
I changed Wait() with WaitAsync().
To avoid continuous looping also added Await and declare the sub as Async.
Below is the code
....
Dim thread As New Thread(
Async Sub()
While True
Await connection.WaitAsync()
End While
End Sub
)
thread.Start()
....

Throwing exception from sub to async call

This is a windows forms application in which I have a particular form. On this form I display the progress of some processing that is supposed to happen in the background asynchronously. All of it works great, except for when I try to handle exceptions that are caught within the background processing....
This is the sub in my form's code that calls the Async function, which is in a module containing all the background processing code:
Public Async Sub BasicProcessing()
Try
Dim processTarget As Action(Of Integer)
processTarget = AddressOf UpdatePulseProcessing
myProgress = New Progress(Of Integer)(processTarget)
myCount.Vehicles = Await ProcessmyCountFile(myCount, myProgress)
If OperationCanceledByUser = True Then
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(Me, "Unable to update count." _
& Environment.NewLine & ex.Message, _
"Error updating count", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
End Sub
This is the async function that it calls, which is in a separate module:
Public Function ProcessmyCountFile(CountToProcess As Count, ByVal ProgressObject As IProgress(Of Integer)) As Task(Of List(Of Vehicle))
myProgressObject = ProgressObject
basicToken = New CancellationTokenSource
Try
Return CType(Task(Of List(Of Vehicle)).Run(Function()
If basicToken.IsCancellationRequested Then
Return Nothing
Exit Function
End If
myCountFile = CountToProcess
MyVehicles = New List(Of Vehicle)
'All that is important in here to note is a call to a regular sub within this module
CreateVehicles()
Return MyVehicles
End Function, basicToken.Token), Global.System.Threading.Tasks.Task(Of List(Of Global.STARneXt.Vehicle)))
Catch ex As Exception
Throw New Exception(ex.Message)
Return Nothing
End Try
End Function
Public Sub StopProcess()
If Not basicToken Is Nothing Then
basicToken.Cancel() ' We tell our token to cancel
End If
End Sub
This is the regular sub called by the Async function:
Private Sub CreateVehicles()
Try
'In here are calls to other regular subs within the same module, let's just call them A and B
Catch ex As Exception
StopProcess()
Throw New Exception("Error creating vehicles at pulse " & pulsePointer & ". " & ex.Message)
End Try
End Sub
When I run this code with data that I know ends up generating an error in sub B, the error does propagate up, as far as up to the method that is directly called by the async function....
So when running in VS, it will stop at "Throw New Exception("Error creating vehicles at pulse " & pulsePointer & ". " & ex.Message)", with the Message containing the message thrown by sub B.
This is what the debugger says on that line:
An exception of type 'System.Exception' occurred in MyProject.exe but
was not handled in user code. Additional information: Error creating
vehicles at pulse....[error message propagated up as thrown by called
subs]. Arithmetic operation resulted in an overflow.
Then strangely enough, within the debugger if I hit "Step Into", it does then return to the sub in my form that called the Async function, which shows the message box on the GUI.
So how do I get this to automatically return back up to the original form code to show the message box? Why does it stop where it stops without continuing to propagate?
FYI, I did find this question, but it ultimately did not help.
#StephenCleary was right - I created a new install for my project as it is, and in the installed version I do get the message box with the expected error message.
Strange behavior on the part of the debugger, and a bit discouraging, but none-the-less I am glad that my code as laid out in my question does actually work.

server busy error message vb.net

I get this error. I can not catch it where it comes from. All methods made with try catch but still I get this error from time to time. I used code:
Private Sub add2ComboBox_called(ByVal text As String)
Try
If Me.InvokeRequired Then
Dim args() As String = {text}
Me.Invoke(New Action(Of String)(AddressOf add2ComboBox_called), args)
Return
End If
ComboBox_called.Items.Add(text)
Catch ex As Exception
log_it(ex.StackTrace)
End Try
End Sub
and also this one:
Public Sub clear_do_not_open()
Dim FILENAME As String = path & "\DO_NOT.OPEN"
Dim index As Integer
Try
Using fs As New IO.FileStream(FILENAME, IO.FileMode.Truncate, IO.FileAccess.Write, IO.FileShare.ReadWrite), _
tl As New TextWriterTraceListener(fs)
index = Trace.Listeners.Add(tl)
Trace.Write("")
Trace.Listeners(index).Flush()
Trace.Flush()
End Using
Trace.Listeners.RemoveAt(index)
Catch ex As Exception
log_it(ex.StackTrace)
End Try
End Sub
How do I make this to press Retry by default if it appears? Wait for a second and press Retry again? If not like this then how do I know that this message pops up? If catch the moment it shows up I could then just restart the program or send an email to myselt so I could come to PC where program runs and I could handle it. Now message pops up and program stops while its on.

Unhandled Exception error line and source function

I am using VS2012 VB.net.
Can I please have some help in creating some code to calculate the error line of an exception and also the function that the exception occurred in.
Here is my current code:
Partial Friend Class MyApplication
Public exceptionListOfExceptionsToNotPauseOn As New List(Of ApplicationServices.UnhandledExceptionEventArgs)
Private Sub MyApplication_UnhandledException(sender As Object, e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim msgboxResult As MsgBoxResult
Dim booleanExceptionFoundInList As Boolean = False
'Dim trace As System.Diagnostics.StackTrace = New System.Diagnostics.StackTrace(ex, True)
'Dim exceptionLineNumber = trace.GetFrame(0).GetFileLineNumber()
For x = 0 To exceptionListOfExceptionsToNotPauseOn.Count - 1
If exceptionListOfExceptionsToNotPauseOn(x).Exception.Message = e.Exception.Message Then
booleanExceptionFoundInList = True
End If
Next
If Not booleanExceptionFoundInList Then
msgboxResult = MessageBox.Show("An exception error has occured." & vbCrLf & "Error message: " & e.Exception.Message & vbCrLf & "Do you wish to pause on this exception again?", "Exception", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If msgboxResult = Microsoft.VisualBasic.MsgBoxResult.No Then
exceptionListOfExceptionsToNotPauseOn.Add(e)
End If
End If
e.ExitApplication = False
End Sub
End Class
UPDATE
The code for the trace code uses an Exception data type where as the code for handling unHandled exceptions above has a parameter of "e As ApplicationServices.UnhandledExceptionEventArgs". Can I use the trace code with this data type? Do I need to cast it to an exception type? Or is it not possible?
I am not mastering in Vb.Net but previously i used below code, may be it can help you
[ex.StackTrace()]
Try
'Your Code goes here
Catch ex As Exception
MsgBox(ex.StackTrace())
End Try
Here are a couple of tips. First is to use PostSharp its a AOP kit that will let you trace all methods entry and exit using Attributes. This would direct you to the function straight away.
Another trick. Subscribing to the ThreadExceptionEventHandler actually does cause the debugger to break on unhandled exceptions! Hence temporarily comment out your MyApplication_UnhandledException and add a ThreadExceptionEventHandler
<STAThread> _
Public Shared Sub Main(args As String())
Try
'your program entry point
Application.ThreadException += New ThreadExceptionEventHandler(Application_ThreadException)
'manage also these exceptions
Catch ex As Exception
End Try
End Sub
Private Sub Application_ThreadException(sender As Object, e As ThreadExceptionEventArgs)
ProcessException(e.Exception)
End Sub
Another trick is is not to run under the debugger. The debugger is masking the exception for some reason. If you run your app normally (Ctrl+F5), you'll get the usual Unhandled exception has occurred in your application... Continue/Quit? dialog.
The code for handling unHandled exceptions above has a parameter of "e
As ApplicationServices.UnhandledExceptionEventArgs". Can I use the
trace code with this data type?
No.
You cannot easily use your trace code datatype with the UnhandledExceptionEventArgs. One idea might be to make a class that inherits from UnhandledExceptionEventArgs but I don't know how you'd call the MyApplication_UnhandledException function with the special type, because that function is invoked when an Exception is Unhandled.