LINQPad: Assert() prints "Fail:" and continues instead of breaking - c#

In LINQPad, Debug.Assert() and Trace.Assert() from the System.Diagnostics namespace don't work as expected.
Instead of breaking - i.e. popping up a message box or whatever else happens to be configured for <trace> - they simply print "Fail:" or "Fehler:" to the output window and let the program continue on its merry way. In other words, instead of a noisy, unignorable explosion there are only near invisible micro-farts that intersperse "Fail:" into the textual output.
Is there any way of getting Assert() to revert to the default behaviour under LINQPad?
Alternatively, is there a simple way of mocking a Trace.Assert() so that failure results in a noisy explosion (i.e. exception, message box, whatever) and the source of the failure is pinpointed in the form of a line number or similar?
My unit tests are based on Trace.Assert(), which makes them totally useless if the function cannot break the program at the point of failure.
In Visual Studio everything works normally but not in LINQPad. I haven't fiddled with any system-wide settings but I did install Mono at some point in time. I went through all settings in LINQPad with a fine comb but to no avail. The LINQPad version is 4.57.02 (non-free), running on Windows 7 Pro (German) and Windows 8.1 Pro (English).
I googled high and wide but the only thing I could find is the topic Trace.Assert not breaking, neither showing the message box here on Stack Overflow. Its title certainly looks promising but the answers therein don't.
P.S.: I tried mocking by adding
class Trace
{
public static void Assert (bool condition)
{
if (!condition)
throw new Exception("FAIL!");
}
}
to the LINQ script and setting a breakpoint on the throw statement. Clicking on the relevant call stack entry in LINQPad's debugger takes me to the relevant source line, so this sort of works. However, I couldn't find an equivalent to FoxPro's SET DEBUG ON for invoking the debugger directly from the source code instead of having to set a breakpoint on the throw...

To answer the second half of your question, i.e., how do you get the LINQPad debugger to break when an exception is thrown, the answer is to click either of the 'Bug' icons on the toolbar.
Click Break when exception is unhandled (red bug) to make your query break whenever an unhandled exception is thrown.
Click Break when exception is thrown (blue bug) to make your query break whenever an exception is thrown, whether or not it is handled.
You can get LINQPad to make either setting the default by right-clicking and choosing Set as default. (Doing so forces the debugger to always attach to your queries, which incurs a small performance cost.)
As to why Debug.Assert(false) doesn't display a dialog, this is because this behavior hasn't been implemented in LINQPad. You could implement this easily as an extension, by adding the following code to My Extensions:
public class NoisyTracer : TextWriterTraceListener
{
public static void Install()
{
Trace.Listeners.Clear();
Trace.Listeners.Add (new NoisyTracer (Console.Out));
}
public NoisyTracer (TextWriter writer) : base (writer) { }
public override void Fail (string message, string detailMessage)
{
base.Fail (message, detailMessage);
throw new Exception ("Trace failure: " + message);
}
}
Then, to enable, write your query as follows:
NoisyTracer.Install();
Debug.Assert (false);

Related

VS 17 breaking on all exceptions

