Keep getting a first chance exception error - vb.net

When i run my program the code catches the timeout exception correctly but then i get a popup message saying:
A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.VisualBasic.dll
Also says this:
Object variable or With block variable not set.
Here is my code:
Dim rt As String = ""
Dim out As String
Dim wRequest As WebRequest
Dim wResponse As WebResponse
Dim SR As StreamReader
Dim time As Date
time = Now()
Try
wRequest = WebRequest.Create(Address)
wRequest.Timeout = 10000
wResponse = wRequest.GetResponse
SR = New StreamReader(wResponse.GetResponseStream)
rt = SR.ReadToEnd
SR.Close()
Catch wex As System.Net.WebException
If wex.Status = WebExceptionStatus.Timeout Then
MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Timed Out", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Try

Related

VB.net - see if remote file exists

I have a function to check if a remote file exists after being passed the URL. Assuming it doesn't exist the function would return 0 to be used in another sub. Here's what I have:
Public Function RemoteFileExists(ByVal fileurl As String) As Integer
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(fileurl), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.GetFileSize
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
RemoteFileExists = 0
Exit Function
End If
Dim fileSize As Long = response.ContentLength
MsgBox(fileSize)
If fileSize > 0 Then
RemoteFileExists = 1
Else
RemoteFileExists = 0
End If
End Function
When I run the app and purposely supply a URL that doesn't exist Visual Studio gives me System.Net.WebException was unhandled. Message=The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
I assumed that the "if response.StatusCode..." would handle that rather than shutting down the program.
Any help appreciated.
DWM
First of all you should switch from Integer to Boolean since you only return either 1 or 0 anyway. A Boolean can be either True or False.
Secondly, you should wrap everything in a Try/Catch block to handle any error that might occur. Wrapping code in Try/Catch can catch most errors (except for the most extreme ones) and putting it around code that could throw an error saves you from having your application crash for the more simple errors.
And finally, you should use Return <value> instead of RemoteFileExists = <value>, since Return will both return the wanted value AND exit the function.
Example implementation:
Public Function RemoteFileExists(ByVal fileurl As String) As Boolean
Try
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(fileurl), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.GetFileSize
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
Return False 'Return instead of Exit Function
End If
Dim fileSize As Long = response.ContentLength
MsgBox(fileSize)
If fileSize > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception 'Catch all errors
'Log the error if you'd like, you can find the error message and location in "ex.Message" and "ex.StackTrace".
MessageBox.Show("An error occurred:" & Environment.NewLine & ex.Message & Environment.NewLine & ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False 'Return False since the checking failed.
End Try
End Function
In the Catch block, ex.Message is the error message, and ex.StackTrace is where in the code the error occurred.

Web request not repeating after failure, try/catch not working

I am trying to send a web request to a Snom PA1 bell. The bell rings periodically throughout the day, but occasionally times out trying to contact the bell. That would be fine, but after this happens a couple times, the web request stops sending altogether. the sub still runs, but no bells. Also, while debugging, the webrequest throws a webexception that is not handled by the catch, even though it is contained within the try/catch.
Does anyone know why the web request would stop working after a failure?
Private Sub ringIPBell(ByVal params() As Object, Optional ByVal secondattempt As Boolean = False)
Dim IPaddress As String = params(0)
Dim ringSeconds As Double = params(1)
Dim wr As Net.HttpWebRequest
If ringSeconds = 2 Then
wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=2")
Else
wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=1")
End If
wr.Method = "post"
wr.CachePolicy = New System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore) 'added Oct2010
wr.Credentials = New Net.NetworkCredential("correctName", "correctPassword")
Dim postdata As String = "PLAY_RINGER:1=Play Ringer"
wr.ContentLength = postdata.Length + 2
Dim requestStream As IO.Stream, strmwrit As IO.StreamWriter
Try
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
Dim responsestream As New IO.StreamReader(wr.GetResponse.GetResponseStream)
Catch ex As System.Net.WebException
If Not secondattempt Then
ringIPBell(params, True)
End If
Dim testvar As String = ex.ToString
Catch ex As Exception
Beep()
End Try
Also, I previously had the following code ringing the bell, but it would only work for one of the two bells, Even though as far as i can tell their settings were identical.
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
requestStream.Close()
As suggested I broke out the responestream line as such:
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
it breaks on "requestStream = wr.GetRequestStream()"
with the error:
"A first chance exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The operation has timed out"

