Is there any way to set or code breakpoints conditionally? - debugging

I've been wondering this for a while - is there a way to code/program breakpoints...? Conditionally? For example, can I specify something like - "when this variable becomes this value, break and open the debugger"? (Would be quite useful, especially in long loops when you want to debug loop execution of a late loop value.)
I suppose this may be IDE-specific since debugging is implemented differently in different IDEs... I'd be interested to know how to do this in any IDE, but specifically in Eclipse and Visual Studio.

This is definitely possible in Visual Studio. You can normally click in the left margin to insert the breakpoint, and then right click on that breakpoint. One of the options in the right click menu is "Condition...", and you can specify a predicate that will tell the debugger only the break on that breakpoint if the predicate is met.

In Visual Studio, you can declaratively set conditional breakpoint, which are like normal breakpoint but will only break when a certain condition is true. The condition can use local variables and whatever is accessible from where the breakpoint is set. Just right click any breakpoint (red dot) and select "Condition...".
In addition, .NET languages can call the Debugger.Break() method to programmatically break the execution. This also can be done within an if statement:
if (count > 8 && Debugger.IsAttached)
Debugger.Break();

If conditional breakpoints aren't supported by your IDE, add in an if statement and break inside of it.
if (variable == 3) {
// Stub code to attach breakpoint.
1 = 1;
}

Setting a conditional breakpoint in Eclipse (thanks for all the Visual Studio answers!):
Set a breakpoint. Right-click and choose "Breakpoint Properties...". Check "Enable Condition" and enter your condition code into the text area.

Most IDEs allow for conditional break points for this very reason. In Visual Studio, you can right click on the red dot for the breakpoint in the margin and open the condition dialog from there. You can also get at the condition dialog from the breakpoint window in Visual Studio. I am not familiar with Eclipse.

Related

Visual Studio: Is there a way to skip execution of code between two breakpoints?

I know I can comment the code but would be even better if there is a shortcut to skip execution of code between two breakpoints.
VS has a feature 'set next statement' which moves the program counter to the to that location and continues execution from there (skipping anything in between). You can read more about it at: https://learn.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger?view=vs-2017#BKMK_Set_the_next_statement_to_execute. The easiest way to use it is to either use the context menu item "Set Next Statement" (right click on where you want to set it) or hold down the ctrl key which changes the green "Run to click" editor glyphs into yellow "Set next statement" glyphs and just click on where you want to set it.
Set next statement is a great tool but it's really dangerous as a debugging tool. You're using the debugger to execute code in a way which would never happen normally. The results of which could cause crashes or other failures easily. It's real easy to do things like skipping over the initialization of a variable that's later used and will now cause an exception/crash.
It can be used in JS, .NET and native.

Visual Studio debug jump out of loop

I know about basic features of visual studio debugging. F10, F11, Shift+F11, Ctrl+F10.
If I am inside a for loop is there a way of stopping right after the loop is completed?
Right now the way I am doing it is to manually go to the location after the loop and press Ctrl+F10. Is there a better way of doing this?
There is no dedicated "Step Out of Loop" command in Visual Studio. "Step Out" (Shift+F11) works only for functions. There are only two options that I can think of:
Like Brian suggests, there is Run to Cursor, which has been there at least since VC++ 6. This is what you're already getting with the Ctrl+F10 keyboard shortcut. I use this literally all the time while debugging; it's an extremely useful tool. I don't really understand why you think this is a lousy way of doing it, or why you think there should be a "better" way.
You could set a simple breakpoint on the line of code immediately following the loop. This is relatively simple if you use the keyboard shortcut F9. But you still have to navigate to the appropriate line of code, so you might as well use Run to Cursor.
If you're working in a C-derived language, your loops probably conclude with a }. So you could use the Ctrl+] keyboard shortcut to move to the matching brace in the source file if your caret is at the loop's opening brace. That might make navigation easier. It certainly can help avoid moving your hands over to the mouse, killing precious seconds.
* Note that keyboard combinations are subject to change, depending on how you have configured your Visual Studio environment.
I just found out that if you hover with your cursor at beginning of the desired line, VS automatically blends in a little play symbol. When you click on it, debugger jumps to this point.
Perhaps you would like to use a breakpoint, which can be used to trigger the debugger once your program has reached a specific line. You can set one by clicking on the left side of the code line, where errors and arrows usually show up during debugging. Hope this helps!
Simple way is to put a break statement in the for loop and add a condition. This will allow you to test the loop while debugging.

How get a breakpoint on variable write in Visual Studio?