Visual Studio 2017 is (kind of suddenly) breaking on all exceptions. That means, if I deactivate them in the exceptions settings (pressing CTRL + ALT + E while debugging), the debugger still breaks on them. I don't know wether this is just a bug of VS I can't change and therefore have to live with, or wether there is a simple solution for it.
This is the exception settings window:
and this the exception VS breaks on:
By the way, I also tried that beautiful minus (nothing happens if I press it) or adding a impossible condition (VS still broke on the exception).
I also tested other exceptions (by simply throwing them), which I deactivated before, and they get thrown as well and I tested the same issue in other projects, where it appeared as well:
I actually even put the whole stuff into a try catch statement but VS still breaks:
InitializeComponent ();
try
{
var t = new Thread (() =>
{
while (!IsHandleCreated) {} //It breaks here (similiar to the screenshots)
while (true)
Invoke (new Action (() => Size = new Size ()));
});
while (true)
{
t.Start ();
Thread.Sleep (100);
t.Abort ();
}
}
catch (ThreadAbortException) { }
It doesn't appear in other IDEs (like Rider) on my PC and doesn't occurr on other PCs in VS. It didn't always occurr on my PC, it just started recently and only in debugging mode. And if I continue the execution (with F5) it just continues normally.
EDIT As I put the try catch inside the thread it behaved a little bit different (I'm sorry for putting pictures in here, but I think they're more expressive in that case):
Can anybody explain this behaviour?
EDIT It seems to be normal for ThreadAbortExceptions to break again at the end of a catch statement. However, VS still shouldn't break on this exception at all.
I was having a similar problem.
I fixed it by unchecking "Break when exceptions cross AppDomain or managed/native boundaries" in Tools > Options > Debugging > General
I fixed it by unchecking Enable Just My Code in Tools > Options > Debugging > General
I can't confirm whether this happens with other project types, but it happens to me consistently with (Visual Studio Tools for Python) VSTP.
Although it is less than satisfactory, it can at least silence the exceptions and allow you to continue working in peace until a better solution surfaces. In my case, it was nearly impossible to debug my code, since StopIteration breaks during every iteration.
Select Debug > Windows > Exception Settings or press Ctrl-Alt-E. Y
Right click anywhere on the Window and select Show Columns > Additional Actions. You will have an "Additional Actions" column appear if it doesn't already.
Right click on a specific exception you want to silence or click the top level checkbox to select an entire category of exceptions, i.e. Python Exceptions. Click Continue When Unhandled in User Code.
Repeat for each additional exception or category of exceptions.
I know it's a little late for this, but ThreadAbortException is different from all other exceptions, and requires some special handling, otherwise it is automatically re-thrown at the end of all catch blocks if you don't actually handle it the way it's supposed to be handled.

Visual Studio breaking when it should not be... Anyone know why?