Object variable or With block variable not set?

I get this error when i run my program:
A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.VisualBasic.dll
Object variable or with block variable not set
Here is my code:
Dim rt As String = ""
Dim out As String
Dim wRequest As WebRequest
Dim wResponse As WebResponse
Dim SR As StreamReader
Dim time As Date
time = Now()
Try
wRequest = WebRequest.Create(Address)
wRequest.Timeout = 10000
wResponse = wRequest.GetResponse
SR = New StreamReader(wResponse.GetResponseStream)
rt = SR.ReadToEnd
SR.Close()
Catch wex As WebException
Dim status As WebExceptionStatus = wex.Status
If status = WebExceptionStatus.Timeout Then
MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Timed Out", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf status = WebExceptionStatus.ConnectFailure Then
MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf status = WebExceptionStatus.ProtocolError Then
MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Protocol Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Try
The source of your error could be your Address variable.
Please try prefix with http:// in front.
Example:
Address = "http://www.google.com"
for more further information, please read MSDN WebRequest.Create Method (String)
The problem is most likely that wResponse.GetResponseStream is failing because wResponse is null. (which is probably because your Address variable isn't valid).
Try adding
Catch ex As Exception
MessageBox.Show("Some other error occurred: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
after your WebException Catch block to see what the problem is.
Or just put a breakpoint on SR = New StreamReader(wResponse.GetResponseStream) and look at wResponse (your choice).
I am checking your code and it works fine.
Here's a demo although I made a little change on the declaration of time variable and putting a string on WebRequest.Create() like:
Dim time As Date = Now
and
WebRequest.Create("https://www.google.fm")
And as per my own search there is nothing much to be concerned about with this kind of error, see the link below.
A first chance exception

How to get result from failing webclient.downloadstring?

If we use webclient.downloadstring on a server with error, we got nothing
Try
result = webClient.DownloadString("https://api.bodis.com/domainclassification?domain=" + CurrentBlog.Domain)
Catch ex As Exception
System.Windows.Forms.Application.DoEvents()
End Try
Usually result contains the response. But in case of error result is empty.
I want to know something. For example, even if the result is bad, usually there is a custom 404 message, etc.
The api.bodis.com is problematic because it mix secure and non secure stuff. However, it gives output anyway in internet explorer. I want to use webclient and I want to know the ouput
Getting ex.response yields nothing
Dim adult = webClient.DownloadString("http://googleads.g.doubleclick.net/apps/domainpark/domainpark.cgi?callback=_google_json_callback&output=js&client=ca-dp-godaddy2_xml&domain_name=" + CurrentBlog.Domain)
'ias.NavigateTillComplete("https://api.bodis.com/domainclassification?domain=" + CurrentBlog.Domain)
Dim result = ""
Dim url = "http://api.bodis.com/domainclassification?domain=" + CurrentBlog.Domain
Dim webRequest = DirectCast(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
Dim response As HttpWebResponse
Try
response = DirectCast(webRequest.GetResponse(), HttpWebResponse)
Catch ex As System.Net.WebException
System.Windows.Forms.Application.DoEvents()
response = DirectCast(ex.Response, HttpWebResponse) 'is nothing there
End Try
Dim responseStream = response.GetResponseStream

How can I read the response from a web request when the Status is not 200?

I am having difficulty getting the response text from a HTTP web request in vb.net when I get a web exception.
This is the code I am doing it with.
Try
myWebResponse = CType(request.GetResponse(), HttpWebResponse)
myStreamReader = New StreamReader(myWebResponse.GetResponseStream())
ResponseText = myStreamReader.ReadToEnd
If myWebResponse.StatusCode = HttpStatusCode.Accepted Or myWebResponse.StatusCode = 200 Then
SendResult = True 'Sent
SendStatus = 1 'message sent successfully
Try
Integer.TryParse(myWebResponse.Headers("Number-Of-MT-PDU"), num_MT_PDU)
Catch ex As Exception
End Try
Else
SendStatus = 2 'message processed but not sent successfully
End If
Catch e As WebException
If (e.Status = WebExceptionStatus.ProtocolError) Then
Dim response As WebResponse = e.Response
Using (response)
Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
statusCode = httpResponse.StatusCode
Try
myStreamReader = New StreamReader(response.GetResponseStream())
Using (myStreamReader)
ResponseText = myStreamReader.ReadToEnd & "Status Description = " & HttpWebResponse.StatusDescription
End Using
Catch ex As Exception
Logger.LogError(Me, ex)
End Try
End Using
Annoyingly, the API I am contacting uses a 404 as a valid response. If I put the request in a browser some message text will be displayed. I want to be able to use that text in my program. I can not simply use the error code to determine actions as I don't think I can differentiate between a valid 404 response and an actual error.
In the code this line
myWebResponse = CType(request.GetResponse(), HttpWebResponse)
throws an exception.
In the exception I can get the 404 code and the description but not the response stream. It is always null.
If I get a 200 response I get the text in the Response stream no problem.
In the web exception response object (in Visual Studios debugger) I have checked the headers and the object values and can't find the response text anywhere. If I stick the request URL in a browser I get response text back even though it is a 404.
The raw response in fiddler:
HTTP/1.1 404 Not Found Connection: close Content-Type: text/plain; charset=UTF-8 Content-Length: 35 "The response Message"
Any ideas on how I can get "The response Message" in my program? I have to use .Net on the server.
Thanks for any help anybody can give.
This LINQPad query works fine, dumping the HTML provided by my web server's "Not Found" error web page:
Dim rq = System.Net.WebRequest.Create(New Uri("http://localhost/test"))
Try
Dim rs = rq.GetResponse
rs.Dump
Catch Ex As System.Net.WebException
Dim rs = Ex.Response
Call (New StreamReader(rs.GetResponseStream)).ReadToEnd.Dump
End Try
FYI Your code works for me, except the presumed typo re HttpWebResponse.StatusDescription (and commenting out "unrelated stuff"), again as a LINQPad query (in .NET 4.0):
Dim request = WebRequest.Create("http://localhost/test")
Dim myStreamReader As StreamReader
Dim SendStatus As Integer = -1
Dim statusCode As HttpStatusCode
Dim ResponseText As String
Try
Dim myWebResponse = CType(request.GetResponse(), HttpWebResponse)
myStreamReader = New StreamReader(myWebResponse.GetResponseStream())
ResponseText = myStreamReader.ReadToEnd
If myWebResponse.StatusCode = HttpStatusCode.Accepted Or myWebResponse.StatusCode = 200 Then
'SendResult = True 'Sent
SendStatus = 1 'message sent successfully
'Try
' Integer.TryParse(myWebResponse.Headers("Number-Of-MT-PDU"), num_MT_PDU)
'Catch ex As Exception
'End Try
Else
SendStatus = 2 'message processed but not sent successfully
End If
Catch e As WebException
If (e.Status = WebExceptionStatus.ProtocolError) Then
Dim response As WebResponse = e.Response
Using (response)
Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
statusCode = httpResponse.StatusCode
Try
myStreamReader = New StreamReader(response.GetResponseStream())
Using (myStreamReader)
ResponseText = myStreamReader.ReadToEnd & "Status Description = " & httpResponse.StatusDescription ' HttpWebResponse.StatusDescription
End Using
Catch ex As Exception
'Logger.LogError(Me, ex)
ex.Dump("Exception")
End Try
End Using
End If
End Try
ResponseText.Dump("ResponseText")
I have also confirmed the above code (with the inferred As clauses added and converting the .Dump calls to Console.WriteLine) works in .NET 2.0 with VB8.
Note that the key is that even though the act of GetResponseStream() throws a .NET WebException, the HttpWebResponse is actually passed to the WebException object, so when in the Catch, you do a new GetResponseStream() on the WebException.Response object.
Below, very similar code for when in the Catch of the initial GetResponseStream()
Try
OriginalResponseStream = GetResponseStream(OriginalHTTPWebResponse)
Catch wex as WebException
Dim response As WebResponse = wex.Response
Dim statusCode As HttpStatusCode
Dim ResponseText As String
Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
statusCode = httpResponse.StatusCode
Try
Dim myStreamReader As New StreamReader(response.GetResponseStream())
Using (myStreamReader)
ResponseText = myStreamReader.ReadToEnd
Process(ResponseText) '<===as in whatever you need to do with the response
End Using
Catch ex As Exception
HandleIt(ex.Message) '<===as in whatever you want to do if Exception during the above
End Try
End Try