I am trying to download a chat.txt file from my ftp server so it updates fast instead of with a timer because the form is lagging with a timer. but now i get the error:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
and my code is:
Private Sub RefreshChat()
Dim client As New Net.WebClient
client.Credentials = New Net.NetworkCredential("username", "pass")
Do
Try
Dim ChatInfo = client.DownloadString("ftp://ftphost/Users/" + Me.Text + "/" + Me.Text + TextBox3.Text + "Chat.txt")
TextBox1.Text = Decrypt(ChatInfo)
Catch
End Try
Loop
End Sub
this is the full error i get:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Related
I tried integrating google API in my VB.NET project.
I am getting the error Object reference not set to an Instance of an object.
But if I run the same thing again it works.
My code:
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
request.Upload()
Dim responsefile = request.ResponseBody
MsgBox(responsefile.Id.ToString) '-----Error catch here
Catch e As Exception
MsgBox("An error occurred: " + e.Message)
Return Nothing
End Try
NOTE : The same thing I run 2nd time in and it works well.
What should I do?
try this;
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
request.Upload()
Dim responsefile = request.ResponseBody
If responsefile.Id.ToString IsNot Nothing Then
MsgBox(responsefile.Id.ToString) '-----Error catch here
Else
request.Upload()
responsefile = request.ResponseBody
MsgBox(responsefile.Id.ToString)
End If
Catch e As Exception
MsgBox("An error occurred: " + e.Message)
Return Nothing
End Try
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
This question appears multiple times on StackExchange but I just can't solve it. Most answers say that this arises due to SSL or TLS issues and to set the protocol to TLS10 or to use KeepAlive.
In my case, I am calling my own PHP endpoint and not using SSL. The server is hosted on GoDaddy.
I am retrieving records from the server. Due to the large size of the returned data, I placed the calls in a loop. The loop runs and fetches data for 40-50 iterations before throwing this error. It is not a timeout issue as the error is thrown within milliseconds.
I suspect a stream or connection is not closing and the VB.Net program is running out of resources or the server has too many open connections.
The code below is slightly abridged to remove sensitive info:
While True
' Create the request
uri = New Uri(My.Settings.ServerURL & My.Settings.GetEmployeeRecords)
request = DirectCast(WebRequest.Create(uri), HttpWebRequest)
' Add user credentials
creds = New CredentialCache
creds.Add(uri, "Basic", New NetworkCredential(My.Settings.UserId, My.Settings.Password))
With request
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
.AutomaticDecompression = DecompressionMethods.GZip + DecompressionMethods.Deflate
.Credentials = creds
.KeepAlive = False
.ProtocolVersion = HttpVersion.Version10
.ConnectionGroupName = Guid.NewGuid().ToString()
.UserAgent = "VB.NET App"
.AllowAutoRedirect = False
End With
' Add parameters
strPostData = String.Format("offset={0}&limit={1}", iOffset, iLimit)
request.ContentLength = strPostData.Length
Try
Using sw As New StreamWriter(request.GetRequestStream)
sw.Write(strPostData)
sw.Close()
End Using
Catch ex As Exception
e.Result = "Error Setting Request Data"
Exit Sub
End Try
' Send the request to the server
Try
response = DirectCast(request.GetResponse, HttpWebResponse)
Catch ex As WebException
e.Result = "Error Sending Request" **<-- This is where it is thrown**
Exit Sub
End Try
' Open the response
Try
reader = New StreamReader(response.GetResponseStream)
Catch ex As Exception
e.Result = "Error Reading Request"
Exit Sub
End Try
' Read the full response
rawresp = reader.ReadToEnd()
reader.Close()
response.Close()
' We should never get a blank response
If rawresp = "" Or rawresp = "[]" Then
e.Result = "Blank Response"
Exit Sub
End If
' The response should be in JSON. Parse it
Try
jResults = Linq.JObject.Parse(rawresp)
Catch ex As Exception
e.Result = "Error parsing response"
Exit Sub
End Try
' Get the complete response into jResults
' The jResults would contain {statuscode, statusDescription, data[]} where the data element would be an array of employees
' Check for error returned in response JSON
If jResults("statusCode").ToString = "404" Then
Exit While
End If
If jResults("statusCode").ToString <> "0" Then
e.Result = "Error received from server"
Exit Sub
End If
' Get the array for the employee records
Try
jEmployees = Linq.JArray.Parse(jResults("data").ToString)
Catch ex As Exception
e.Result = "Response Does Not Contain Employee Array"
Exit Sub
End Try
' Everything is fine. Add the recordds to the local database
SaveEmployeesToLocalDB(jEmployees)
iCount = jEmployees.Count
iOffset += iCount
iTotalRecords += iCount
If iCount = 0 Then
Exit While
End If
If iTotalRecords Mod (20 * iLimit) = 0 Then
Application.DoEvents()
Threading.Thread.Sleep(3000)
End If
End While
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?
Greatings, ive got a piece of code and i keep getting an error when executing the code in VB. The error says " 'Captcha' is not declared." . Enyone?## Heading ##
The code:
With New Net.WebClient
Try
Dim b() As Byte = .UploadFile(New System.Uri("127.0.0.1"), Captcha.Path)
Captcha.Solution = System.Text.Encoding.ASCII.GetString(b).Split(CChar("|"))(5).ToString
Catch ex As Exception
Result.FailMessage = "Could not retrieve captcha response; " & ex.Message
Exit Try
End Try
End With