A little background. I write many data conversion apps for various platforms, and am no novice to using breakpoints, exception handling etc.
I have a range of conversion type methods that will take an object input (usually used directly out of a sqldatareader) and convert it to a specific type output, with a default returned if unable to do a direct conversion. Here is an example:
public int? GetNullInt(object obj)
{
try
{
int blah = Convert.ToInt32(obj);
if (blah == 0)
return null;
else
return blah;
}
catch (Exception ex)
{
return null;
}
}
In this case I want to return null if the object is either not an int or is 0.
Now.. the problem is that even tho this code is wrapped in a try/catch, for some reason in this one single application (windows forms, C#, .NET 4.5.2), Visual Studio is breaking when the input string is not in an expected format. The break asks me if I want to break on this type of exception (check box unchecked), but no matter what settings I set, it keeps breaking, even though I am catching the exception (can set a breakpoint in the catch and "continue" to it, so I know the try/catch is functioning). I have "Reset to default" the exception settings in VS, still no joy.
Now I know I can change this method slightly to use int.TryParse (and I am going to do that now), but that does not solve the underlying problem of why VS is breaking in the first place, since this was NOT an unhandled exception.
Any ideas?
(here is a screenshot of the break)
Photo of the break happening at runtime
In visual studio you have new window called Exception settings.
This window appears after pressing Ctrl + Alt + E.
In this window you can set the Exception handling.
You code is working fine in my Visual Studio Desktop For Express 2015.
You just need to uncheck all the things in this window.
Please refer an Image.
You can refer below post, this is exactly same which you want.
Visual Studio 2015 break on unhandled exceptions not working
From the look of your screenshot you do not have "Just My Code" enabled in the debugger settings
If that setting is not enabled you can't use the "Only catch unhandled exceptions" feature of visual studio.

Visual Studio: edit-and-continue on handled exceptions?

Here's a code reproducing the behavior I'm expecting to get:
static void Main(string[] args)
{
// try // #2
{
string x = null; // #1
AssertNotNull(x, nameof(x));
}
// catch (ArgumentNullException) { } // #2
Console.WriteLine("Passed.");
Console.ReadKey();
}
[DebuggerHidden]
public static void AssertNotNull<T>(T arg, string argName) where T : class
{
if (arg == null)
throw new ArgumentNullException(argName);
}
The behavior is the same for any VS starting from VS2008 (did not check on earlier versions).
If you run it under debug (using a standard debugging settings) you're not allowed to continue until you fix the code (using the EnC). Hitting F5 will just rerun assertion due to [DebuggerHidden] and "Unwind stack on unhandled exception" setting combo (setting is enabled by default).
To fix the code, just replace the #1 line with object x = "", set the next statement to it and hit F5 again.
Now, enable "break when thrown" for the ArgumentNullException and uncomment the lines marked with #2.
The behavior changes: you're stopped on assertion again, but the stack does not unwind (easy to check with CallStack window). F5 will continue from the place the exception was thrown.
Ok, so... now the question is:
Is there any way to enable auto stack unwinding when breaking on handled exceptions?
Hidden VS option, existing extension or (maybe) API that can be used from my own extension?
UPD: To clarify the question: I want to break at the line with failed assertion, edit the code with edit and continue, set next statement to the fixed code and continue the execution.
As it works if the exception is not caught down the stack.
UPD2 As proposed by Hans Passant: Posted an suggestion on UserVoice. Feel free to vote:)
and uncomment the lines marked with #2
This is the critical part of your question. You changed more than one thing, the critical change is that you altered the way the stack is unwound. The debugger option you like is titled "Unwind stack on unhandled exception". Problem is, there is no unhandled exception anymore. Your catch clause handles it and it is now the CLR that unwinds the stack.
And it must be the CLR that does the unwinding, the debugger does not have an option to do it on the first-chance exception break that you asked for. And SetNext can't work at that point. Which, if I interpret the question correctly, you would really like to have since what you need to do next is busy work, single stepping through the catch block is not enormous joy.
Although it is not implemented, I think it is technically do-able. But only because I'm blissfully unaware how much work the debugger team will have to do. It is a good ask to make E+C work better, you can propose it here. Post the URL to your proposal as a commnent and good odds it will get a bunch of votes. I'll vote for it.
To clarify the question: I want to break at the line with failed
assertion, edit the code with edit and continue, set next statement to
the fixed code and continue the execution.
Open the "Exception Settings" Menu (Debug > Windows > Exception Settings)
Under "Common Language Runtime Exceptions", check the box for "System.ArgumentNullException". (Or check them all, whatever you're looking for.)
It should now break whenever a System.ArgumentNullException is thrown, regardless if it will be caught in a catch block.
However, you cannot edit and continue active statements. If you try to modify your assertion line, you'll see something like this:

Debug.Assert not always working in c#

I have a strange problem with Asserts being ignored. You can reproduce it with this minimal example. I am wondering why this problem occurs and how to face it:
public class TestAssert
{
public string EmptyString
{
get
{
System.Diagnostics.Debug.Assert(false);
return string.Empty;
}
}
Dictionary<string, object> dict = new Dictionary<string, object>();
public void ShowAssertIgnored()
{
var foo = dict[EmptyString];
}
}
You can see that the Debug.Assert(false) is ignored even though the property is evaluated. Just call
var test = new TestAssert();
test.ShowAssertIgnored();
and you should see what I mean (also shown on the image).
The code is compiled and run in Debug (other asserts work fine!), 32 bit, x86 + AnyCPU, VS2012 professional, .Net Framework 4
Edit:
The project is a console application and I was running it for several times in a row. Having a breakpoint before System.Diagnostics.Debug.Assert(false); most often a messagebox appears. But not always: When I just retry the same situation several times I sometimes see the result in the console.
To say it again: I can reproduce non-deterministic behaviour in the VS2012 debugger!
If you read the docs, you'll see that Debug.Assert isn't designed to throw.
Typically, the Assert(Boolean) method is used to identify logic errors during program development. Assert evaluates the condition. If the result is false, it sends a failure message to the Listeners collection. You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.
When the application runs in user interface mode, it displays a message box that shows the call stack with file and line numbers. The message box contains three buttons: Abort, Retry, and Ignore. Clicking the Abort button terminates the application. Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicking Ignore continues with the next instruction in the code.
If running in an UI environment, it may trigger throw-like behaviour that is defined in the listeners that the UI environment/test-runner sets up.
So, in short, Debug.Assert(false) won't halt your application but its listeners might.
Assuming that there is no UI here... If you want your code to fail, then you'll need to write your own TraceListener:
public class MyTraceListener : TraceListener
{
public override void Write(string msg)
{
throw new Exception(msg);
}
public override void WriteLine(string msg)
{
throw new Exception(msg);
}
}
and add it to the listeners collection:
Debug.Listeners.Add(new MyTraceListener());
Have you checked your project settings to define the DEBUG constant? The Debug.Assert() methods have the [ConditionalAttribute("DEBUG")] attribute, which means, they will by ignored during compilation, if the "DEBUG" constant is not defined.
That's an expected behaviour, Debug.Assert() works in debug build only:
By default, the Debug.Assert method works only in debug builds. Use
the Trace.Assert method if you want to do assertions in release
builds. For more information, see Assertions in Managed Code.
https://msdn.microsoft.com/en-us/library/kssw4w7z(v=vs.110).aspx
use Trace.Assert() if you want it working in release as well.

How to NOT breaking on an exception?

I've got something like this:
try
{
instance.SometimesThrowAnUnavoidableException(); // Visual Studio pauses the execution here due to the CustomException and I want to prevent that.
}
catch (CustomException exc)
{
// Handle an exception and go on.
}
anotherObject.AlsoThrowsCustomException(); // Here I want VS to catch the CustomException.
In another part of code I have multiple occurencies of situations where CustomException is thrown. I would like to force the Visual Studio to stop breaking on instance.SometimesThrowAnUnavoidableException() line cause it obscures the view of other places where I'm interested in breaking on CustomException.
I tried DebuggerNonUserCode but it is for a different purpose.
How to disable Visual Studio from catching particular exception only in a certain method?
You can use custom code to do this in two steps.
Disable automatic breaking on the CustomException exception.
Add a handler for the AppDomain.FirstChanceException event to your application. In the handler, if the actual exception is a CustomException, check the call stack to see if you actually want to break.
Use the Debugger.Break(); to cause Visual Studio to stop.
Here is some example code:
private void ListenForEvents()
{
AppDomain.CurrentDomain.FirstChanceException += HandleFirstChanceException;
}
private void HandleFirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
Exception ex = e.Exception as CustomException;
if (ex == null)
return;
// option 1
if (ex.TargetSite.Name == "SometimesThrowAnUnavoidableException")
return;
// option 2
if (ex.StackTrace.Contains("SometimesThrowAnUnavoidableException"))
return;
// examine ex if you hit this line
Debugger.Break();
}
In Visual Studio, go to debug->exceptions and turn off breaking for your CustomException by unchecking the appropriate checkbox, then set a breakpoint in the code (probably on the catch statement) on the places you actually want to break on.
If you want Visual Studio to stop breaking on all exceptions of a type, you have to configure the behavior from the Exceptions window.
Full instructions are here, but the gist is to go to the Debug menu and choose exceptions, then uncheck the items you dont want the debugger to break on.
I don't think there is a way to avoid a specific method using this technique, but maybe the better question is "why is this throwing an exception?"
You could add a set of #IF DEBUG pre-processor instructions to avoid running the problematic sections of code.
You can disable stepping altogether by placing the DebuggerStepThrough Attribute before the method.
As this disables stepping in the whole method, you may isolate the try-catch into a seperate one for debugging purposes.
I did not test, but it should not even break in that method when en exception is thrown. Give it try ;-)
See also this SO thread
You can't simply disable Visual Studio from stoping in a particular place of code. You can only prevent it to stop when particular type of exception is thrown but that will affect all places where such exception occurs.
Actually you can implement custom solution as suggested by 280Z28.

Categories