How I can set breakpoint on variable change (I think this is write access) in Visual Studio?
This is referred to as a Data Breakpoint in Visual Studio. To create one you'll need the address of the variable in question (just add &variableName) to the watch or immediate window. Then do the following
Debug -> New Breakpoint -> New Data Breakpoint
Enter the address in and size of the value in bytes
Note: This is only supported for C++ applications. Managed languages don't support data break points.
You need to add "Has Changed" condition to your breakpoint. To do this:
Set breakpoint on the line you want it to break when your variable is changed.
Right-click red dot icon, select "Condition".
Enter your variable name and select "Has Changed" option.
You may find more information in this MSDN how-to.
This is now supported in VS2019 for . NET Core 3.0 or higher check this out
How do I set a data breakpoint? Setting a data breakpoint is as easy as right-clicking on the property you’re
interested in watching inside the watch, autos, or locals window and
selecting “Break when value changes” in the context menu. All data
breakpoints are displayed in the Breakpoints window. They are also
represented by the standard, red breakpoint circle next to the
specified property.
If you right click on the break point you can can set Conditions... This lets you specify a if a variable value is true or if its changed.
Break point conditions
You can add a conditional breakpoint by:
Add a normal breakpoint
Right-Click on it and select "Condition"
Select "Has changed"
The breakpoint will only be hit when the condition inside the textbox has changed.
As far as I'm aware, the condition inside the textbox needs to be written in the language you are debugging. I.e. in C#: x >= 5
If you are just looking for the change of a variable, you can simply add the variable itself to the TextBox and the breakpoint will be hit when the variable changes.
HTH,
Christian

Visual Studio 2008 - Debugging tips/tricks - Continue "until next function" or "until next file"

Is there any way to tell the debugger to just continue until the next file is accessed, and/or until the next (developer written) function is accessed, without setting debug points ahead of time? I'm kind of new to VS debugging so all I use right now are f5, f10, and f11.
There is currently no way to do what you are asking. The main ways of telling VS to go until something happens are the following
Hit F5 and VS will go until the next user breakpoint or ,depending on your settings and where it occurs, the next exception is raised
Right click and select "Run to cursor"
Shift-F11 breaks out of the current method
Run to cursor doesn't require an explicit break point but it does require that you know where you want to break next.
You can right-click and select "run to cursor" if you just want to run to a specific line ahead in the execution stream.
Another one is Shift-F11 which finishes the current method and breaks again when you get back to the caller.
Actually, there is a way to set conditional break points.
Click in the left margin on the line where you want to break, as usual. (or F9)
Right-click on the red dot. In the context menu, click on "Condition...."
In the dialog, set your condition, e.g., fileName == "foo"
Hit F5 and go until the conditional break is hit.
Looks like there's not a way to do what I wanted to do

