Extending visual studio debugger - visual-studio

I have linked list containing few tens of objects like this:
struct Item {
Item * next;
const char * name;
....
};
When I want to see in debugger in visual studio what item list holds, I need to hover/click on next many times to expand whole list until I hit nullptr. This is slow, error-prone (hand slips and I can start all over again) and not very organized.
Is there any scripting for VS2015 debugger available in which I could iterate whole list and just dump the name into console or whatever?
EDIT: I found about concord extensibility api ( https://blogs.msdn.microsoft.com/visualstudioalm/2015/10/02/announcing-visual-studio-debug-engine-extensibility-samples/ ) but it seems rather complex.
This is supposed to be in-house tool, so speed/ease of development is more important than robustness and/or easy of deployment.

If the data set you are working with is small, I would go with the tried and true method of std::cout.
Or just dump the contents of the list into a file and put a break point after that file is written to so you can check its contents before the program continues.

You can do it. Insert a Tracepoint (Right mouse button> Breakpoint >Insert Tracepoint) and READ CAREFULLY to whole text of that window. Then you will know HOW to print to the Output window WHAT you want.
Insert also a breakpoint on another line that is CONDITIONAL. Just put a normal breakpoint, then over the red ball, Right mouse button > Condition, then input
!next
Notice the !

Related

Is there a way to properly dump the navigation history in Visual Studio?

Very frequently, I will be looking for a specific section of code where something happens, and will reach there by starting at a function at a high level of abstraction and go lower by successively opening the code of called methods. Eventually I will find what I'm looking for, and I would like to save the path that I took to get there - which is pretty much what the call stack would be if I had put a breakpoint in that code and stopped here at runtime, except that I'm just inspecting the code.
I'm aware the little arrow next to the "Back" arrow lets me somewhat get that in the UI and I can then take a screenshot of what I'm shown, but that's not a fantastic solution. The names of the functions are trimmed (leading to cases where it could match several functions), the line number is seldom shown (only if there was no code at that line), and I would much rather have the text format to begin with so I can copy the function names into a search tool rather than type them from the screenshot later.
So I was wondering: is there a way to dump the navigation history in Visual Studio ?
Where I could for ex. ask for the last 50 cursor positions, and get the file, file path, line number & possibly the code at that line in text format or some more intelligent thing, should the IDE support that.
Thanks.
PS: I found this very similar question Is there extension for viewing navigation history in Visual studio? that's >5 years old and didn't have a satisfying answer, so I'm trying my luck again, hoping things have changed since if there was no solution back then.

Saving array contents to file using Visual Studio immediate window

I am using Visual Studio 2017 and C++ to debug a huge project
I don't use it frequently so I am not sure if this is possible or not, but is there any way to save all the contents of an array to a file using the immediate window? I have been looking around to find out the capabilities of the immediate window but there doesn't seem to be any place where this is clearly explained
This page comes up on google which only says it's possible to display contents of a variable, but doesn't give much more information
By looking around stackexchange I have found that a range of values in an array can be displayed using something like
array_name, 10
which will show the first 10 elements of an array, and this answer says there is a way to simply direct the output in the immediate window to a file, but my array has thousands of elements, and the array_name, XX trick only displays first 100 elements on the array in the immediate window
Is there a straightforward way to save contents of a variable or array to file in Visual Studio 2017 while the program is at a breakpoint?
You can get the content of any variable by copying it out of the watch window. From there you can pasted it into a file. I don't think there's anything to write it to a file from VS. You could of course have your program do that.
To get the variable values to the clipboard add a watch expression for your variable in the watch window (it's along the bottom of VS). However, don't just copy the expression (as that will get capped) expand it out then select all (Ctrl+A) and then right click Copy Value and you should get it to the clipboard. Depending on the contents of your array there might be truncation.

Can I set a conditional breakpoint without specifying a specific location?

Similar questions: One, Two. But this is not what I am looking for.
Similar questions, but said options are diabled: Three, Four, Five.
Situation: I want to identify the line where the value of the variable ApplianceState changes to the value normal. ApplianceState is an enum type and can have one of 4 different values. The project I am working on is quite huge and looking for it line-by-line could take days.
Question: Is there a way I can set a watch so that visual studio breaks at the line where the value of ApplianceState changes to normal?
I know I can set a conditional breakpoint, but that would mean I have to set a break point on certain line, and I don't want to do that.
Also, I have enabled native code debugging and the menu item New Data Breakpoint, in menu Debug -> New Breakpoint, is disabled (greyed out). So, I can't select it.

Visual Studio 2008 Debug Window to display timestamp?

I want to be able to see a time stamp in the beginning of every trace in the debug window in Visual studio.
[Time stamp here] The thread 'Win32 Thread' (0xcd0) has exited with code 0 (0x0).
[Time stamp here] => CLR ProvideAssembly: AppDomainId: 1, Ref: 'msvcm90d...
Example of this is the sysinternals application - DebugView. The problem is that I can't have Visual Studio debugging, and listening with DebugView at the same time, and I am not comfortable with adding the time stamp manually to my tracers.
Since the output window text is read-only once written, there's not an easy way to do exactly what you want to do. However, it's easy to do something similar: append a timestamp line after new text is written to the output window. This will make the output window a lot more messy, but you'll get your timings.
Here's how this would work: First, create a Visual Studio Add-in or Macro which hooks the PaneUpdated event of the Outlook Window's active pane. (See this thread for how to do this with a Macro approach). Make sure to check, in the event handler, that pane.Name == "Debug" and ignore other panes. Second, when you detect new text in the debug output pane, append a timestamp line, like this:
public void AddTimestamp(DTE2 dte)
{
// Retrieve and show the Output window.
OutputWindow outWin = dte.ToolWindows.OutputWindow;
pane = outWin.OutputWindowPanes.Item("Debug");
}
catch
{
pane = outWin.OutputWindowPanes.Add("Debug");
}
pane.OutputString("[timestamp: " + DateTime.Now.ToString() + "]\n");
}
It's also possible to pre-pend a timestamp to each line, but it's a lot harder. You can't change text already in the Output window (it's read-only), but you can clear the window and you can add text. So you could use the same event-handler approach above to detect text changes, but instead of appending you could copy the current text, prepend timestamps to any lines which don't have timestamps already, clear the window, and re-add the now-with-timestamps text. The problem with this is performance once your output window gets large. So you'd probably have to implement a kind of "lazy stamping" which does the clear and insert in the background, in order to avoid killing your IDE when (as is common) 100's of lines of debug output get emitted in a short time. Also, when you clear and re-add, if you're currently selecting text in the output window, your selection is lost.
Personally, I'd just do the easy thing and append timestamp lines rather than the harder pre-pend approach. Since stuff at the end of the line is hard to see without scrolling, I'd probably ensure there was a newline before the timestamp, so the user would see each batch of one or more output lines followed by one timestamp line.
It's possible there may be a way to hook the output window before text is displayed, but I couldn't find any such extensibility point in the VS Extensibility APIs.
One more idea: you could always roll your own tool window, e.g. "Ivan's Debug Output" which listens to events coming from the real output window, and echoes new lines (with timestamps) to your own tool window. This is probably the hardest option, but should do exactly what you want.
to add a new answer to an ANCIENT question, there's an feature in the productivity power tools 2013 extension and productivity power tools 2015 extension that add a timestamp margin to the output window, no code required.
I was looking for the same functionality. Colleague of mine came up with the $TICK macro in the message field, printing out the 'current' cpu ticks.
Take a look at these tips from Simon Chapman, too.
I wanted this functionality too, so eventually I wrote an extension to do it (much like Justin Grant suggested in the accepted answer). After using it for a while, I decided that relative timestamps were even more useful to me when debugging. If folks wanted absolute timestamps, I'm sure I could add that functionality back in. Anyway, if you're interested you can check it out at niahtextfilter.com.
And to show the relative timestamps in action in a Visual Studio debug session:

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