Compiler error in using block - c#

I am trying to catch any errors that crop up when a URL is invalid, below is the original code:
public static void mymethod()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse())
timer.Stop();
timeTaken = timer.Elapsed.ToString();
}
I have tried to create an exception handler as below, but no luck:
public static void mymethod()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
try
{
using (var response = request.GetResponse())
}
catch
{
Console.WriteLine("error here...")
}
timer.Stop();
timeTaken = timer.Elapsed.ToString();
}

You should do something like this.
public static void ShowResponseAndTimeTaken(string firstline)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse())
{
Console.WriteLine("Response : {0}", response);
}
timer.Stop();
Console.WriteLine("Time taken : {0}", timer.Elapsed);
}
catch(Exception e)
{
Console.WriteLine("error : {0}", e.Message);
}
}

Your usage of using-block is incorrect. The correct looks like this:
using (var response = request.GetResponse())
{
}
or just without the block:
var response = request.GetResponse();
response.Dispose()

I believe you cannot intercept it because it is thrown before "try" block:
it is possible that "firstline" variable contains a text with perhaps incorrectly formatted uri,
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);

You can also validate URL using regex instead of waiting for exception to be thrown - http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx.
Here (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx) you can find detailed description about GetResponse. Check what exceptions can be thrown and modify your current exception handling.
You shouldn't leave try...catch as it is. At least catch Exception class.

WebRequest.Create only throws if the scheme is invalid (the bit before the colon), there is a security error or if the URI you pass is null (although you have not enclosed that statement inside your try statement so such errors will be unhandled by the above code anyway).
To handle other errors, you should look at the HttpWebResponse.StatusCode property and handle the HTTP errors in way appropriate to your application.

I think you are talking about syntactic errors, because your code does not compile?
Try to add the missing semicolon on this line:
Console.WriteLine("error here...")
And the using-block contains no block:
using (var response = request.GetResponse())
remove the using:
var response = request.GetResponse())

Related

AggregateException "One or more errors occurred.An error occurred while sending the request."

I tried to post a file to an API rest from my WCF .Net framework 4.5. Here is my code:
public string CreateConclusion(string[] instanceUIDs)
{
var root = #"C:\";
string filename = "1.2.840.114257.1.9.1245.56421.52314.1119854.01248.dcm";
using (var client = new HttpClient())
{
var stream = new FileStream(root + filename, FileMode.Open);
using (var content =
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(stream), "fileToUpload", filename);
using (var message = client.PostAsync("https://localhost:44343/api/ConclusionReports/UploadFile", content).Result)
{
var input = message.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(input.Result) ? Regex.Match(input.Result, #"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
}
}
}
}
It doesn't work and throw an exception: "One or more errors occurred.An error occurred while sending the request."
Does anyone can help me to solve this problem? Thank you in advance
An aggregate exception can always be unwrapped to discover the real cause. Try to write your client call inside a try-catch like this:
try {
//Some risky client call that will call parallell code / async /TPL or in some way cause an AggregateException
}
catch (AggregateException err){
foreach (var errInner in err.InnerExceptions) {
Debug.WriteLine(errInner); //this will call ToString() on the inner execption and get you message, stacktrace and you could perhaps drill down further into the inner exception of it if necessary
}
}

C# - StreamReader ReadToEnd - WebException: The request was aborted: The request was canceled

My app produces the following error randomly. I havent been able to re-produce it on my machine, but on users who have installed it, it happens to them.
System.Net.WebException: The request was aborted: The request was canceled.
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
Whats odd is, ReadToEnd() cant product a WebException error (Found out by hovering over it and seeing what type of exceptions it can cause), yet from this Crash Dump it is?, To make sure I even put a WebException try catch and it still happens.
I read online a tiny bit and see it might be caused by ServicePointManager.DefaultConnectionLimit so I added that in with 1000 int value, and now im not sure if it fixed it - I havent seen any reports, but that doesnt mean its not happening.
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string s = "";
try { s = sr.ReadToEnd(); }
catch (IOException) { return "2"; }
catch (WebException) { return "2"; }
}
This is the code im using, if needed, I can provide r's values. Just know that I use quite a lot.
EDIT: I can confirm on the client's side that even with the ServicePointManager.DefaultConnectionLimit set to 1000 it still occurs.
I had a similar problem to this some time ago. Can you handle the WexException doing something like this:
public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
try
{
return (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError)
throw;
return (HttpWebResponse)ex.Response;
}
}
I borrowed the code above from the answerer here: HttpWebRequest.GetResponse throws WebException on HTTP 304
Then the first line of your code would do this:
using (HttpWebResponse resp = GetHttpResponse(r))
Found out what managed to fix it, no idea WHY, but this works:
try
{
using (HttpWebResponse resp = httpparse.response(r))
{
if(resp != null)
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string s = "";
try { s = sr.ReadToEnd(); }
catch (IOException) { return "2"; }
}
} else
{
return "2";
}
}
}
catch (WebException)
{
return "2";
}
Makes no sense, the error occurs at sr.ReadToEnd(), yet putting the Try Catch over the response() makes it fixed?

Variable not within scope using HttpWebRequest and WebResponse

