XmlDocument.LoadFromUriAsync blocks on no internet connection in Metro-ui Style App - c#

I am using this code to get an xml from an uri
try
{
doc = await XmlDocument.LoadFromUriAsync(new Uri(apiRequest));
}
catch(Exception e)
{
return false;
}
The problem is that the function isn't throwing any exception when not connected to the internet, and the whole program just blocks. It does throw an exception if I set the uri to something invalid like "http://notanactualluri.com" or to a valid uri that doesn't contain an xml.

Related

Check if .NET LDAP Bind was successfull

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.

WebClient throw 'An exception occurred during WebClient request'

I know that question has been ask a lot in the internet, but yet i didn't found a satisfying answer.
private string LocalSqlDriverDownloader()
{
ProgBar prograssBar = new();
string sqlLocalDBUrl = "https://download.microsoft.com/download/7/c/1/7c14e92e-bdcb-4f89-b7cf-93543e7112d1/SqlLocalDB.msi";
string fileName = "SqlLocalDB.msi";
string directory = $#"{Path.GetPathRoot(Environment.SystemDirectory)}Download"; // C:\Download
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using WebClient webClient = new();
webClient.DownloadProgressChanged += (s, e) =>
{
Application.Current.Dispatcher?.Invoke(() =>
{
(prograssBar.DataContext as PrograssbarWindowViewModel).PrograssBarValue = e.ProgressPercentage;
});
};
webClient.DownloadFileCompleted += (s, e) =>
{
prograssBar.Close();
};
string downloadPath = $#"{directory}\{fileName}";
try
{
webClient.DownloadFile(sqlLocalDBUrl, downloadPath);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
prograssBar.ShowDialog();
return directory;
}
I don't have a clue why this throw to me an exception, I tried to download other files, http and https, it doesn't seams to have any difference to the outcome.
The given exception:
System.Exception
HResult=0x80131500
Message=An exception occurred during WebClient request.
Source=PulserTesterMultipleHeads
StackTrace:
at PulserTesterMultipleHeads.Models.MainTestPageMV.LocalSqlDriverDownloader() in C:\Project\Models\MainTestPageMV.cs:line 955
at PulserTesterMultipleHeads.Models.MainTestPageMV.LocalSQLDriverInstaller() in C:\Project\Models\MainTestPageMV.cs:line 905
at PulserTesterMultipleHeads.Models.MainTestPageMV..ctor(Action closeAction, String catalogDesc) in C:\Project\Models\MainTestPageMV.cs:line 70
at PulserTesterMultipleHeads.UserControls.MainTestPage..ctor() in C:\Project\UserControls\MainTestPage.xaml.cs:line 31
Remove this whole construct:
try
{
webClient.DownloadFile(sqlLocalDBUrl, downloadPath);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
and replace it by
webClient.DownloadFile(sqlLocalDBUrl, downloadPath);
Then you will still get an error, but at least you will be able to see what is wrong and where. The exception and maybe the inner exception will tell you in no uncertain terms what is wrong. The stack trace will tell you where it went wrong.
As it is, you have added this block and all it does is it removes the information you need to find out what is wrong. We cannot tell you what went wrong specifically, because your code intentionally removes it.

How to handle specific HttpClient errors

When the HttpClient throws an exception trying to get a page it returns a HttpRequestException. This exception doesn't really have anything to categorize the error apart from the message so the only way i can see to handle errors is like so:
try
{
HttpResponseMessage response = await client.GetAsync("http://www.example.com/");
// ...
}
catch (HttpRequestException e)
{
if(e.Message == "Name or service not known")
{
HandleNotKnown();
return;
}
if(e.Message == "Some other specific message")
{
HandleOtherError();
return;
}
// ... etc
}
I don't like doing this because I feel like at some point the error text could change in an update and break my code.
Is there a better way to handle specific errors with HttpClient?
The HttpRequestException inherits from Exception and so it has the InnerException property
Gets the Exception instance that caused the current exception.
So check this Exception for more details.

Is there a way to catch the "An unexpected network error occurred" exception specifically, or to manually throw it (for testing)?

Background:
I have a CSV file containing a list of filepaths. Each file needs to be copied from the filepath to a new location over the network. My program handles this fine, however there are occasional network blips, which throw an IOException with the message "An unexpected network error occurred.". When this happens, I want to retry a few times (with a short delay) before giving up (if a retry is successful, the program would continue as normal). At the minute, I am catching IOException and using the Message value to determine whether to retry or throw, however it doesn't appear to be retrying as expected. I assume this is because the message I'm comparing isn't quite the same, but I can't think of how I can verify as the problem is occasional.
Questions:
Is there a way to replicate this error (without just creating a new IOException with the relevant Message)?
Is there a better way of isolating this particular error?
Sample Code:
private static void CopyFile(FileInfo file, string destinationFilepath)
{
try
{
file.CopyTo(destinationFilepath);
}
catch (IOException e)
{
var saved = false;
if (e.Message == "An unexpected network error occurred.")
{
saved = RetryCopyFile(file, destinationFilepath);
}
if (!saved)
{
throw;
}
}
}
private static bool RetryCopyFile(FileInfo file, string destinationFilepath)
{
var saved = false;
var maxRetries = 20
var retries = 0;
while (!saved && (retries < maxRetries))
{
try
{
file.CopyTo(destinationFilepath, true);
saved = true;
}
catch (Exception)
{
Thread.Sleep(10000);
retries++;
}
}
return saved;
}

c# application is crashing when the server is down

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.

Categories

Resources