WebClient throw 'An exception occurred during WebClient request' - c#

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.

Related

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# how to catch Exception

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.

Generating custom exception in c#

I have tried this code to raise a manual exception
protected void test ()
try
{
throw new Exception("HI"); //line22
}
catch (Exception ex) { lblerror.Text = ex.ToString(); }
but received exception below
System.ArgumentException: HI at
Project_Test_M_Test.btnsubmit_Click(Object sender, EventArgs e) in
D:\Project\Test\M_Test.aspx.cs:line 22
I want to see error message that I have send not this.
Please use ex.Message instead of ex.ToString().
btw, its not a good idea to throw the base class Exception. please use a more specific one.
This is what you need to do, use Message property to access the error message.
protected void test ()
{
try
{
throw new Exception("HI"); // Exception message passed from constructor
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}

Get Form Name, Method Name and More Details that caused the exception

I'm trying to catch unhandled exceptions by using the following code in Program.cs File.
Im trying to create a string containing all the required information of the error.So that i can identify the Point in code where the error occurs.
My question is there a way i can get the following details from the error object after compilation and obfuscation
Name of the form from which the error occurred
The Line Number of code which triggered the error
and any other useful info to pinpoint the exact line of code
private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
string error;
error = e.Exception.Message + "|" + e.Exception.TargetSite;
}
private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string error;
error = e.Exception.Message + "|" + e.Exception.TargetSite;
}
I've written the following snippet and have been using it for all of my apps. It goes through all inner exceptions and stack traces of those exceptions that contain most of the info you need:
public static string ExceptionTree(Exception ex)
{
// find all inner exceptions
StringBuilder strbException = new StringBuilder();
do
{
strbException.AppendLine("Exception: " + ex.Message);
strbException.AppendLine("Stack Trace: " + ex.StackTrace);
strbException.AppendLine();
ex = ex.InnerException;
}
while (ex != null);
return strbException.ToString();
}
Just use > System.Environment.StackTrace
try
{
//Exception
throw new Exception("An error has happened");
}
catch (Exception ex)
{
//Open the trace
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
//Write out the error information, you could also do this with a string.Format
as I will post lower
Console.WriteLine(trace.GetFrame(0).GetMethod().ReflectedType.FullName);
Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}
Using string.Format
String.Format("An error has occurred at {0} at line {1}", trace.GetFrame(0).GetMethod().ReflectedType.FullName, trace.GetFrame(0).GetFileLineNumber());
Simply,
(e.ExceptionObject as Exception).ToString();
solve your purpose.

data type to use for an exception thrown by a validator?

I need to capture any exceptions thrown by the validator but I cannot figure out how to due it. Here is the code I have tried:
internal static class XMLValidator
{
public static void Validate(XElement elem)
{
string xsdMarkup;
using(var file = new StreamReader(Constants.Xsd))
{
xsdMarkup = file.ReadToEnd();
}
XmlSchemaSet schema = new XmlSchemaSet();
bool valid = true;
schema.Add(XmlSchema.Read(XElement.Parse(xsdMarkup).CreateReader(), (o, e) => { }));
new XDocument(elem).Validate(schema, (o, e) => { valid = false; exception = e; });
if (valid == false)
{
throw exception;
}
valid = true;
}
}
I get a "the name exception does not exist in current context" error. I'm pretty sure that the problem is that I have not given exception a data type. However I have no idea what type to use.
I tried adding var before the exception but then it's not recogonized inside of the if statement and of course var cannot be declared outside of a method
I then tried declaring exemption globally as a string and setting to e like this:
exception = e.ToString();
but then I can't throw it inside of the if statement.
How would I go about doing this?
The delegate you're using creates an XmlSchemaValidationException:
XmlSchemaValidationException exception = null;
new XDocument(elem).Validate(schema, (o, e) => { valid = false; exception = e.Exception; });
if (valid == false)
{
throw exception;
}
Well, in this particular case you probably want to create your own type of Exception to throw.
public class InvalidDataException : Exception
{ }
(There are times where it's appropriate to do something within the definition of the class, but in most cases you really don't need anything.)
Then you can do something like this:
throw new InvalidDataException("Error message goes here");
Or, you can find some existing type of exception to throw that is created by the standard library or what have you.

Categories

Resources