Try/Catch not catching execption - vb.net

I have this piece of code
Me.WebDetailsByIDTableAdapter.FillbyID(Me.WebDataSet.WebDetailsByID, CType(Me.WebRefSpinEdit.Text, Integer))
within a Try / Catch Block.
The TableAdapter is filled from an internet database. Our service provider has us behind a dynamic IP address. So periodically we have to log into the database control panel to allow access from our IP.
When I run the code in debug mode I receive the following error:
Exception thrown: 'MySql.Data.MySqlClient.MySqlException' in MySql.Data.dll
Additional information: Authentication to host '####' for user '###' using method 'mysql_native_password' failed with message: Access denied for user '#' to database '###'
The try catch block is:
Private Sub frmCourse_Details_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New MySqlConnection(My.Settings.WebConString)
Try
Me.BodiesTableAdapter.Fill(Me.MainDataSet.Bodies)
Me.ListCompaniesTableAdapter.Fill(Me.MainDataSet.ListCompanies)
Me.StatusTableAdapter.Fill(Me.MainDataSet.Status)
Me.CourseLIstTableAdapter.FillCoursesList(Me.MainDataSet.CourseLIst)
Me.CourseDocumentsTableAdapter.Fill(Me.MainDataSet.CourseDocuments, Me.CourseTextEdit.GetColumnValue("ID"))
If String.IsNullOrEmpty(Me.DateofCourseDateEdit1.Text) Then
Me.barFolderStatus.Caption = "Folder Not FOUND"
Else
Dim d As Date = Me.DateofCourseDateEdit1.Text
System.IO.Directory.CreateDirectory(GetCourseDirectory(CSEID))
If System.IO.Directory.Exists(GetCourseDirectory(CSEID)) Then
Me.barFolderStatus.Caption = GetCourseDirectory(CSEID) & " - Folder OK!"
Else
System.IO.Directory.CreateDirectory(GetCourseDirectory(CSEID))
Me.barFolderStatus.Caption = "Folder Not FOUND"
End If
End If
Me.RolesTableAdapter.Fill(Me.MainDataSet.Roles)
Me.InstructorsByCourseTableAdapter.Fill(Me.MainDataSet.InstructorsByCourse, Me.CourseTextEdit.Text)
If Me.CourseTypeTextEdit.Text = "Internal" And Not String.IsNullOrEmpty(Me.WebRefSpinEdit.Text) Then
Me.WebDetailsByIDTableAdapter.FillbyID(Me.WebDataSet.WebDetailsByID, CType(Me.WebRefSpinEdit.Text, Integer))
End If
Me.InstsGrid.RefreshData()
con.Open()
If con.State = ConnectionState.Open Then
BarStaticItem1.Caption = "Website Access OK"
Else
BarStaticItem1.Caption = "No Website Access"
End If
InitialSetDetails()
UpdateRibbon()
Me.Cursor = Cursors.Default
Catch ex As Exception
MessageBox.Show("Load Course Details:" & ex.Message)
Finally
con.Dispose()
End Try
Me.IDSpinEdit.ReadOnly = True
End Sub
Why is this exception not being caught? Is there some other error handling code I should be implementing?

Related

Vb.net application connect to multiple server via TCP/IP

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

Loading DataGridView from another form

I have been a long time reader of questions and answers on this site and this is my first question.
I have a Datagridview I want to load from a MySQL database. I can get the code to work if the datagridview is contained in the form I am writing the code in. If I request try and load it onto another form it does not work
The top bit of code works and the latter bit does not.
Public Sub LoadGrid3()
Dim job As String = TextBox10.Text
MySql.AddParam("#job", job)
Try
MySql.ExecQuery("select * from imprint.jobs_commonfields where jobno = #job")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If MySql.RecordCount > 0 Then DataGridView1.DataSource = MySql.mysqlds.Tables(0)
End Sub
Public Sub LoadGrid3()
Dim job As String = TextBox10.Text
MySql.AddParam("#job", job)
Try
MySql.ExecQuery("select * from imprint.jobs_commonfields where jobno = #job")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If MySql.RecordCount > 0 Then Form3.job_detail.DataSource = MySql.mysqlds.Tables(0)
End Sub

Closing my application After Exception shows using try,catch method VB.NET

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

what exception rule to use with unselected radio buttons to produce exception dialog

