Debugger shows properties that throw an exception - c#

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".

Related

How to detect Visual Studio debug execution context from within code?

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.

Source of System.NullReferenceException

I am implementing a error logger for a web shop and just logging a NullReferenceException in a specific class is only useful to a certain level. I am not really interested in how to prevent the exception, as I am aware of that, but sometimes it still happens thus the error logger.
Then the question is: How do I find the source of a System.NullReferenceException inside all the exception information.
Make sure you log the full stack trace. Assuming you've got debug information turned on (no reason not to for a web app...) you should be able to get to the line which caused the problem.
Of course, that won't always give you all the information you need, if you've got:
if (foo.Bar.Baz && person.Address.Road.Length)
in a single line... but it's the best starting point you'll get.
Additionally, adding argument validation to methods can make it a lot simpler to pin down what's wrong. Personally I'm a fan of helper methods for this. For example, in Noda Time we have Preconditions, so I can just call:
Preconditions.CheckNotNull(foo, "foo");
(which also returns the value of foo, which is handy in constructors which are copying arguments into fields).
The earlier you can detect the unexpectedly-null reference, the better.
If I understand the question correctly, in Visual Studio, go to Debug > Exceptions, and check all options to throw exceptions. This will allow you to see everything that is being thrown while debugging. You can possibly use the contents of InnerException to determine what the root location of the error is being caused.

Pros/cons of different methods for testing preconditions?

Off the top of my head, I can think of 4 ways to check for null arguments:
Debug.Assert(context != null);
Contract.Assert(context != null);
Contract.Requires(context != null);
if (context == null) throw new ArgumentNullException("context");
I've always used the last method, but I just saw a code snippet that used Contract.Requires, which I'm unfamiliar with. What are the advantages/disadvantages of each method? Are there other ways?
In VS2010 w/ Resharper,
Contract.Assert warns me that the expression is always true (how it knows, I'm not quite sure... can't HttpContext be null?),
Contract.Requires gets faded out and it tells me the compiler won't invoke the method (I assume because of the former reason, it will never be null), and
if I change the last method to context != null all the code following gets faded out and it tells me the code is heuristically unreachable.
So, it seems the last 3 methods have some kind of intelligence built into the VS static checker, and Debug.Assert is just dumb.
My guess is that there is a contract applied to the interface IHttpHandler.ProcessRequest which requires that context != null. Interface contracts are inherited by their implementers, so you don't need to repeat the Requires. In fact, you are not allowed to add additional Requires statements, as you are limited to the requirements associated with the interface contract.
I think it's important to make a distinction between specifying a contractual obligation vs. simply performing a null check. You can implement a null check and throw an exception at runtime, as a way to inform the developer that they are using your API correctly. A Contract expression, on the other hand, is really a form of metadata, which can be interpreted by the contract rewriter (to introduce the runtime exceptions that were previously implemented manually), but also by the static analyzer, which can use them to reason about the static correctness of your application.
That said, if you're working in an environment where you're actively using Code Contracts and static analysis, then it's definitely preferable to put the assertions in Contract form, to take advantage of the static analysis. Even if you're not using the static analysis, you can still leave the door open for later benefits by using contracts. The main thing to watch out for is whether you've configured your projects to perform the rewriting, as otherwise the contracts will not result in runtime exceptions as you might expect.
To elaborate on what the commenters have said, the difference between Assert, Assume and Requires is:
A Contract.Assert expression is transformed into an assertion by the contract rewriter and the static analyzer attempts to prove the expression based on its existing evidence. If it can't be proven, you'll get a static analysis warning.
A Contract.Assume expression is ignored by the contract rewriter (as far as I know), but is interpreted by the static analyzer as a new piece of evidence it can take into account in its static analysis. Contract.Assume is used to 'fill the gaps' in the static analysis, either where it lacks the sophistication to make the necessary inferences or when inter-operating with code that has not been decorated with Contracts, so that you can Assume, for instance, that a particular function call returns a non-null result.
Contract.Requires are conditions that must always be true when your method is called. They can be constraints on parameters to the method (which are the most typical) and they may also be constraints on publicly visible states of the object (For instance, you might only allow the method to be called if Initialized is True.) These kinds of constraints push the users of your class to either check Initialized when using the object (and presumably handle the error appropriately if it's not) or create their own constraints and/or class invariants to clarify that Initialization has, indeed, happened.
The first method is appropriate for testing for a null condition that should never exist. That is, use it during development to ensure it doesn't unexpectedly get set to null. Since it doesn't do any error handling, this is not appropriate for handling null conditions in your released product.
I would say the 2nd and 3rd versions are similar in that they don't handle the issue in any way.
In general, if there's a possibility that the variable could actually be null in the final product, the last version is the one to use. You could do special handling there, or just raise an exception as you've done.

How can I trace a variable at runtime in C#?

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.

Debugging a C# Object Initializer

Does anyone have any tips for debugging exceptions in a C# object initializer block? The object initializer syntax is basically all or nothing, which can make it especially difficult to troubleshoot inside of a LINQ query. Short of breaking the object creation out to a separate method, is there anything I can do to see which property setter is throwing an exception?
Disabling the option to step over property setters [Step over properties and operators (Managed Only)] can allow you to step into the property setters.
Otherwise, the best option is often to just break it out and debug it outside of the LINQ statement. You can wrap your initialization parameters into an anonymous type in linq, and construct your object(s) outside of your linq statement for debugging purposes.
Have you set up VS to break when an exception is thrown? (the default is to break only on unhandled exceptions). Debug | Exceptions, and check "thrown".
That alone is probably not an answer to your question, but it might help with the debugging.
Beyond that, you could temporarily break your code out of the initializer block (just for debugging), and then if you want, you can reinstate the initializer block once you have the code working.
Break it out of the object initializer block where your setting each property individually. That way you can actually step into the code.

Categories