Breaking on code triggered by target application UI event in Visual Studio - c#

I've been debugging a WPF application bequeathed to me by a gentleman who is fond of making interesting architectural decisions. As a result, I'm having trouble locating the code that runs when a user clicks an on-screen menu item. Following the binding from the view to the viewmodel got me to some collection of "control functions" that's initialized at startup (apparently, all manner of different controls with varying functions had to go into a single collection). I've managed to find some code that's triggered by the click, but it's too deep, too far removed from the click event to be of any use to me.
This got me thinking...
In Visual Studio, (I'm using VS2015) when the application isn't running, if you select Debug -> Step into, debug is triggered, and then the debugger breaks on the very first line of the code (in my case the constructor call of the class that inherits from System.Windows.Application)
Isn't there a way to do this while the application is already running? Let's say I've started a WPF (or WinForms) application, a window has been displayed, the UI thread is running and awaiting user input. The user clicks on a button, and some code is executed. But unless there's a breakpoint in the code, the debugger doesn't do anything about it. As I've explained, this can be a problem if I don't know which code is actually run. Is there a way to tell Visual Studio, "listen, if the user clicks on something, break on the first line of (user) code triggered by this action." Is that possible?

Related

How can I prevent code in Windows.Forms OnDeactivate running when hitting a breakpoint?

For example: create a new Windows.Forms project and give it a button. Add the following code:
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
Debug.WriteLine("deactivated");
}
private void button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("hello");
}
As expected, the output window displays "hello" when the button is clicked, and "deactivated" when some other window is activated.
Now, place a breakpoint on the Debug.Writeline("hello"). Click the button, then resume execution. Notice that the output window shows both "hello" and "deactivated".
I would like to find a way to prevent this, so that debugging my app does not change its behavior any more than necessary. Just as when the breakpoint is not present, the click handler should run but the deactivate one should not.
It would be ideal to find a setting in Visual Studio such that hitting a breakpoint does not fire the deactivate event in the app at all. I have not found such a setting.
It would be acceptable to find a way to know that the application being activated in place of mine is Visual Studio (better: that it is some debugging tool...this program might well be debugged using Visual Studio Code or Mono Develop). Then I could code OnDeactivate not to do the deactivate behavior in that case.
It is possible to set an Action on a breakpoint that will set a flag in the program that prevents the action. This is a very undesirable solution because every programmer must remember to do it every time they create a breakpoint where the deactivate action is not wanted.
Remote debugging is another potential solution; but I don't want to have to do all my debugging using another system.
(Note: in the real app, what happens on deactivate is to save what the user is editing. The problem is that when I'm in the middle of debugging something else an unexpected Save can mess things up. Data may not be in a valid state to save.)
You've said "Remote debugging is another potential solution; but I don't want to have to do all my debugging using another system." (which I'm guessing also rules out using a VM).
My suggestion would be to become less dependent upon debugging the running application by writing Unit Tests. With Unit Tests, you can test isolated parts of your system independently of others.
When you have Unit Tests in place you can run each individual test under Debug, allowing you to step through the code exactly like you do when debugging the application; but since you get to define the scope of the test, the whole application isn't running, so things like the application losing focus can be made out out of scope.
Once a test is in place, it can shorten the time taken by the code+debug iteration cycle, making you more productive. It achieves that because the test fires you straight into the relevant code with the test scenario already set up, rather than the whole application having to start up, and you navigating through to the relevant parts each time to get into the scenario you want.
Another benefit of these tests (if they are written the right way) is that you can make them run as part of an automated build which is triggered whenever someone changes some code. This means that if anyone breaks that code, the test will fail, and the build will fail.

UI behaves differently when I am debugging in Visual Studio

I have some drag and drop functionality I am using in an xceed grid. When I try to drag and item down just one row, it doesn't work. But if I put a break point in my drop method and do the drop then, it has changed when I come back to the UI. What might cause it to behave differently whether I break into the code or not?
If you "pause" your application using a debugger breakpoint, the state of the system (e.g. mouse button state) can change while it's paused, and thus be different when you allow the program to continue running. This can cause a very different behaviour than if the program were running normally. As a result of this, debugging drag and drop problems using breakpoints is often impossible.
In these situations a good approach is often to go back to basics and use a Debug.WriteLine (or similar) to dump useful information about the state of your variables as it runs "normally" (instead of killing it with a breakpoint). Then you can examine this dumped information at your leisure after the program has finished the drag, in order to work out what was happening at each stage in the process and work out why it failed.

.NET/C# debugging: How to debug a classical heisenbug?

Recently, I've run into a classical Heisenbug. Here's the situation:
I have a tree list, the master view, in one panel, and a detail view in another panel to the right, that displays information about the currently selected tree node. (Very similar to Windows Explorer.)
When I add a new node to tree (think of right-clicking a folder in Windows Explorer and saying "New -> Folder"), the newly created node gets selected.
And here's the bug: The detail view on the right should get updated to show the new node. However, it doesn't. I have to switch to another tree node once, before I can see information about the new node in the detail view.
The bug is easily reproducible and happens in both "Release" and "Debug" build configurations. But: As soon as I set a breakpoint in the event handler (for the "Add new node" menu entry) and enable it, everything works fine =>Heisenbug! I don't have to do any real debugging. Clicking "continue" after the breakpoint gets hit is enough.
For better understanding, I've made a video that should illustrate what's going on.
Everything I could think of to get rid of the issue was putting the thread (the application is single-threaded) to sleep for a few seconds, but that doesn't work.
I'd greatly appreciate any suggestions on what I could try to determine the cause of the issue. Or maybe someone has a guess about the cause?
I'm targeting the 3.5 framework and using x86 as solution platform. The tree list control is from DevExpress' WinForms controls; Visual Studio version is 2010.
Thanks
Update 3: Issue solved. The problem was that the call to the detail view's Focus() method didn't trigger the GotFocus event, which is crucial for updating the detail view. (I don't know why, probably it already had the focus.) However, the method did not fail, it simply did nothing.
Now I just focus another control before focussing the detail view and that's it. The reason why everything worked fine during debugging was that switching from Visual Studio back to my application correctly set the focus on the detail view.
A major obstacle in hunting down this issue was that setting a breakpoint in the GotFocus event handler is useless: anytime you try to switch back from Visual Studio to the app, the GotFocus event gets re-triggered, and you're stuck in an endless loop. Comments on how that could be worked around are welcome.
Anyway, my specific problem is solved.
Thank you very much to everybody who answered or commented. It helped me a lot.
Update 2: In my code, I select the newly created node in the tree. This triggers a FocusedNodeChangedEvent. In the corresponding event handler, I update the detail view and call its Focus() method.
It seems as if that fails when there's no breakpoint set. I think what triggers the correct update during debugging is that the detail view automatically gets the focus.
Window messages
Update 1: Here are the window messages that Eddy's answer provided. (Long list of messages deleted)
First time I've seen a video to support an SO :)
I'm thinking that the right-hand pane, or control group, need(s) to have Invalidate() called - which I think the breakpoint is triggering because it switches to VS, overdrawing the window. Then, when you switch back again, it forces everything to redraw, thus making it work.
When you have a "heisenbug" you need to see what is going on but with a lighter touch that doesn't interrupt the flow of the program.
I would suggest that you form an hypothesis about where your problem lies. I would then edit the code to include calls to the various methods of the Debug class, that test the hypothesis or just give runtime information for diagnosis. Then run your code in debug mode and see what you get in the output.
If you have a more elusive "hiesenbug" theat occurs only in release mode you would need to roll you own logging mechanism to gather your evidence.
Put a System.Diagnostics.Debugger.Break() in the update routine for the other window. Then when the bug appears, a run time break point will be fired and you can view the stack.
It seems that the problem has to do with not getting the right event called to trigger and update to the child panel. When hitting the breakpoint your app loses focus and when you return it gains it again (which is a difference from running it). In order to inspect what events are and aren't called and what the difference is between the two scenario's add the following code to your form to see all the window messages that appear.
protected override void WndProc(ref Message winmsg)
{
base.WndProc(ref winmsg);
System.Diagnostics.Debug.WriteLine(winmsg.Msg + " - " + winmsg);
}
Comparing the differences might help you in determining a way how to workaround this problem.

WPF: program.exe doesn't exit "the process cannot access the file.. used by another process"

I've worked on quite a few WPF solutions, and this is the first time i am seeing this problem.
Today it started happening intermittently. where after closing my WPF window, the .exe is still running under visual studio.
so i have to kill my program.exe manually in order to compile again.
Initially i thought because i overrode application start/exit/exception .. but i commented all that out, and it is still happening.
In fact, i see multiple instances of my program.exe in process explorer!
Can't figure out what is causing my exe not to exit. Is there any explicit dipose logic i can add in applicaton exit event to ensure it really exits?
My application consists of single window, and multiple user controls as views.
update
if i open in debug mode. and close the main WPF window, my visual studio does not stop debugging. however call stack window is empty.
You can use the Application.Exit event to log when your application shuts down.
Alternatively, you can attach the debugger to your running instance (even if it wasn't started in the debugger) then pause it to see where it's at. Make sure to look at the Threads tool window, as you may pause outside the UI thread.
This should take care of it, though its probably better to try to figure out the underlying issue.
System.Diagnostics.Process.GetCurrentProcess().Kill();

Debugging all events in Visual Studio 2010 without setting break points

I am trying to debug a windows form application which has a large number of events: button presses, timers, etc..
Is there a way to catch every line of code being executed by the application without setting a break point?
edit:
The program was not written by me, so I am unfamiliar with the code. I wish to step through the entire program, catching every line of code being executed. Setting break points in every event is impractical as various controls are created dynamically.
For debugging a button click without setting breakpoints:
Start the app with the debugger.
Get to the state immediately before the intended click.
Go back to the debugger and press Pause then F11 (Step Into) -- nothing will happen.
Go to the app and press the button -- the debugger should take over and drop you into the event handler.
Note: This will not work if Paint, any Mouse event, or probably some other events are handled. The debugger will drop you into those handlers any time you attempt the steps above.
If you're using the Ultimate edition of your Visual Studio 2010 you can use its new feature called IntelliTrace (previously Historical Debugger). This will allow you to do exactly what you want - be able to see all method calls and events that happened during execution of your program, and you'll be able to jump back to the event which you need.
To enable IntelliTrace, go to Tools → Options → IntelliTrace, and check the "Enable IntelliTrace" checkbox, and select one of two modes: "events only" or "events and call information", then run your application with a debugger (F5).
The difference between the two modes is that the latter uses the profiler to collect all runtime information, so you get a complete call stack, however you won't be able to use edit-and-continue features of the debugger.
You can find more in this series of articles, and of course, on MSDN.
You could also try a code coverage tool.
For example, if you have Resharper and dotCover, you can run your application (via the dotCover->Cover Application... menu item) and when the application finishes, dotCover will show you which lines of code were run in the VS IDE by highlighting them in green. Lines of code which where not run are coloured in red.
I don't know if there are other tools which do this, but it's an option.
I developed the Runtime Flow tool to solve exactly this problem - to understand a large unfamiliar .NET codebase via realtime function calls monitoring. It's similar to IntelliTrace, but places more emphasis on control flow than on debugging.
Why would you want to break on every line? This would be very onerous and time consuming. If you want to see the activity of your program as it executes, use a logging mechanism or Debug.Writeline to output information to the Immediate window.
You cannot trace lines of code, but you can use Trace.TraceInformation calls where you want to have an idea of what's executed. There's also Debug.Write. Both output will write in the output window of Visual Studio.
Another solution would be to add logging to your application, for example with log4net, but that may be overkill for your needs.
This isn't exactly what you're asking for, but in case you didn't know you can toggle an existing breakpoint on or off. In your case, you could add break points at key places throughout your code and just disable them when you don't want to debug them. That way, you'll be able to re-enable them later when you want to use them again.
Enabling/disabling is available through the Breakpoints window found under the Debug > Windows > Breakpoints menu (CTRL+D, B). You can also include "Function" and "File" columns in the window, which might help you identify which breakpoints are in the event handlers that you care about
Not really, but you can set one breakpoint and single-step (F10/F11) through the rest of the code.
Nope 'fraid not - you need to set each breakpoint yourself.
If it helps F9 is the shortcut key for assigning a breakpoint - just set a breakpoint on the start of each method and use step through (F10) / step into (F11) from there.

Categories

Resources