Retrieve errors from MySQLDataAdapter.update() - vb.net

I'm deliberately trying to change my dataset to have a duplicate primary key with the expectation that this action would throw a mysql error.
How can I retrieve such errors from MySQLDataAdapter.Update()??
I've had a brief look at event handlers but I can't seem to find where to get the error anywhere. Although I did notice that MySqlRowUpdatingEventArgs.Status = SkipCurrentRow
Code snippet:
Private Sub UpdateTable()
Dim MyCommandBuilder As New MySqlCommandBuilder(MyDataadapter)
txtConsole.AppendText(vbNewLine & MyDataSet.HasErrors.ToString)
AddHandler MyDataadapter.RowUpdating, AddressOf OnRowUpdating
AddHandler MyDataadapter.RowUpdated, AddressOf OnRowUpdated
If MyDataSet.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
' Without the MySqlCommandBuilder this line would fail.
Try
Dim rowsAffected As Integer = MyDataadapter.Update(MyDataTable)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
Catch ex As MySqlException
txtConsole.AppendText(vbNewLine & "Error: " & ex.ToString())
End Try
End If
RemoveHandler MyDataadapter.RowUpdating, AddressOf OnRowUpdating
RemoveHandler MyDataadapter.RowUpdated, AddressOf OnRowUpdated
End Sub
' handler for RowUpdating event
Private Shared Sub OnRowUpdating(sender As Object, e As MySqlRowUpdatingEventArgs)
PrintEventArgs(e)
End Sub
' handler for RowUpdated event
Private Shared Sub OnRowUpdated(sender As Object, e As MySqlRowUpdatedEventArgs)
PrintEventArgs(e)
End Sub
Private Overloads Shared Sub PrintEventArgs(args As MySqlRowUpdatingEventArgs)
Console.WriteLine("OnRowUpdating")
Console.WriteLine(" event args: (" & " command=" & args.Command.CommandText & _
" commandType=" & args.StatementType & " status=" & args.Status & ")")
End Sub
Private Overloads Shared Sub PrintEventArgs(args As MySqlRowUpdatedEventArgs)
Console.WriteLine("OnRowUpdated")
Console.WriteLine(" event args: (" & " command=" & args.Command.CommandText & _
" commandType=" & args.StatementType & " recordsAffected=" & _
args.RecordsAffected & " status=" & args.Status & ")")
End Sub

Related

Classes and textbox is not a member of class generate

Hello i'm trying to move my code to difrent classes so i can keep everything organized.
What i have now:
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
What i want:
Public Class Form1
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
//run code of class generate
end sub
end class
public class generate
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
end class
I tried this before but it will give errors like "generatedlines is not a member of class generated"

Form is sent to back after function runs

I've got the following section of code:
Public Sub SendTestEmail()
Try
Dim Mail As New MailMessage
Mail.Subject = "Test email"
Mail.To.Add(smtpTXTsendto.Text)
Mail.From = New MailAddress(smtpTXTusername.Text)
Mail.Body = "This is a test message"
Dim SMTP As New SmtpClient(smtpTXTserver.Text)
If smtpCHECKssl.Checked = True Then
SMTP.EnableSsl = True
Else
SMTP.EnableSsl = False
End If
SMTP.Credentials = New System.Net.NetworkCredential(smtpTXTusername.Text, smtpTXTpassword.Text)
SMTP.Port = smtpTXTport.Text
SMTP.Send(Mail)
MessageBox.Show("A test email has been sent." & Environment.NewLine & Environment.NewLine & "To: " & smtpTXTsendto.Text & Environment.NewLine & "From: " & smtpTXTusername.Text & "." & Environment.NewLine & Environment.NewLine & "If you did not recieve an email, please check your settings and try again.", "Test Email")
Catch ex1 As Exception
MessageBox.Show(ex1.Message)
Return
End Try
End Sub
The Sub SendTestEmail is called inside of a Background worker.
The odd issue I'm having, as that when a MessageBox appears, and I click OK the form gets sent to the back of the screen, behind all applications ...
I've tried adding a Me.focus, but it gives me issues about Cross Tread violations.
Any ideas why this is happening?
Background Worker Code:
Private Sub BGWSendTestEmail_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BGWSendTestEmail.DoWork
SendTestEmail()
End Sub
Private Sub BGWSendTestEmail_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWSendTestEmail.RunWorkerCompleted
If (e.Cancelled) Then
MsgBox("Something went wrong!")
Else
GroupBoxTesting.Visible = False
Me.Enabled = True
End If
End Sub
Private Sub SMTPButtonTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMTPButtonTest.Click
GroupBoxTesting.Visible = True
Me.Enabled = False
BGWSendTestEmail.RunWorkerAsync()
End Sub
Change BGWSendTestEmail_RunWorkerCompleted to something like this and remove exception handling from SendTestEmail
Me.Enabled = True ' Always enable form first after completed
If e.Error Is Nothing Then
If Not e.Cancelled Then
MessageBox.Show("A test email has been sent." _
& Environment.NewLine _
& Environment.NewLine _
& "To: " & smtpTXTsendto.Text _
& Environment.NewLine _
& "From: " & smtpTXTusername.Text _
& "." & Environment.NewLine _
& Environment.NewLine _
& "If you did not recieve an email, please check your settings and try again.", _
"Test Email")
GroupBoxTesting.Visible = False 'Maybe put this also into start of method?
Else
MsgBox("Something went wrong!")
End If
Else
MessageBox.Show("Email sending failed. Exception: " & e.Error.Message)
End If
If you debug this program your debugger will attach exceptions in do_work method, but if you run it without debugger then exceptions are handled at completed method.

