I'm using this code, to fetch the latest version of my app in *Form1_Load*:
string result1 = null;
string url1 = "http://site.com/version.html";
WebResponse response1 = null;
StreamReader reader1 = null;
try
{
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
request1.Method = "GET";
response1 = request1.GetResponse();
reader1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
result1 = reader1.ReadToEnd();
}
catch (Exception ex)
{
// show the error if any.
}
finally
{
if (reader1 != null)
reader1.Close();
if (response1 != null)
response1.Close();
}
The problem is that when I shut the server down the whole application is stucking and a window is popping out,saying:
Unable to connect to the remote server
Which seems legit.
Is there a way to bypass this crash (when the server is down) and break out of the version checking?
Add an additional catch block that catches the specific Exception type that you're seeing... the code will look like...
try
{
//*yadda yadda yadda*
}
catch (System.Net.WebException WebEx)
{
//*Correctly set up a situation where the rest of your program will know there was a connection problem to the website.*
}
catch (Exception ex)
{
//*Do the error catching you do now*
}
finally
{
//*yadda yadda*
}
This construction will allow you to handle WebExceptions differently from other kinds of exceptions: note that all Exceptions derive from one base class, Exception, and you can make your own for uses like this.
Related
Current Issue:
When trying to execute a search on an LDAP Connection in .NET, the server response is that a "successfull bind" has to be made beforehand, which in my prior experience with LDAP Error messages I honestly dont buy.
The code for the search is as follows:
var req = new SearchRequest("dc=test,dc=intern", "(&(sAMAccountName=*test*))", SubTree, new string[1] { "cn" });
uSearchResults = (SearchResponse)uEntry.SendRequest(req).Entries;
dblSearchResultsCount = uSearchResults.Count;
The code for the bind is the following:
try
{
connection = new LdapConnection(new LdapDirectoryIdentifier(LdapHost, LdapPort));
connection.AuthType = 2;
connection.SessionOptions.ProtocolVersion = 2;
connection.Credential = new System.Net.NetworkCredential(strUsername, strPassword);
connection.Bind();
LogEvent("Bind", 0, "Bind most likely successfull, no exception was thrown");
}
catch (Global.System.DirectoryServices.Protocols.DirectoryOperationException ServerEx2)
{
//Logging Code
return false;
}
catch (COMException ex)
{
//Logging Code
return false;
}
catch (LdapException ex)
{
//Logging Code
return false;
}
catch (Exception ex)
{
LogEvent("Bind", 0, ex.Message);
return false;
}
As you can see, I am catching every error known to man in the bind process, which as far as I know is the only way to check if the bind worked or not. The credentials, host and port are also verified to be correct.
The connection variable has no properties or functions known to me to check if a bind was successfull. The only measure I can take if the bind worked is to check if any errors occured along the way.
How can I check in the connection variable that is of the type LdapConnection if the bind was actually successfull?
The source code shows that it keeps a _bounded boolean variable, but does not expose it. So you can't check it.
But the code for binding does show that it will throw an exception if anything goes wrong. So if no exception is thrown when you call Bind(), you know the bind was successful.
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?
I am new in C# programming and I don't understand this problem.
using (WebClient wc = new WebClient())
{
try
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
HtmlResult = wc.UploadString(URI, myParameters);
}
catch(AuthenticateExeption a)
{
throw new AuthenticateExeption("I can not connect to the server...");
}
}
I am trying catch exeption using my AuthenticateExeption, but code never go to throw new AuthenticateExeption("I can not connect to the server..."); and program always down on HtmlResult = wc.UploadString(URI, myParameters); line.
Why?
You are catching the Auth Exception and then you rethrow a new version of it...
Think more like this...
using (WebClient wc = new WebClient())
{
try
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
HtmlResult = wc.UploadString(URI, myParameters);
if (some failed condition)
{
// I don't know what actually throws this, this is just for sim purposes
throw new AuthenticateExeption("I can not connect");
}
}
catch(AuthenticateExeption a)
{
// Handle the exception
Log(a.Message) // etc....
}
catch(Exception e)
{
// Handle all other exceptions
}
}
And from this point if you really wanted to throw the same exception you caught then you should first catch it, handle it, and then rethrow it for an external try/catch to furthermore handle.
You may be getting another type of exception. If you replace catch(AuthenticationException a) with catch(Exception ex) and add a breakpoint on that line then you can watch ex to see what type of exception is occurring.
Alternatively, since .Net will catch the most specific exception (i.e. most-derived type) first, so you could leave your current catch block and add an additional catch(Exception ex) block underneath it so that if an AuthenticateException occurs it will get caught, but all other exceptions will drop through to the more general case.
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.
I created a simple console application using C#. It creates an instance of a class and calls one of the class' methods. This method contains a try-catch block to catch exceptions of the type System.Net.WebException and rethrow it so that the main method can catch it and act appropriately. When I execute the compiled application the exception does not get passed to the main class and the user would never see my custom error message. Instead this screen pops up telling me that there was an unhandled WebException (it's in German but I think it can be recognized anyway ;-)):
alt text http://img29.imageshack.us/img29/4581/crapq.png
This is the method inside my class named BuffaloRouter:
public void Login()
{
string sUrl = _sUrl + "/somestuff.htm";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(sUrl);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(sUrl), "Basic", _credential);
request.Credentials = credCache;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
_sContent = reader.ReadToEnd();
response.Close();
receiveStream.Dispose();
reader.Dispose();
_parseSessionIds();
}
catch (WebException)
{
throw;
}
}
And this is the method inside my main class:
private static bool _login()
{
_router = new BuffaloRouter(_sIP, new System.Net.NetworkCredential("root", _sPassword));
try
{
Console.WriteLine("Login...");
_router.Login();
return true;
}
catch (System.Net.WebException)
{
_showErrorMessage("Could not connect to " + _sIP);
return false;
}
}
UPDATE:
I feel more than a little embarrassed and would rather not talk about it. But like a few times before I didn't relly look at what I was doing ;-)
The method inside the main class was not even invoked when I was running the app. The one that was invoked didn't have a try-catch block so that the exception thrown inside my class' method made the app do what it was supposed to, i.e. CRASH!!
I'm stupid, sorry for wasting everone's time.
If all you're doing is rethrowing the exception, then you don't need to catch it in the first place. Just remove the try...catch from your Login method.
Having done that temporarily edit your code to catch the general exception and debug it to find out what exception is actually being raised. Having done that edit the code again to catch that exception (and that exception alone).
As ChrisF has indicated you don't need to rethrow the error in the Login method. If your catch block is not running in the _login method, then I would guess your not catching the right exception.
Are you positive your getting a System.Net.WebException