Is there a way to prevent Visual Studio from breaking on exceptions in a specific method? - visual-studio

I know I can control the way Visual Studio handles exceptions according to their type and to the fact that they're eventually caught using the "Exception" dialog.
However, I've got a library that's internally throwing (and catching) an ArgumentOutOfRange exception when I'm calling a specific method. The exception is thrown (and caught by the library) maybe 1% of the time, but I'm calling this method a lot. The editor says it's by design (and indeed, the design they've chosen makes sense).
The thing is that I don't want Visual Studio to break each time the exception is thrown.
I don't want to stop breaking on ArgumentOutOfRange exceptions, as I may have some in my code and want to break on those.
I don't want to enable "just my code" debugging because I'm concerned about the exceptions thrown outside of my code (notably for performance reasons)
Is there a way to achieve this? I've been looking into attributes (such as DebuggerStepThrough), but haven't find something adequate yet.
Any hints on how to do this ?

I don't want to enable "just my code" debugging
Yeah, stop there right now. That is exactly the feature you need to not get the unwanted debugger breaks. If you don't want to know about somebody else's crappy code then flip that checkbox back on.
This invariably goes off the rails when programmers use exceptions for flow control. A very common crime. It takes two of them to turn that into a mess that turns a debugging session into a very tedious click nightmare. When you need the debugger feature that breaks on the first-chance exception then you basically lost if somebody else needed that as well.
Everybody hopes that they can magically use the [DebuggerNonUserCode] or [DebuggerHidden] or [DebuggerStepThrough] attributes to make that problem disappear. It doesn't. The other programmer did not think his code was unimportant enough to deserve those attributes. And, well, it wasn't because there's always a bug hidden in code that uses try/catch-em-all code. Pokémon code.
So Microsoft had to find another way to help programmers deal with crappy library code. They did. Tick that checkbox, bam, solved. Nothing you can do about that crappy code anyway, other than sending a nasty-gram to the author. Don't let us or Microsoft slow you down doing that as well, y'all have to get along to create a product that people like to use.

I think it's not possible in visual studio but it certainly is in WinDbg.
See for example http://blogs.msdn.com/b/alejacma/archive/2009/08/24/managed-debugging-with-windbg-breaking-on-an-exception-part-1.aspx
On a side note it seems that starting with visual studio 2010 you can load and use WinDbg extension DLLs directly providing aditional functionality (including possibly the one that you need) but I haven't tried this yet - see for example http://www.dotnetcurry.com/ShowArticle.aspx?ID=648

What you can do is use Concord, the debug engine that ships with Visual Studio (starting with version 2012). It's quite extensible through a nice managed API (and deployable using vsix technology), but it's not fully documented.
Concord has the concept of debug monitors, that we can hook using the IDkmDebugMonitorExceptionNotification Interface
The cool thing is this interface can monitor all exceptions thrown. It can also "suppress" any detected exception event, which is exactly what we need.
What I suggest is to start with the Hello World sample: . Download it, and make sure it runs as expected for you.
Now, just modify HelloWorld.vsdconfigxml like this:
<!--TODO: If you copy the sample, ensure to regenerate the GUID in this file -->
<!-- 1. change component level to something higher than 40500 -->
<ManagedComponent
ComponentId="51736b11-9fb4-4b6d-8aca-a10a2b7ae768"
ComponentLevel="40501"
AssemblyName="HelloWorld">
<!-- 2. change class full name to HelloWorld.ExceptionHandler, for example -->
<Class Name="HelloWorld.ExceptionHandler">
<Implements>
<InterfaceGroup>
<NoFilter/>
<!-- 3. change supported interface -->
<Interface Name="IDkmDebugMonitorExceptionNotification"/>
</InterfaceGroup>
</Implements>
</Class>
</ManagedComponent>
Then, just create an ExceptionHandler.cs class and put something like this in there:
public class ExceptionHandler : IDkmDebugMonitorExceptionNotification
{
private bool _unhandledDetected;
// we're being called!
public void OnDebugMonitorException(DkmExceptionInformation exception, DkmWorkList workList, DkmEventDescriptorS eventDescriptor)
{
if (_unhandledDetected)
{
// this will cause the program to terminate
eventDescriptor.Suppress();
return;
}
if (exception.ProcessingStage.HasFlag(DkmExceptionProcessingStage.Unhandled))
{
_unhandledDetected = true;
}
else if (exception.ProcessingStage.HasFlag(DkmExceptionProcessingStage.Thrown))
{
if (SuppressException(exception))
{
eventDescriptor.Suppress();
}
}
}
// should we suppress a thrown (1st chance) exception?
private bool SuppressException(DkmExceptionInformation exception)
{
// implement any custom logic in here, for example use the exception's name
if (exception.Name == typeof(ArgumentOutOfRangeException).FullName)
{
// for example, use the module (assembly) name
var clrAddress = (DkmClrInstructionAddress)exception.InstructionAddress;
var clrModule = clrAddress.ModuleInstance;
if (clrModule.Name == "TheUglyOne.dll")
return true; // we don't want this one!
}
return false;
}
}
When you run the project, you should see all exceptions being monitored (regardless of your 'just my code' and/or exception triggers settings), so what you just need to do is implement some logic to suppress the ones you really don't want to see. I've not checked but I suppose you could build your logic using custom attributes as the Dkm classes provide quite a lot of .NET metadata information.
Note: as you can see, there is some trickery to make sure the program will terminate normally.