Hidden Features of Visual Studio (2005-2010)?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible.
For instance-
Crtl + R, Ctrl + W to show white spaces. Essential for editing Python build scripts.
Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor"
Create a String called Guides with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor.
What other hidden features have you stumbled upon?
Make a selection with ALT pressed - selects a square of text instead of whole lines.
Tracepoints!
Put a breakpoint on a line of code. Bring up the Breakpoints Window and right click on the new breakpoint. Select 'When Hit...'. By ticking the 'Print a message' check box Visual Studio will print out a message to the Debug Output every time the line of code is executed, rather than (or as well as) breaking on it. You can also get it to execute a macro as it passes the line.
You can drag code to the ToolBox. Try it!
Click an identifier (class name, variable, etc) then hit F12 for "Go To Definition". I'm always amazed how many people I watch code use the slower right-click -> "Go To Definition" method.
EDIT: Then you can use Ctrl+- to jump back to where you were.
CTRL+SHIFT+V will cycle through your clipboard, Visual Studio keeps a history of copies.
Sara Ford covers lots of lovely tips: http://blogs.msdn.com/saraford/archive/tags/Visual+Studio+2008+Tip+of+the+Day/default.aspx
But some of my favourites are Code Snippets, Ctrl + . to add a using <Namespace> or generate a method stub.
I can't live without that.
Check out a great list in the Visual Studio 2008 C# Keybinding poster: http://www.microsoft.com/downloadS/details.aspx?familyid=E5F902A8-5BB5-4CC6-907E-472809749973&displaylang=en
CTRL-K, CTRL-D
Reformat Document!
This is under the VB keybindings, not sure about C#
How many times do you debug an array in a quickwatch or a watch window and only have visual studio show you the first element? Add ",N" to the end of the definition to make studio show you the next N items as well. IE "this->m_myArray" becomes "this->m_array,5".
Incremental search: While having a source document open hit (CTRL + I) and type the word you are searching for you can hit (CTRL + I) again to see words matching your input.
You can use the following codes in the watch window.
#err - display last error
#err,hr - display last error as an HRESULT
#exception - display current exception
Ctrl-K, Ctrl-C to comment a block of text with // at the start
Ctrl-K, Ctrl-U to uncomment a block of text with // at the start
Can't live without it! :)
Stopping the debugger from stepping into trivial functions.
When you’re stepping through code in the debugger, you can spend a lot of time stepping in and out of functions you’re not particularly interested in, with names such as GetID(), or std::vector<>(), to pick a C++ example. You can use the registry to make the debugger ignore these.
For Visual Studio 2005, you have to go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio \8.0\NativeDE\StepOver and add string values containing regular expressions for each function or set of functions you wish to exclude; e.g.
std::vector.*::.*
TextBox::GetID
You can also override these for individual exceptions. For instance, suppose you did want to step into the vector class’s destructor:
std::vector.*::\~.*=StepInto
You can find details for other versions of Visual Studio at http://blogs.msdn.com/andypennell/archive/2004/02/06/69004.aspx
Ctrl-F10: run to cursor during debugging. Took me ages to find this, and I use it all the time;
Ctrl-E, Ctrl-D: apply standard formatting (which you can define).
TAB key feature.
If you know snippet key name, write and click double Tab. for example:
Write
foreach
and then click tab key twice to
foreach (object var in collection_to_loop)
{
}
2. If you write any event, write here
Button btn = new Button();
btn.Click +=
and then click tab key twice to
private void Form1_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
btn_Click function write automatically
in XAML Editor, Write any event. for example:
MouseLeftButtonDown then click tab
MouseLeftButtonDown="" then click tab again
MouseLeftButtonDown="Button_MouseLeftButtonDown" in the code section Button_MouseLeftButtonDown method created.
Sara Ford has this market cornered.
http://blogs.msdn.com/saraford/default.aspx
More Visual Studio tips and tricks than you can shake a stick at.
Some others:
The Visual Studio 2005 and 2008 3-month trial editions are fully-functional, and can be used indefinitely (forever) by setting the system clock back prior to opening VS. Then, when VS is opened, set the system clock forward again so your datetimes aren't screwed up.
But that's really piracy and I can't recommend it, especially when anybody with a .edu address can get a fully-functional Pro version of VS2008 through Microsoft Dreamspark.
You can use Visual Studio to open 3rd-party executables, and browse embedded resources (dialogs, string tables, images, etc) stored within.
Debugging visualizers are not exactly a "hidden" feature but they are somewhat neglected, and super-useful, since in addition to using the provided visualizers you can roll your own for specific data sets.
Debugger's "Set Instruction Pointer" or "Set Next Statement" command.
Conditional breakpoints (as KiwiBastard noted).
You can use Quickwatch etc. to evaluate not only the value of a variable, but runtime expressions around that variable.
T4 (Text Template Transformation Toolkit). T4 is a code generator built right into Visual Studio
Custom IntelliSense dropdown height, for example displaying 50 items instead of the default which is IMO ridiculously small (8).
(To do that, just resize the dropdown next time you see it, and Visual Studio will remember the size you selected next time it opens a dropdown.)
Discovered today:
Ctrl + .
Brings up the context menu for refactoring (then one that's accessible via the underlined last letter of a class/method/property you've just renamed - mouse over for menu or "Ctrl" + ".")
A lot of people don't know or use the debugger to it's fullest - I.E. just use it to stop code, but right click on the red circle and there are a lot more options such as break on condition, run code on break.
Also you can change variable values at runtime using the debugger which is a great feature - saves rerunning code to fix a silly logic error etc.
Line transpose, Shift-Alt-T
Swaps two line (current and next) and moves cursor to the next line. I'm lovin it. I've even written a macro which changed again position by one line, executed line transpose and changed line position again so it all looking like I swapping current line with previous (Reverse line transpose).
Word transpose, Shift-Ctrl-T
When developing C++, Ctrl-F7 compiles the current file only.
Document Outline in the FormsDesigner (CTRL + ALT + T)
Fast control renaming, ordering and more!
To auto-sync current file with Solution Explorer. So don't have to look where the file lives in the project structure
Tools -> Options -> Projects and Solutions -> "Track Active Item in Solution Explorer"
Edit: If this gets too annoying for you then you can use Dan Vanderboom's macro to invoke this feature on demand through a keystroke.
(Note: Taken from the comment below by Jerry).
I'm not sure if it's "hidden", but not many people know about it -- pseudoregisters. Comes very handy when debugging, I've #ERR, hr in my watch window all the time.
Ctrl-Minus, Ctrl-Plus, navigates back and forward where you've been recently (only open files, though).
I don't use it often, but I do love:
ctrl-alt + mouse select
To select in a rectangular block, to 'block' boundaries.
As noted in comments,
alt + mouse select
Does just a plain rectangular block.
Here's something I learned (for C#):
You can move the cursor to the opening curly brace from the closing curly brace by pressing Control + ].
I learned this on an SO topic that's a dupe of this one:
“Hidden Secrets” of the Visual Studio .NET debugger?
CTRL + Shift + U -> Uppercase highlighted section.
CTRL + U -> Lowercase the highlighted section
Great for getting my SQL Statements looking just right when putting them into string queries.
Also useful for code you've found online where EVERYTHING IS IN CAPS.
Middle Mouse Button Click on the editor tab closes the tab.
To display any chunk of data as an n-byte "array", use the following syntax in Visual Studio's QuickWatch window:
variable, n
For example, to view a variable named foo as a 256-byte array, enter the following expression in the QuickWatch window:
foo, 256
This is particularly useful when viewing strings that aren't null-terminated or data that's only accessible via a pointer. You can use Visual Studio's Memory window to achieve a similar result, but using the QuickWatch window is often more convenient for a quick check.

Resources