I'm looking for a way to detect how code is called during a debugging session in Visual Studio. Trying to differentiate these two contexts:
Ordinary debugging, whether running or single stepping.
Called via the debugger itself, such as my ToString being called from the watch window.
(I'm doing this because I have some non-release thread validation code I want to disable in the second case.)
Anyone have a way to do this, or ideas about things to pursue? I'm fine with hacky, tricksy methods, even if they are specific to a particular version of VS.
Things that don't work:
Grabbing a StackTrace and looking for something magic that means the debugger is calling in, rather than regular code. VS uses the current thread in its current state to call out of for the Watch window, so all the StackTrace is going to see is the current stack at the debugger breakpoint + the getter/ToString that the Watch window is calling, right on top of it.
This situation typically arises when methods that Visual Studio assumes are pure (i.e. evaluation has no impact on the state of the program) either have side effects or have preconditions that the debugger violates.
These situations are best solved using the following tools:
DebuggerBrowsableAttribute: Apply this attribute to properties:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Apply to all properties whose get method is not pure, i.e. the getter alters the state of the program, either through setting a cached value or otherwise
Apply to all properties whose get method has preconditions the debugger could violate, such as threading restrictions, cross-thread invocations (don't forget implicit if you use COM interop)
DebuggerDisplayAttribute: Apply this attribute to all types whose ToString() implementation performs non-trivial operations (avoid debugger performance impact) or has preconditions the debugger might not meet (e.g. threading requirements). This attribute is used instead of calling ToString() for these types.
DebuggerTypeProxyAttribute: Apply this attribute to types that require special consideration for when, what, and how information is presented in the debugger. The .NET framework itself uses this attribute extensively to provide features like clear output for the List<T> and HashMap<T> types, and even to improve information available for types like Lazy<T> that are sometimes OK to evaluate and other times could affect the state of the program.
As far as ordinary debugging goes, I think this is what you want:
System.Diagnostics.Debugger.IsAttached
Here's the documentation.
This won't help with the watch window though. On this, maybe the StackTrace class can help but I haven't tried it myself. It's in the same namespace.
Related
When using libraries (currently the PNP Core SDK) I often notice that while inspecting some objects, they have many properties that "threw an exception".
This looks like that:
But what does this mean exactly?
Does it mean that the value would throw an exception if I tried to access it? But I thought getters should never throw exceptions. Is this a bad practice?
So did the debugger already try to access all those properties and therefore "knows" in advance that it would throw an exception if I tried to access those properties at runtime?
What should such property states communicate to the developer? How should I behave if I see that?
Yes, the debugger evaluates all those properties. And while doing so, he encountered an exception. The text (which is not fully visible on your screen shot) will give an indication as to why the exception was thrown. A typical cause is that the object is not valid any more (it's been disposed, for instance). Some properties might also throw an exception because they cannot be evaluated by the debugger for technical reasons. This may for instance happen when looking at instances of System.Type with the debugger.
For this very reason, it is advised that properties are lightweight and should not throw exceptions. Complex operations that involve e.g. accessing a database or querying some piece of hardware information should not be done trough properties. But not all APIs actually adhere to this recommendation.
There are even cases when the debugger may cause side effects due to its property evaluation, therefore a get property should never change the state of an object. Code that would use the following property would work differently when being debugged as when not:
public int NextNumber
{
get
{
return _number++;
}
}
To disable property evaluation in the debugger, go to Tools->Options->Debugging and deselect "Allow property evaluation and other implicit function calls".
My library has some methods whose return value should never be discarded. Leaking them is a very popular mistake even for me, the author. So I want the compiler to alert programmer when it does so.
Such value may be either stored or used as an argument for another method. It's not strictly to use the stored value but if it's simply discarded it's 100% error.
Is there any easy to setup way to enforce this for my library users?
var x = instance.Method(); // ok
field = instance.Method(); // ok
instance.OtherMethod(instance.Method()); // ok
MyMethod(instance.Method()); // ok, no need to check inside MyMethod
instance.Method(); // callvirt and pop - error!
I thought about making IL analyzer for post-build event but it feels like so overcomplicated...
If you implement Code Analysis / FXCop, the rule CA1806 - Do not ignore method results would cover this case.
See: How to Enable / Disable Code Analysis for Managed Code
Basically, it's as simple as going to the project file, code analysis tab, checking a box and selecting what rules to error / warn on.
Basically tick the checkbox # 1, and then use 2 to get to a window where you can configure a ruleset file (this can either be one you share between libraries or something more global (if you have a build server, make sure its stored somewhere the build can get to, i.e. with the source not on a local machine).
Here's a ruleset with the rule I mean:
The Nicolai's answer enables ruleset for any types but I needed this check for only my library types (I don't want to force my library users to apply rule set on all their code).
Using out everywhere as suggested in the comments makes the library usage to hard.
Therefore I've chosen another approach.
In finalizer I check whether any method was called (it's enough for me to confirm usage). If not - InvalidOperationException. Object creation StackTrace is optionally recorded and appended to the error message.
User may call SetNotLeaked() to disable the check for particular object and all internal objects recursively.
This is not a compile-time check but it will surely be noticed.
This is not a very elegant solution and it breaks some guidelines but it does what I need, doesn't make user to view through unnecessary warnings (RuleSet solution) and doesn't affect code cleanliness (out).
For tests I had to make a base class where I setup Appdomain.UnhandledException handler in SetUp method and check (after GC.Collect) whether any exception was thrown in TearDown because finalizer is called from another thread and NUnit otherwise shows the test as passed.
Is it possible to get a list or a specific instance of IDebugEngine2 (MSDN) from a Visual Studio Package without using IVsLoader approach (described here)?
Normally I would expect most services to be available through GetService, either directly or through some other service. But I can not easily find anything that can provide debug engines.
What are you trying to do with it? The debugger interfaces are extremely fragile. Often there are 2, 3, or maybe more possible ways to perform an action with the debugger interfaces, but the particular DE implementation only supports 1 of them. Debug engine implementers are not expecting any direct calls to their debug engine interfaces from anywhere except Visual Studio itself, and the risk of breaking debugger functionality if you attempt it lies somewhere between very high and guaranteed.
For example, here are some of the potential ways to tell a DE to launch and/or attach to a process:
IDebugEngineLaunch2.LaunchSuspended
IDebugPortEx2.LaunchSuspended
IDebugProgramEx2.Attach
IDebugProgramNode2.Attach_V7
IDebugProgramNodeAttach2.OnAttach
IDebugEngine2.Attach
IVsDebuggableProjectCfg.DebugLaunch
VsShellUtilities.LaunchDebugger
IVsDebugger2.LaunchDebugTargets
IVsDebugger2.LaunchDebugTargets2
Edit 1: In the case of my Java debugger, the debug engine is created by the session manager with the following stack:
My code calls IVsDebugger2.LaunchDebugTargets2
The environment calls back to my implementation of IDebugProgramProvider2.WatchForProviderEvents
After creating a new instance of IDebugProgram2 (a copy of IDebugProcess2 obtained from the IDebugDefaultPort2 that VS passed to WatchForProviderEvents is passed to the IDebugProgram2 constructor), my code calls IDebugPortNotify2.AddProgramNode
The environment calls back to the constructor of my debug engine
I recently was investigating the same question, and eventually found you can easily do this via ILocalRegistry3.CreateInstance!
Please see my post here for more info
How can I track a variable's values as they change, at runtime, in C#? I'm interested in the same functionality that the debugger provides when I'm tracing a variable through execution steps, only that I need to call upon it from my code. Some sort of key-value observing, but for all kinds of variables(local, class, static, etc), not only properties. So, basically, receive a notification when a variable's value changes.
You are working from the assumption that the debugger can track variable changes. It can't.
It is possible with unmanaged code, the processor has dedicated debug registers that allow setting data breakpoints. Up to three are provided. It generates a hardware interrupt when it sees a particular memory location getting written. This otherwise very useful feature isn't available in managed code however. The garbage collector is completely incompatible with it, it moves objects around, giving them another address.
The managed debugger does support a "when hit" condition on a breakpoint, allowing you to dump info to the output window. That however requires a breakpoint, it cannot be triggered by a change in variable value. It also really slows down code execution since the debugger actually enters a break state before executing the condition.
The obvious place to put such a breakpoint is in a property setter. Which is what you'll need to implement this feature in code. You can do anything you want in that setter, using the Trace class for example.
To add to what Marc said, if you want to do this for lots of properties and methods you might want to check out aspect oriented programming techniques, and libraries such as PostSharp.
http://www.sharpcrafters.com/postsharp
The managed debugger uses the ICorDebug COM API for pretty much everything. The part that you're interested is ICorDebugValue and its descendants. Note that a LOT of the debugging API requires that the process be not running (ie, have encountered a breakpoint) in order for the various inspections to happen. A high level overview of ICorDebug is here. The documentation on it is kinda sparse, but some Googling may help. Good luck.
The only sensible way you could do that without the debugger would be: don't use a variable, but use a property, and (perhaps conditionally) add trace to the setter:
private int myValue;
public int MyValue {
get {return myValue;}
set {
SomeTraceMethod(myValue, value, ...);
myValue = value;
}
}
Obviously this cannot then be used for arbitrary fields/variables.
As others mentioned a mechanism like that makes only sense when using properties. In .NET you can then make use of the INotifyPropertyChanged interface.
For a sample how to implement it see
How to: Implement the INotifyPropertyChanged Interface
The referenced article talks explicitly about Windows Forms, but you are not bound to that (the interface is actually declared in the System.ComponentModel namespace in System.dll). In fact, this interface is widely used for data binding scenarios, e.g. in WPF.
The .NET coding standards PDF from SubMain that have started showing up in the "Sponsored By" area seems to indicate that properties are only appropriate for logical data members (see pages 34-35 of the document). Methods are deemed appropriate in the following cases:
The operation is a conversion, such as Object.ToString().
The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
Obtaining a property value using the get accessor would have an observable side effect.
Calling the member twice in succession produces different results.
The order of execution is important.
The member is static but returns a value that can be changed.
The member returns an array.
Do most developers agree on the properties vs. methods argument above? If so, why? If not, why not?
They seem sound, and basically in line with MSDN member design guidelines:
http://msdn.microsoft.com/en-us/library/ms229059.aspx
One point that people sometimes seem to forget (*) is that callers should be able to set properties in any order. Particularly important for classes that support designers, as you can't be sure of the order generated code will set properties.
(*) I remember early versions of the Ajax Control Toolkit on Codeplex had numerous bugs due to developers forgetting this one.
As for "Calling the member twice in succession produces different results", every rule has an exception, as the property DateTime.Now illustrates.
Those are interesting guidelines, and I agree with them. It's interesting in that they are setting the rules based on "everything is a property except the following". That said, they are good guidelines for avoiding problems by defining something as a property that can cause issues later.
At the end of the day a property is just a structured method, so the rule of thumb I use is based on Object Orientation -- if the member represents data owned by the entity, it should be defined as a property; if it represents behavior of the entity it should be implemented as a method.
Fully agreed.
According to the coding guidelines properties are "nouns" and methods are "verbs". Keep in mind that a user may call the property very often while thinking it would be a "cheap" operation.
On the other side it's usually expected that a method may "take more time", so a user considers about caching method results.
What's so interesting about those guidelines is that they are clearly an argument for having extension properties as well as extension methods. Shame.
I never personally came to the conclusion or had the gut feeling that properties are fast, but the guidelines say they should be, so I just accept it.
I always struggle with what to name my slow "get" methods while avoiding FxCop warnings. GetPeopleList() sounds good to me, but then FxCop tells me it might be better as a property.