Debugging a C# Object Initializer - c#

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.

Related

Debugger shows properties that throw an exception

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

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.

Prevent debugger from stopping on an Exception in a Compiled LambdaExpression

In my program, I create dynamic lambda expressions and then compile them to delegates. These delegates are then invoked to extract information from my entities.
Some of the delegates may throw exceptions, I've caught the exception where I call the delegate. I've enabled "Enable just my code" and applied [DebuggerNonUserCode] attribute to where the LambdaExpression is created, where compiled, and where Called. But because in Debug>Exceptions>Common Language Runtime Exceptions, the Thrown check box is checked, visual studio always stops on the error, which is a major inconvenience for the developers.
It seems that [DebuggerNonUserCode] should somehow be applied to the compiled delegate, but how? Or any other suggestion?
Thanks.
As far as I know, you cannot apply attributes to anonymous methods generated using expressions, aside from possibly some horrible messing around with dynamic type generation.
However, a possible suggestion would be to go to the exception menu in Debug > Exceptions and choose which exceptions you want to break on specifically. If your expressions tend to throw exceptions of specific kinds, you can just disable breaking on those exceptions.

Can ReSharper be set to warn if IDisposable not handled correctly?

Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a using block, or omit the proper Dispose call in a finally block?
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal.
That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.
Discontent with current methods, I created my own: EyeDisposable. It's an IL instrumenter so it should catch many leaks not caught by static analysis. It's still in its early stage, inputs are welcome.
See this blog post for some tricks for testing for Dispose() in DEBUG. Basically, write a DEBUG-only destructor that asserts that you were disposed.
You could design a small add-in to R# that you could have run inside the code editor that scans the code and updates the code analysis to reflect that you an object who's missing the structure you've just described.
I'd look into the R# plugin architecture if you decide to go that route.
You might want to look at FXCop for this: http://msdn.microsoft.com/en-us/library/ms182328(VS.80).aspx
It's a pity R# doesn't handle it, even if just a warning for fields in your class and/or variables you create.

Categories