How do I set a breakpoint on every access to a class - c#

When working with third party systems, especially very configurable systems that dynamically load providers, controllers, components and so on, I sometimes just want to know when a certain object or class is accessed. Normally, I'd place a breakpoint on any potential lines in my source (a nuisance, but it works), but if source is not available:
How can I instruct Visual Studio 2010 Ultimate to break on any and each access to a given class?
Note: as far as my experience goes, this is not generally possible, but I'd like to see it confirmed

Not the most elegant, but if you Ctrl+F public then you can spam between F9 [set breakpoint] then F3 [find next] to set a breakpoint on every public entry point into the class.
You might also want to add breakpoints for protected and internal entry points, and any explicit interface implementations (declarations that don't have public)

You can click Debug > New Breakpoint > Breakpoint at Function. Ctrl-B brings you there directly. It'll allow you to break at a specific function.
During debugging, you can see in the Breakpoints-window whether the method is found and will be hit (red round icon) or not (white with circle icon, as of disabled breakpoint), just as with normal breakpoints.

At one time (pre VS2008) you could set a breakpoint at every line in a file by select all (ctrl-a) followed by set breakpoint (F9).
To set just one on the entry to every method takes, if I recall correctly, a macro. Check out John Robbins' blog as a possible source: http://www.wintellect.com/CS/blogs/jrobbins/
[EDIT: ctrl-A, F9 doesn't work in 2010 or 2008, so it must be an earlier version I remember this from]

I just made a Visual Studio 2010 addin for this. Check this: http://weblogs.asp.net/uruit/archive/2011/08/04/visual-studio-2010-addin-setting-a-class-breakpoint.aspx
Update
This project now lives on Github. Feel free to contribute.

Related

Load Visual Studio 2019 Extension on Startup

I need to measure the time I spend in break mode debugging my Projects.
So I came up with the idea to write a custom VS extension which binds to the
OnEnterBreakMode & OnEnterRunMode debugging events.
This works just fine, but I need to make sure my extension is loaded right at the startup of VS.
Otherwise, the extension might not be loaded when I am already debugging.
Unfortunately Visual Studio 2019 heavily forces the user to use the AsyncPackage base class and
set the BackgroundLoadingFlag. On default VS deactivates extensions which use the deprecated API,
which allows synchronously loading extensions on startup.
Do you have any tips or workarounds on how I can make sure that my extension was loaded when I
start debugging?
So set your package to auto-load when the KnownUIContexts.DebuggingContext is activated, which means your package should be loaded once debugging has started -- there's no reason for you to load at startup if nobody every debugs anything in that session. Once your package loads, subscribe to those events, but also check the current state to see if you already entered break mode and missed the initial event. Rather than trying to "always load before the first event" it's often better to subscribe to events and just check the appropriate property to see if you are already in that state.
(And why do we not allow you to just load synchronously at startup? Because then everybody does that because it's easy, and your Visual Studio takes a real long time to load.)

C# check to see if property is accessed by the visual studio debugger

I am writing a C# application. I have some objects with some lazy properties that actually do quite some work when you request their values.
I want to be able to check if they are called by the visual studio debugger when debugging and not execute them at all. For example when I click on an object with these properties then it shouldn't load them at all.
How can I do this?
Consider using DebuggerBrowsableAttribute:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
The docs state:
Never -> Never show the element.
https://lostechies.com/jamesgregory/2009/08/18/debugger-property-evaluation-side-effects/ also briefly discusses the attribute.
Besides the excellent suggestion of #mjwills, if you don't have the source code or don't want to modify it at this point in time, turn the feature of in VS:

How to set breakpoints to all lines in a c# file in visual studio?

I am working with Visual Studio 2015.
I have a big c# class file with lot of properties and methods. I want to set breakpoints to all possible lines (set and get of properties, methods) at once. How can I do that?
You could add Debugger.Break() on the end of every single line. Therefore you could use the search and replace function of visual studio and replace \n with Debugger.Break()\n (Remember activating the regular expression option). This would cause the debugger to break at every single line, even though you won't have an indicated breakpoint.
I don't think that there's a method to add normal vs breakpoints to every single line though, due to the fact that it's quite useless, considering that you normally just step through the code with F11.
I think you are looking for this,
steps to follow:
1) Add a break point on the first line of code you want to debug.
2) Run the application.
3) When you want to run the next line of code, Select Debug | Step Into
4) Repeat step #3 for each line of the code
With vim (vsvim) you can set a breakpoint, move down a line, then repeat however many times you like, eg:
{Escape}qq:vsc Debug.ToggleBreakpoint{Enter}jq100#q
will set breakpoints on the next 100 lines
edit: here is example video, wouldnt let me embed gif https://imgur.com/SFhlEr7
Step Into(F11) or use the Debugger.Break() or add breakpoint directly would be the workarounds for you, of course, I suggest you use the Step Into(F11) which was much more convenient.
If you could use the latest VS2017 version, it has a new feature "Run to Click" which is also a better workaround for you during debugging.
Actually you don't have to debug every line code, that's also the reason I suggest you use this new feature.
Run to Click: Simply click the icon next to a line of code while debugging to run to that line. No longer set temporary breakpoints or
perform several steps to execute your code and stop on the line you
want. Now while stopped at a break state under the debugger, the Run
to Click icon subtly appears next to the line of code that your mouse
is hovered over. Move your mouse to the icon and click the button, now
your code will run and stop on that line the next time it is hit in
your code path. Turn it off from Debug> Options > Enable Run to
Click.
Reference:
https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes
Open a feature request with Microsoft https://learn.microsoft.com/en-us/visualstudio/ide/suggest-a-feature?view=vs-2022
There should be a mode that visual studio can be put in so that it automatically stops on every line of code in a particular project. This would be VERY valuable when you attach the debugger to a pre-existing process and you don't know where in the app is the current point of execution is, ie: web apps where you do not know the entry point.

