Exit Method without ArgumentException - c#

i have a Cancel button on a Progressbar, which is used to Show the Progress of Uploading e-Mails,
now i want this button to Exit the method which Uploads e-Mails.
My plan, once the button gets pressed, make bool cancelUpload true.
i have been unlucky to exit the method with the use of break or simply through an if Statement.
but now i found online that i could throw an Argument Exception,
which i implemented as follows:
if (cancelUpload)
{
throw new ArgumentException("SomeText");
}
but the Problem i have with this, is that once the User clicks on Cancel, he gets an Exception, which Looks like an Error or something went wrong, is there a way to get out of the method, without it looking as though something went wrong?(similiar to ArgumentException)
Thanks a lot in Advance!
Edit: The Method (void Method) is to big to be shown,
but when i tried to return;, i got an Error in Visual Studio saying:
TargetInvocationException was unhandled Exception has been thrown by the target of invocation

Related

breakpoints not hit once evaluation timed out

I quite often stumble about code that takes too much time for the debugger to evaluate yielding to the following annoying error:
Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
Usually we can ignore this by just stepping further, making the debugger-thread snyc to our process and then re-evaluate our statement.
However when I attach my source-code to a running, managed process, I´m unable to step any further. As soon as I get the mentioned error, no breakpoints are hit at all nor will "Break all" let me break the execution and see the currently executing statement.
The yellow line produces the error mentioned above. However no breakpoint is hit after continuing, neither by using F10 ("Step over") nor F5 ("Continue"). After this I´m completely unable to debug anything in my entire codebase.
Also when I try to break debugging to see what the process is currently doing no source-code is available nor any dissambly-information, as seen here:
I have a few methods that run one by one in a loop. To show the entire progress after every such method my BackGroundWorker is notified:
void RunTests()
{
foreach(var m in methods)
{
m.Invoke(...);
backgroundWorker1.ReportProgress(1);
}
}
private void InitializeComponent()
{
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.RunTests);
}
The behaviour occurs inside the currently invoked method. I suppose it´s because of the other thread which the BackGroundWorker uses in order to notify the progress to the UI (in my case a progressbar), but that´s just a guess.
Has anyone an explanation or even better a solution which doesn´t need to re-start the process (which as I noticed yields to the exact same behaviour btw.).
This is because the exception is un-handled and Visual Studio cannot move past that line without it being handled in some manner. It is by design.
Continuing in the Visual Studio debugger after an exception occurs

Stop startActivity(intent) when going in catch block from another class

I am developing an Android Xamarin appliation in which I have an activity with a button. Some of the code in the button is this:
fsp_SellDet_New_ByItemID fsp_SellDet_New_ByItemID = new fsp_SellDet_New_ByItemID(this);
fsp_SellDet_New_ByItemID.ExecuteNonQuery(_SellID,
_ItemID,
_PodID,
_ItemSellQty,
_ItemPrice,
_ItemPricePer,
-_BaseDiscount,
-_AdditionalDiscount,
_ItemSum,
_ItemVAT,
_ItemCode,
_ItemShortName,
_ItemBrand,
_ItemIssue);
Intent i = new Intent(this, typeof(SellDet));
StartActivity(i);
Finish();
My problem is that inside the ExecuteNonQuery method I have handled exceptions in a try and a catch block like so:
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return;
}
Even tho I am using "return;", Android still opens the next activity so I cannot really see what the exception was, since by the time the AlertDialog shows up, the next activty is already opened.
Can you give me some advices on how to make it so if I receive an exception in the ExecuteNonQuery method, an AlertDialog will popup and it won't go in the next activty.
Or maybe can you tell me how to make it, so that you will have to press "OK" on the alertDialog and then it will go in the activty. Remember, the AlertDialog is inside the executeNonQuery method in the newly created class, not in the button method..
Thank you in advance
There are many ways to fix this issue. In no particular order (let me know if you need to see coded examples for any of them):
Do not catch the exception in ExecuteNonQuery() and instead catch it within the calling method
Have ExecuteNonQuery() return a bool, false if an exception occurs and true if not. Then put an if check around your StartActivity code
Pass an Action into your ExecuteNonQuery() that would run within the empty delegate you are passing to _dlgAlert.SetButton("OK", delegate { /* Passed in Action executes here */ });, the Action would have your StartActvity code in it

UnauthorizedAccessException can't be caught

I've recently run into this problem, and it doesn't make sense.
the following snippet is real:
try
{
File.Create(targetFile);
//File.WriteAllText(targetFile, $"test {DateTime.Now.ToString()}");
}
catch (UnauthorizedAccessException uaex)
{
}
I have checked it step by step, as soon as i get with the debugger to the "File.Create()" method, the exception rises, and it doesn't enter the catch block, also, if i remove the try-catch, it doesn't bubble up to the calling of the method which contains this.
Anyone got any idea why the try-catch and the bubbling doesn't work?
ps. The location where I am trying to create the file is write protected on purpose, this is just a way to check if it is.
I've made a mistake.
The exception is actually being caught, if you put anything in the catch block, it does execute.
To be fair the debugger confused me, by showing the exception pop-up right at the calling of the method, but that was solved by restarting the IDE