client gives error 10060 when sending message to a TCP port

we are using a vb.net chat application which uses a TCP client to send message.it uses TCP port 25025.In some cases we get an error 10060 from client when sending message.Also the error is not continuous and is intermediate.In both PC windows firewall and antivirus firewall is off.To troubleshoot the problem i have tried telnet and netstat command and it worked without any error.what may be possible reasons for this error and how to troubleshoot?
Error 10060 is 'connection timed out'.
Check your timeout parameters for all sockets/TCP client/server objects.
Check that you are not looping somewhere waiting for a response, etc.
Without any source code or further information, other diagnosis is difficult!
these are client side and server side code.
we get Error 10053 and 10061 also
Client side code
in our application when user clicks 'send' message' button this procedure will be called..
Public Sub SendMessageByPort(ByVal PCName As String, ByVal Port As Integer, ByVal Message As String)
Try
'add winsock control added
Dim TempWinClient As New AxMSWinsockLib.AxWinsock
Me.Controls.Add(TempWinClient)
AddHandler TempWinClient.CloseEvent, AddressOf TcpClient_CloseEvent
AddHandler TempWinClient.ConnectEvent, AddressOf TcpClient_ConnectEvent
AddHandler TempWinClient.DataArrival, AddressOf TcpClient_DataArrival
AddHandler TempWinClient.Error, AddressOf TcpClient_Error
TempWinClient.RemoteHost = PCName
TempWinClient.RemotePort = Port
TempWinClient.Tag = Message
TempWinClient.Connect()
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "UpdateToServer")
End Try
End Sub
Private Sub TcpClient_ConnectEvent(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
sender.SendData(sender.tag)
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "WinClient_ConnectEvent")
End Try
End Sub
Private Sub TcpClient_DataArrival(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent)
Try
Dim TempStr As String = ""
Dim MsgID As String = "" '
Dim ErrorMsgstr As String = ""
sender.GetData(TempStr)
If TempStr.IndexOf("[ERROR]") >= 0 Then
MessageBox.Show("Error when Message send to " & sender.RemoteHost.ToString & " " & TempStr, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf TempStr.IndexOf("[SUCCESS]") >= 0 Then
MessageBox.Show("Message Sucssesfully sent to port", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(TempStr, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
sender.Close()
Me.Controls.Remove(sender)
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "TcpClient_DataArrival")
End Try
End Sub
Private Sub TcpClient_CloseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Try
sender.Close()
Me.Controls.Remove(sender)
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "WinClient_CloseEvent")
End Try
End Sub
Private Sub TcpClient_Error(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent)
Try
Dim retryCnt As Integer
Dim MessageData As String = sender.tag
Dim RetryProcess As Boolean
Dim ErrorDetails As String = "Not Uploaded to Web because of connection failure in network " & sender.RemoteHost.ToString & ". DataSent:" & MessageData
'for this error we tried three times
If InStr(e.description, "Connection is aborted due to timeout or other failure", CompareMethod.Text) > 0 Then
retryCnt = Val(getArgColVal("RetryProcess", MessageData))
If retryCnt < 3 Then
MessageData = Replace(MessageData, "#RetryProcess$" & retryCnt & "|", "", , , CompareMethod.Text)
MessageData = MessageData & "#RetryProcess$" & (retryCnt + 1) & "|"
RetryProcess = True
End If
End If
If RetryProcess = True Then 'retry sending message to port on error
Call SendMessageByPort(sender.RemoteHost.ToString, sender.RemotePort, MessageData)
Else
Call Write_toErrorLog("", e.description, e.number, Me.Name, "TcpClient_Error", True, , , ErrorDetails) '
Call MsgWinman("785", "sender" & MsgVarSep & "description" & MsgVarSep & "number", sender.RemoteHost.ToString & MsgVarSep & e.description & MsgVarSep & e.number)
End If
End If
sender.Close()
Me.Controls.Remove(sender)
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "TcpClient_Error") 'sod 19.9.13'Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "WinClient_Error")
End Try
End Sub
Server side code
'global variables
Dim TempWebDetails() As WebUpLoadDetails
Dim WinSocketArray As AxMSWinsockLib.AxWinsock() = New AxMSWinsockLib.AxWinsock() {}
Dim WinSocketName() As String
'''
''' 0-->Close,1-->Listen,2-->Others
'''
Dim WinSocketState() As Integer
Dim WinTimer() As Integer
'frmpaydet is form name
Private Sub frmPayDet_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
Try
LoadNewSocket()
ListenFreeSocket()
Me.Hide()
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Text, "frmPayDet_Shown")
End Try
End Sub
Private Sub LoadNewSocket()
Dim IsVisible As Boolean = Me.Visible
Try
Me.Visible = True
Dim i As Integer = WinSocketArray.GetUpperBound(0) + 1
ReDim Preserve WinSocketArray(i)
ReDim Preserve WinSocketState(i)
ReDim Preserve WinSocketName(i)
ReDim Preserve WinTimer(i)
WinSocketArray(i) = New AxMSWinsockLib.AxWinsock
WinSocketArray(i).Name = "WinServer" & i
WinSocketName(i) = WinSocketArray(i).Name
Me.Controls.Add(WinSocketArray(i))
AddHandler WinSocketArray(i).CloseEvent, AddressOf tcpServer_CloseEvent
AddHandler WinSocketArray(i).ConnectionRequest, AddressOf tcpServer_ConnectionRequest
AddHandler WinSocketArray(i).DataArrival, AddressOf tcpServer_DataArrival
AddHandler WinSocketArray(i).Error, AddressOf tcpServer_Error
ToolSeverCount.Text = " | WinSocket Count is " & i + 1 & " |"
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "LoadNewSocket")
Finally
Me.Visible = IsVisible
End Try
End Sub
Private Sub ListenFreeSocket()
On Error GoTo ListenFreeSocket_eh
Dim ListenFlg As Boolean
Timer1.Enabled = True
ToolServer.Text = ""
If WinSocketArray.Length > 0 Then
For i As Integer = 0 To WinSocketState.GetUpperBound(0)
If WinSocketState(i) = 1 Then
ToolServer.Text = " | " & WinSocketArray(i).Name & " Sever Listen at Port " & WinSocketArray(i).LocalPort & " | "
ListenFlg = True
Exit For
End If
Next
'if not found then listen socket which is free
If ListenFlg = False Then
For i As Integer = 0 To WinSocketState.GetUpperBound(0)
If WinSocketState(i) = 0 Then
WinSocketArray(i).LocalPort = Split("PC110:8000", ":")(1)
WinSocketArray(i).Listen()
ToolServer.Text = " | " & WinSocketArray(i).Name & " Sever Listen at Port " & WinSocketArray(i).LocalPort & " | "
WinSocketState(i) = 1
If i = WinSocketState.GetUpperBound(0) Then LoadNewSocket()
ListenFlg = True
Exit For
End If
Next
End If
End If
If ListenFlg = False Then
'Enable Timer
LoadNewSocket()
Timer1.Enabled = True
Else
'Disable Timer
Timer1.Enabled = False
End If
Exit Sub
ListenFreeSocket_eh:
'Write_toErrorLog_old(Err.Description, Err.Number, Me.Name, "ListenFreeSocket")'this line must be commented
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Call ListenFreeSocket()
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "Timer1_Tick")
End Try
End Sub
Private Sub tcpServer_ConnectionRequest(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent) ' Handles tcpServer1.ConnectionRequest, tcpServer2.ConnectionRequest, tcpServer3.ConnectionRequest, tcpServer4.ConnectionRequest, tcpServer5.ConnectionRequest, tcpServer0.ConnectionRequest
Try
CloseWinSocket(sender.name)
sender.Accept(e.requestID)
ConnectWinSocket(sender.name)
ListenFreeSocket()
ToolStatus.Text = " | " & sender.RemoteHostIP & " IP Address Accepted | "
Catch ex As Exception
ToolServer.Text = ex.Message & " Please Call Coding Team"
End Try
End Sub
Private Sub CloseWinSocket(ByVal SocketName As String)
Try
If SocketName.Trim <> "" Then
Dim i As Integer = Array.IndexOf(WinSocketName, SocketName)
WinSocketArray(i).Close()
WinSocketState(i) = 0
WinTimer(i) = 0
Else
If Not WinSocketState Is Nothing Then
For i As Integer = 0 To WinSocketState.GetUpperBound(0)
If WinSocketState(i) <> 0 Then
WinSocketArray(i).Close()
WinSocketState(i) = 0
WinTimer(i) = 0
End If
Next
End If
End If
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "CloseWinSocket")
End Try
End Sub
Private Sub ConnectWinSocket(ByVal SocketName As String)
Try
Dim i As Integer = Array.IndexOf(WinSocketName, SocketName)
WinSocketState(i) = 2
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "ConnectWinSocket")
End Try
End Sub
Private Sub tcpServer_DataArrival(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent)
Try
Dim TempStr As String = ""
Dim ReplyMessage As String = ""
sender.GetData(TempStr)
If TempStr Is Nothing Then TempStr = ""
If TempStr.Trim <> "" Then
''some process is done
'ReplyMessage string assigned proper reply string
sender.SendData(ReplyMessage)
Else
CloseWinSocket(sender.name)
ToolStatus.Text = " | No Data Sent to IPAddress:- " & sender.RemoteHostIP & " | "
End If
Catch ex As Exception
Write_toErrorLog(ex.StackTrace, Err.Description, Err.Number, Me.Name, "tcpServer_DataArrival")
End Try
End Sub
Private Sub tcpServer_Error(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent)
Try
ToolServer.Text = e.description & " Please Call Coding Team"
CloseWinSocket(sender.name)
ListenFreeSocket()
ToolServer.Text = "Sever Listen on Local Port " & sender.LocalPort()
Catch ex As Exception
ToolServer.Text = ex.Message & " Please Call Coding Team"
End Try
End Sub
Private Sub tcpServer_CloseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Try
CloseWinSocket(sender.name)
ListenFreeSocket()
Catch ex As Exception
ToolServer.Text = ex.Message & " Please Call Coding Team"
End Try
End sub

Saving an Image in VB.NET

I have a little code for saving an image from an URL in VB.NET but im not finding the location where it saves the image, i added a location string but i dont know how to use it in the code.
How do i change the location whre my code saves the image ( Imports System.Drawing
Public Class Form1)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyImage As System.Drawing.Image
Dim URL As String = TextBox1.Text
Dim FileName As String, URLpieces As String()
Dim location As String = "C:/SaveIMGURL/"
URLpieces = Split(URL, "/")
FileName = URLpieces.GetValue(UBound(URLpieces))
MyImage = GetImage(URL)
MyImage.Save(FileName)
MyImage = Nothing
End Sub
Function GetImage(ByVal URL As String) As System.Drawing.Image
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Request = System.Net.WebRequest.Create(URL)
Response = CType(Request.GetResponse, System.Net.WebResponse)
If Request.HaveResponse Then
If Response.StatusCode = Net.HttpStatusCode.OK Then
GetImage = System.Drawing.Image.FromStream(Response.GetResponseStream)
End If
End If
Try
Catch e As System.Net.WebException
MsgBox("A web exception has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.ProtocolViolationException
MsgBox("A protocol violation has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.Sockets.SocketException
MsgBox("Socket error [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.IO.EndOfStreamException
MsgBox("An IO stream exception has occured. System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Finally
End Try
End Function
End Class

Cannot add computer to active directory using LDAP

Using the following code:
Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
'see if it already exists
If DirectoryEntry.Exists("LDAP://CN=" & AdEntry.Text & ",OU=" & Machinetype.Text & ",OU=Computers,OU=" & USlocation.Text & ",OU=North America,DC=company,DC=com") = True Then
MsgBox("Object already exists")
Else
Try
'Set the directory entry
Dim de As New DirectoryEntry("LDAP://OU=" & Machinetype.Text & ",OU=Computers,OU=" & USlocation.Text & ",OU=North America,DC=company,DC=com")
Dim newComputer As DirectoryEntry = de.Children.Add("CN=TESTER", "computer")
newComputer.CommitChanges()
MsgBox("Computer added!")
Catch ex As Exception
MsgBox("Error adding computer")
End Try
End If
End Sub
End Class
According to http://msdn.microsoft.com/en-us/library/ms180851(v=VS.80).aspx this should work, but it returns an exception. Is there something I'm missing?