Is there a way to stay on current document after a "break all" in Visual Studio?

Visual Studio opens source code on top of the stack when I "break all" while debugging; I want to keep the cursor on the document I'm currently working on, without any other document or window (e.g.: no symbols loaded) being opened.
There is a way to stay on the current document, but that requires creating a Visual Studio add-in and a new UI command in the Debug toolbar. Credits for this answer should actually also go to openshac, who posted a similar SO question and also gave a workaround in his OP by using a macro.
The implementation is fairly simple (it took me a few minutes to have it working). First, in the add-in project, modify the Exec method in the Connect.cs file like this:
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "BreakInCurrentDocument.Connect.BreakInCurrentDocument")
{
// here's where the magic happens
// ******************************
var activeWindow = _applicationObject.ActiveWindow;
_applicationObject.Debugger.Break();
if (_applicationObject.ActiveWindow != activeWindow)
{
_applicationObject.ActiveWindow.Close(vsSaveChanges.vsSaveChangesNo);
}
// ******************************
handled = true;
return;
}
}
}
After creating and registering the add-in, just:
click TOOLS on the Visual Studio's menu
Customize
Commands
Choose the "Toolbar" radio button
Select "Debug"
Add Command...
From the "Addins" category, choose your custom add-in.
That's it.
Latest build of VSCommands extension (free version) available from http://visualstudiogallery.msdn.microsoft.com/a83505c6-77b3-44a6-b53b-73d77cba84c8 has just what you want.
It adds a Break In Current Document button to Debug Toolbar and Debug Menu:
http://vscommands.squaredinfinity.com/Media/VSCommands/BlogPost//blog/breakincurrentdocument.png
It's a feature.. when you do "break all" then it is assumed that your process has hung. The first thing you might be interested in such case is - WHERE. Hence, it's directing you right down to the 'current' place that is being executed. IIRC, this is defacto standard for all low-level debuggers. If you don't want the "no symbols loaded" just mark the 'show disasembly' and it will never pop up again:) (of course, instead, you will see the exact point of stop. And yes, this is also a feature that I myself used many times to debug unknown library code)
On the other hand, if you know where you want the code to stop, place the breakpoint there instead.
On yet another hand (as if we had three), if you want to actually stop the application - stop it, don't break, just stop.
I sense that your actual problem lies in the fact that you use one of the features in a wrong way, and therefore another feature bugs you. Please tell me, what do you use the "break all" for and how/why does it collide with your current text-editing. Why can't you stop or break-at-here instead? Or "detach"?
Anyways, I have to admit that as a feature, there should be some option for turning it off, just for the sake of configurability of the IDE.
EDIT
AAhh.. you're right. I've completely forgot about the glorious edit&continue. I'm not joking/teasing, E&C is a great feature that I wish all other platforms had. I've forgot about it, because... I extensively use lambdas, generics, foreachs and etc features that effectively block edit-and-continue.
Anyways, the point is, since that the edit-and-continue is the golden feature that you'd like to use - the application must be in 'break' mode. However, nevertheless how do 'break'/'pause' etc it, the IDE will assume it that the PAUSE was you goal, not editing, hence it will show you where did you pause the app.
There are a few options in MSVS like "show just my code" that may help you a little, but it will not solve the problem: edit-and-continue during debugging was designed for "small, local edits". Like, if(x>0)throw new uncaught() instead if(x<0)throw new uncaught(). Your app stopped on assertion or breakpoint and is about to crash, first-change exception handler fired off and here's your chance! You unwind the crash handler, correct the code, then run. Everything in the same one method which you had the stop occur in, as a way of just-in-time patches..
This is one of the main problems why can't you add methods, classes, modify generics, etc during E&C session: ie. editing your current lambda or current foreach might be OK, but the IDE would be not able to relocate the flows and execute the new code properly. This is a bit similar to why you sometimes see the "stale code" warning, but with those code constructs it is even harder to analyze, and therefore not implemented. And probably will never hit the top of MS's TO-DO list :/
The current boom in .Net/C# is not 'live development' but 'notaliveyet development' heavily supported by modularity and unit testing, where you put the effort to be able to test most of the features of the application off-line.. But that's a paradigm shift and for small projects or for local desktop development sometimes it is simply an overkill.

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