Response.write in application_error not working?

Ok, I have a weird problem and can't find anything about it online. I'm trying to get custom application-level error handling working in ASP.NET. I have customErrors turned off in the web.config with the hopes of handling everything in application_error. Bear with me...
My code in global.asax is very simple:
void Application_Error(Object sender, EventArgs e) {
HttpContext.Current.Trace.Write("ERROR MESSAGE");
Response.TrySkipIisCustomErrors = true;
var error = Server.GetLastError();
HttpContext.Current.Response.Write("ERROR MESSAGE");
HttpContext.Current.ClearError();
}
I created a simple aspx page and threw an error in Page_Init or Page_Load, and everything worked as expected, i.e.: I see "ERROR MESSAGE" on a blank page when an error occurs.
Now I dynamically add some user controls to that aspx page and everything renders as expected. If I then throw an error from INSIDE one of the controls, I only get a blank white page. "ERROR MESSAGE" does not appear.
Now I know that application_error is still firing because when I remove the call to ClearError(), I get a Yellow Screen Of Death. Also, I can execute a Server.Transfer in there and that works fine. But nothing will come out for Response.Write.
This goes further: I can set Response.StatusCode, but a Response.Redirect will error out (and thus throw me into an infinite loop). Trying to write to the Event Log also errors out, but instead of throwing a new error, it throws the original, i.e.: "Input string was not in a correct format." when I try to convert a string to a number. As mentioned, Response.Write doesn't do anything, though it does not throw an error.
So looking at my trace log, in the second case (exception inside dynamically added user control) I see a full control tree and the error occurs right after Begin Render. In the first case, the tree is empty and the error is thrown either after Init or Load. Both times, trace.axd reports Unhandled Execution Error.
When I move the throw inside the control to the control's constructor or OnInit, things work as expected. When I move it to OnLoad or Render, it gets goofy.
So I'm wondering if at some point the Response object loses certain functionality. I've tried all sorts of permutations, from syntax (using HttpContext.Current.Response vs Context.Response vs pulling the Response object from the "sender" parameter), to moving the ClearError() or Response.Clear(), etc methods around, etc. I've tested the Response object for "null-ness" as well, and it never reports a null. I can set some response properties (http status code) but not others.
I'm using IIS7.5 integrated mode (.NET v4), but experienced similar problems when I tried Classic mode.
So I'm trying to solve this mystery, obviously, but my goal is to ultimately handle all errors, no matter what point in the asp.net lifecycle they occur, and to be able to write out some information from the handler (ie application_error).
Handled unhandled exceptions using this approach. Custom error is off in web.config.
All 3 options work.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Response.TrySkipIisCustomErrors = true;
this.Server.ClearError();
this.Server.GetLastError();
//DO SOMETHING WITH GetLastError() may be redirect to different pages based on type of error
//Option 1:
Response.Write("Error");
//Option 2:
Response.Redirect("~/Error.aspx");
//Option 3:
this.Server.Transfer("~/Error.aspx");
}

Error in CanExecute() - how to get rid of dialog?

I'm trying to handle exceptions in a dialog so that if any exception occurs, the dialog will be closed and the application will not crash. As you can see, I use a simple try-catch block:
IDialogView dialog = null;
try
{
if (_dialogViewModel == null)
{
dialog = ViewFactory.SomeDialog();
_dialogViewModel = new DialogViewModel(dialog);
_dialogViewModel.LoadData();
}
_dialogViewModel.ShowDialog();
}
catch (Exception ex)
{
if (dialog != null)
dialog.Close();
_dialogViewModel = null;
MessageBox.Show("Sorry, there was an error in the dialog.", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
The problem happens when an error occurs in button's CanExecute() event handler. Error is successfully caught, but when I show the MessageBox to the user, CanExecute() executes again, and so the error happens again. In the end it results in application crash.
I've googled some info, and it were said to make sure that there is no exceptions in CanExecute() event handler. But something like this can happen somewhere else, and that's why I want to simply catch ALL exceptions in the dialog entry point without working with every method.
So, my question is: how to destroy the dialog so that after exception catch it won't show again anymore? Close() didn't work, because before closing it still calls CanExecute().
As you found when you googled, you should make sure that a CanExecute handler is a) lightweight and b) never throws an exception. You are running into the main reason for this: a CanExecute will be run repeatedly, and automatically, by the framework. It will run when focus changes, on input events, when databindings change, and in response to a number of other reasons that you have little to no control over.
The problem is: you do have an error, and that error is occurring repeatedly. That means you can choose between crashing, or showing the dialog repeatedly. Or, you can do something about the error.
Your answer: fix the error.
(Your handler as it stands is fine for your other errors. Leave it there. But this particular error, you need to fix right away.)

Categories

Resources