I am trying to produce an error exception when the user has not selected an option with radio buttons. The code I have does not produce the error exception message boxes. I am not getting any coding errors as the syntax seems to be fine, just that the code is not producing the desired procedure.
Try
SelectedServiceDeciaml = CostSelectedService
TotalDecimal = SelectedServiceDeciaml + TotalDecimal
AmountAllServicesTextBox2.Text = TotalDecimal.ToString("c")
Catch DiscountException As ArgumentException When (Discount10RadioButton5.Checked = False AndAlso Discount20RadioButton6.Checked = False AndAlso NoDiscountRadioButton7.Checked = False)
MessageBox.Show("A discount amount must be selected.", "Data entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Information)
With NoDiscountRadioButton7
.Focus()
.Select()
End With
End Try
You don't have to create a custom exception for your case, but if you want to create a custom exception then I would create a new class that inherits from the built in class: System.Exception. If you want to go that route I could give an example to you.
Try
SelectedServiceDeciaml = CostSelectedService
TotalDecimal = SelectedServiceDeciaml + TotalDecimal
AmountAllServicesTextBox2.Text = TotalDecimal.ToString("c")
If (Discount10RadioButton5.Checked = False AndAlso Discount20RadioButton6.Checked = False AndAlso NoDiscountRadioButton7.Checked = False) Then
MessageBox.Show("A discount amount must be selected.", "Data entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Information)
With NoDiscountRadioButton7
.Focus()
.Select()
End If
Catch ex As Exception
MessageBox.Show("An error occured... Heres the error: " & ex.ToString)
End Try

System.Net.Mail VB.NET 3.5 System.Net.Mail.SmtpException

I have searched the net thoroughly for a solution to this and have yet to find one.
I'm trying to establish a simple mail client to send text documents as raw text through SMTP. To do this I am using the System.Net.Mail library under VB.Net version 3.5
Whenever I try to send a message, I receive a System.Net.Mail.SmtpException.
I have tried using different mail providers, under different settings and have yet to solve this problem. This problem has been tested on 3 separate computers, all with different specifications.
The code is as follows:
Private Sub SendEmailMessage()
Try
If My.Computer.Network.IsAvailable Then
If DataValid() Then
'Data is valid, send the eMail.
Dim MailReceiver As String = txtReceiver.Text
'Create the eMail Message.
'Dim message As New MailMessage(from:=txtMailAddress.Text, to:=MailReceiver, subject:="(MTG) <CARD> " & ID, body:="<p>" & ConstructedFileString() & "<p>")
Dim message As New MailMessage
Dim MessageFrom As New MailAddress(txtMailAddress.Text)
Dim MessageTo As New MailAddress(MailReceiver)
With message
.From = MessageFrom
.To.Add(MailReceiver)
.Subject = "(MTG) CARD " & ID
.IsBodyHtml = True
.Body = "<p>" & ConstructedFileString() & "<p>"
End With
'Establish eMail Client
Dim emailClient As New SmtpClient()
Dim emailCredentials As New Net.NetworkCredential
With emailCredentials
.UserName = txtMailAddress.Text
.Password = txtPassword.Text
.Domain = "gmail.com"
End With
With emailClient
.Host = txtHostServer.Text
.Port = txtPort.Text
.Credentials = emailCredentials
.EnableSsl = chkSSL.Checked
.Timeout = 5000
End With
'Dim MailDomain As String = ""
'Dim PositionAt As Byte = 0
'PositionAt = txtMailAddress.Text.IndexOf("#")
'For i = PositionAt + 1 To Len(txtMailAddress.Text)
' MailDomain = MailDomain & txtMailAddress.Text.Chars(i)
'Next
'Debug.Print(MailDomain)
If My.Computer.Network.Ping(hostNameOrAddress:=emailClient.Host) Then
'Send the message.
emailClient.Send(message)
Else
'Could not ping, do not send.
ErrorOut("Could not reach the eMail Server.")
End If
Else
'Data is not valid, do not send the eMail.
End If
Else
ErrorOut("No network could be found. Check your network configurations.")
End If
Catch ex As Security.SecurityException
'Security exception
ErrorOut("A Security Exception was raised.")
Catch ex As Net.NetworkInformation.NetworkInformationException
'Network info exception
ErrorOut("Exception raised when retrieving network information.")
Catch ex As Net.NetworkInformation.PingException
'Ping exception
ErrorOut("Exception raised when pinging the network.")
Catch ex As Net.Mail.SmtpFailedRecipientException
'Recipient exception
ErrorOut("Mail Recipient Exception raised.")
Catch ex As Net.Mail.SmtpException
'Mail Server Exception
ErrorOut("Mail Server Exception raised")
Catch ex As Exception
'Generic Exception raised.
ErrorOut("General Exception raised", True)
End Try
End Sub
Any help on this matter is greatly appreciated, thanks.
Stack trace:
System.Net.Mail.SmtpException: The operation has timed out.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at NetProj.EmailDialog.SendEmailMessage() in ...
I believe this is the famous SSL issue with System.Net.Mail
http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx
It was there in framework 3.5 not sure about 4.0 if they fixed it or not.