Related

Hide test from Visual Studio Test Explorer

Using Fact(Skip = "Manual Only") is not entirely satisfactory because, if I click directly on the test to run it, it's still ignored.
I want it to not appear in Test Explorer but I can still run it by clicking on it. Is this possible?
Nice trick from Jimmy Bogard is to use the fact that Skip is writable and react to something in the environment:
public class RunnableInDebugOnlyAttribute : FactAttribute
{
public RunnableInDebugOnlyAttribute()
{
if (!Debugger.IsAttached)
Skip = "Only running in interactive mode.";
}
}
(Aside from that, no xUnit does not have an [Interactive]; the closest thing is `[Trait("Interactive","True")] and use that to either use the trait grouping in test explorer to remove them.
Finally, a 'cheat' way is to use TestDriven.Net, which doesnt care if there is an attribute (along with lots of other facilities).

Drupal, entity_metadata_wrappers and debugging

For handling entities in Drupal I'm using Entity Metadata Wrappers (the "Drupal way").
It's really easy to start coding and see all the advantages it has... except when you get a fatal error and you are not clear where it comes from.
This is what the database log shows:
EntityMetadataWrapperException: Unknown data property
field_whatever. at EntityStructureWrapper->getPropertyInfo()
(line 335 of
/var/www/html/sites/all/modules/entity/includes/entity.wrapper.inc).
Sadly, many times that "field_whatever" is "nid", "uid" or some very common property, so it's name is spread all over my code, which makes me difficult to get to the origin of the error.
I'm currently doing this:
Write a tiny piece of code and then run to see if something fails.
Using getPropertyInfo when handling entities with "not so common" fields.
Loosing hair.
What is worst is that sometimes the error does not appear when you are coding, but a week later. So it could be anywhere...
Is there any way of handling entity metadata wrapper errors better? Can I get better information in the database log and not just a line? A backtrace maybe?
Thanks.
Well, having the devel module active (just to see the nice krumo message) we can do something like this inside our module:
<?php
set_exception_handler('exception_with_trace');
function exception_with_trace($e)
{
dpm($e->getTrace());
}
That will return the backtrace error of the exception thrown by the entity metadata handler on the next page load (some page in your site where everything is running fine).
Also you can set the exception handler exclusively and more elegant just for some pages or some users with some role... or when some parameter in the url is met, or when in some state of your Drupal site is met (ex. when a bool persistent variable 'exception_with_trace' is true). Even, under certain conditions and control, you can use it in production too.
If the site does not work "at all" you can include it in your settings.php file, but instead of printing the trace, you must write the trace to a file and watch the trace in a different context (not Drupal but some php file).
If exceptions are too long and are causing memory problems then getting the trace as string is also possible. See http://php.net/manual/es/exception.gettraceasstring.php
Hope that helps.

Motorola MC65 - EMDK .NET 2.6 - E_SCN_READTIMEOUT using ScanWait()

I'm looking to integrate the Barcode2 class in the EDMK 2.6 library into our existing Barcode scanning interface.
I've wired the example code up to our interface method StartScan() and always get E_SCN_READTIMEOUT as the result even though the code seems to be responding to the scan. (the breakpoint at if (scan.Result == Results.SUCCESS) is hit in response to the scan
public void StartScan()
{
if (!barcode.IsScanPending)
{
ScanData scan = barcode.ScanWait(2000); // 2 second timeout
if (scan.Result == Results.SUCCESS)
{
if (scan.IsText)
{
textbox1.Text = scan.Text;
}
}
}
}
The result is always E_SCN_READTIMEOUT, I suspect this may be a conflict with DataWedge 3.4 running on the device, but the functionality of the scanner and triggers seem to be dependent on it.
Getting barcode scans to the clipboard using DataWedge is not an option for us, is there a way to get the library to function despite DataWedge(assuming that is causing the read timeouts)?
The DataWedge application did need to be disabled, (this can be done programmatically via the datawedge API from Motorola, Thanks Abdel for the hint here!).
https://docs.symbol.com/ReleaseNotes/Release%20Notes%20-%20DataWedge_3.3.htm
A little background on our Windows Mobile application for reference, we have a hardware singleton that contains interfaces for all hardware components and loads related types and assemblies via reflection. If we referenced types directly the code above worked.
The end solution ended up being to use the Symbol.Barcode library instead of Symbol.Barcode2.

Language Service: ParseReason.Check never called after migrating to VS2010

I just migrated my language service from VS2008 to VS2010. Everything works fine except for one important thing: I no longer get LanguageService.ParseSource invoked for ParseReason.Check. It do get a single invoke after opening a file. But after editing code, it no longer gets invoked.
Any ideas what could be causing that?
I also migrated a language service from 2008 to 2010. Can you check if you've fallowed all of these steps?
http://msdn.microsoft.com/en-us/library/dd885475.aspx
I didn't have to do anything else, which I verified by diffing the important files in our depot before and after the change.
I don't know if you ever figured your question out, but have you tried making sure that your Source class' LastParseTime is set to 0 when creating it? I seem to recall some issues with Check not happening unless you manually set LastParseTime to 0 when creating your Source object.
Protip: If you use .NET Reflector, you can disassemble all of the base classes for the LanguageService framework and get a pretty good understanding of how it all works under the hood. The classes you'd be interested in live in Microsoft.VisualStudio.Package.LanguageService.10.0.dll, which should be installed in the GAC. I've found this to be unimaginably helpful when trying to figure out why things weren't working in my own Language Service, and being able to step through the source code in the debugger mitigates almost all the pain of working with these frameworks!
When your Source object is initialized, it starts off with a LastParseTime of Int32.MaxValue. The code that causes fires off a ParseRequest with ParseReason.Check checks the LastParseTime value to see if the time since the last change to the text is less than the time it takes to run a parse (or the CodeSenseDelay setting, whichever is greater).
The code that handles the response from ParseSource is supposed to set the LastParseTime, but as far as I can tell, it only does that if the ParseReason is Check.
You can get around this issue by setting Source.LastParseTime = 0 when you initialize your Source. This has the side-effect of setting CompletedFirstParse to true, even if the first parse hasn't finished yet.
Another way to fix this issue is to override Source.OnIdle to fire off the first call to BeginParse() This is the way I would recommend.
public override void OnIdle(bool periodic)
{
// Once first "Check" parse completes, revert to base implementation
if (this.CompletedFirstParse)
{
base.OnIdle(periodic);
}
// Same as base implementation, except we don't check lastParseTime
else if (!periodic || this.LanguageService == null || this.LanguageService.LastActiveTextView == null || (this.IsCompletorActive) || (!this.IsDirty || this.LanguageService.IsParsing))
{
this.BeginParse();
}
}

Break when a value changes using the Visual Studio debugger

Is there a way to place a watch on variable and only have Visual Studio break when that value changes?
It would make it so much easier to find tricky state issues.
Can this be done?
Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter:
&myVariable
You can also choose to break explicitly in code:
// Assuming C#
if (condition)
{
System.Diagnostics.Debugger.Break();
}
From MSDN:
Debugger.Break:
If no debugger is attached, users are
asked if they want to attach a
debugger. If yes, the debugger is
started. If a debugger is attached,
the debugger is signaled with a user
breakpoint event, and the debugger
suspends execution of the process just
as if a debugger breakpoint had been
hit.
This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.
In Visual Studio 2015, you can place a breakpoint on the set accessor of an Auto-Implemented Property and the debugger will break when the property is updated
public bool IsUpdated
{
get;
set; //set breakpoint on this line
}
Update
Alternatively; #AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the get; or set; and hit F9 and a breakpoint will be placed accordingly. Nice!
public bool IsUpdated { get; set; }
Imagine you have a class called A with the following declaration.
class A
{
public:
A();
private:
int m_value;
};
You want the program to stop when someone modifies the value of "m_value".
Go to the class definition and put a breakpoint in the constructor of A.
A::A()
{
... // set breakpoint here
}
Once we stopped the program:
Debug -> New Breakpoint -> New Data Breakpoint ...
Address: &(this->m_value)
Byte Count: 4 (Because int has 4 bytes)
Now, we can resume the program. The debugger will stop when the value is changed.
You can do the same with inherited classes or compound classes.
class B
{
private:
A m_a;
};
Address: &(this->m_a.m_value)
If you don't know the number of bytes of the variable you want to inspect, you can use the sizeof operator.
For example:
// to know the size of the word processor,
// if you want to inspect a pointer.
int wordTam = sizeof (void* );
If you look at the "Call stack" you can see the function that changed the value of the variable.
Change the variable into a property and add a breakpoint in the set method. Example:
private bool m_Var = false;
protected bool var
{
get {
return m_var;
}
set {
m_var = value;
}
}
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
If you are using WPF, there is an awesome tool : WPF Inspector.
It attaches itself to a WPF app and display the full tree of controls with the all properties, an it allows you (amongst other things) to break on any property change.
But sadly I didn't find any tool that would allow you to do the same with ANY property or variable.
I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.
Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).
As Peter Mortensen wrote:
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter: &myVariable
Additional information:
Obviously, the system must know which address in memory to watch.
So
- set a normal breakpoint to the initialisation of myVariable (or myClass.m_Variable)
- run the system and wait till it stops at that breakpoint.
- Now the Menu entry is enabled, and you can watch the variable by entering &myVariable,
or the instance by entering &myClass.m_Variable. Now the addresses are well defined.
Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.
You can use a memory watchpoint in unmanaged code. Not sure if these are available in managed code though.
You can probably make a clever use of the DebugBreak() function.
You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.

Resources