I am having an issue with my variable httpRes. Basically this is the basics of a command line app that will check a set of given URL's and return their status code, i.e. unauthorized, redirect, ok etc. The problem is one of the apps within my list keeps throwing an error. So I used a try catch clause to catch the error and tell me what caused it.
Unfortunately the variable httpRes works in the try clause, but not in the catch. It keeps being returned as null. I called httpRes outside of the try/catch statement so I am hoping my scope is correct but for whatever reason the value never changes from null for the catch statement, only the try statement.
Here is the code referenced.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace URLMonitor
{
class Program
{
static void Main(string[] args)
{
string url1 = "https://google.com"; //removed internal URL for security reasons.
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url1);
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = null;
try
{
httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Website is OK");
// Close the response.
//httpRes.Close();
}
}
catch
{
if (httpRes != null)
{
if (httpRes.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Things are not OK");
//httpRes.Close();
}
}
else
{
Console.WriteLine("Please check the URL and try again..");
//httpRes.Close();
}
}
Console.ReadLine();
}
}
}
Well if you catch an exception, that would probably be because GetResponse failed, right? So you wouldn't have assigned anything to httpRes yet...
It seems to me that you should be catching WebException, at which point you can look at the response - if there is one:
catch (WebException e)
{
// We're assuming that if there *is* a response, it's an HttpWebResponse
httpRes = (HttpWebResponse) e.Response;
if (httpRes != null)
{
...
}
}
It's pretty much never worth writing a bare catch block, btw - always at least catch Exception, but ideally catch a more specific exception type anyway, unless you're at the top level of your application stack.
Personally I wouldn't bother using the same variable for both pieces of code - I'd declare the response for the success case within the try block, and the response for the failure case in the catch block. Also note that you should normally be disposing of your WebResponse, e.g.
using (var response = request.GetResponse())
{
// Use the response
}
I don't believe you need to do this if GetResponse throws an exception and you obtain the response from the exception.

Webrequest cant "escape" timeout

Hi everyone im trying to create a method that will always return a url source, if for example internet goes off it will continue working until it comes up and return the url source and so on if something else occurs. So far in my method when i "turn off" the internet and "turn it on" back procedures continue normaly but im having an issue when a timeout occurs and im "falling" in a loop i know that the while(true) is not the right approach but im using it for my tests.
So how can i skip the timeout exception and "retry" my method?
public static async Task<string> GetUrlSource(string url)
{
string source = "";
while (true)
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
hwr.AllowAutoRedirect = true;
hwr.UserAgent = UserAgent;
hwr.Headers.Add(hd_ac_lang[0], hd_ac_lang[1]);
hwr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
hwr.Timeout = 14000;
try
{
using (var response = hwr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
source = await reader.ReadToEndAsync();
if (check_source(source))
{
return source;
}
}
}
}
catch (WebException ex)
{
hwr.Abort();
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttatusCode.NotFound)
{
// handle the 404 here
return "404";
}
}
else
{
Console.WriteLine(ex.Status.ToString());
}
}
}
}
Note: i used to have the hwr.Abort(); into a finnaly clause but it didnt help.
Edit: the console is writting this message every 14 seconds as my timeout i think its something related with that.
ِAn alternative solution to get rid of timeout problem can be is to use WebBrowser component and to navigate to the required url(webbrowser1.Navigate(url);) ,and to wait in a loop until the documentcompleted event is raised and then to get the source code by this line :
string source = webbrowser1.DocumentText;
Well it seems that i found a solution that was related with the service point of the request.
So in my catch when a timeout occurs im using this to release the connection.
hwr.ServicePoint.CloseConnectionGroup(hwr.ConnectionGroupName);
I'll keep this updated.

Why is my exception handling code not handling exceptions?

I have some C# code that pulls down a remote website using the HttpWebRequest class. I'm handling errors with a try/catch, but some errors (like Webrequest and IOException) don't seem to be getting "caught" with the way I have it setup:
try
{
StartScrap("http://www.domain.com");
}
catch (Exception ex)
{
LogError(ex.ToString();
}
private void StartScrap(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseText = String.Empty;
using (StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
responseText = readerStream.ReadToEnd(); <-- I will sometimes get a Webexception error here that won't get caught above and stops the code
}
}
}
Update: There is more to the code, so maybe it is something outside of the code I posted? I am basically using this code in a Windows Application on a form that has a NotifyIcon. I'm using the Timer class to run the code at a certain timer interval. This is how I have it setup:
public TrayIcon()
{
InitializeComponent();
}
private void TrayIcon_Load(object sender, EventArgs e)
{
try
{
StartScrap("http://www.domain.com");
}
catch (Exception ex)
{
LogError(ex.ToString());
}
finally
{
StartTimer();
}
}
private void StartTimer()
{
Timer Clock = new Timer();
Clock.Interval = 600000;
Clock.Start();
Clock.Tick += new EventHandler(TrayIcon_Load);
}
What exactly do you mean by "stops the code"? Are you running in a debugger by any chance? My guess is that if you run outside the debugger - or just hit "run" again in the debugger - you'll get into the catch block with no problems. Alternatively, go into the debugger settings and change at which point the debugger steps in.
Of course, if this isn't happening in the debugger, we just need more information about exactly what you're seeing.
Could it be that LogError is throwing an exception?
Frankly speaking I am not sure what exactly happening but I will suggest you to go with ELMAH.(Error Logging Modules and Handlers)
Here is a step by step How to for ELMAH.
Nevermind, I found out I was calling the wrong function my Timer class and it was bypassing the event handler.

Categories

Resources