"Hidden Secrets" of the Visual Studio .NET debugger? [closed] - visual-studio

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As much as I generally don't like the discussion/subjective posts on SO, I have really come to appreciate the "Hidden Secrets" set of posts that people have put together. They provide a great overview of some commonly missed tools that you might now otherwise discover.
For this question I would like to explore the Visual Studio .NET debugger. What are some of the "hidden secrets" in the VS.NET debugger that you use often or recently discovered and wish you would have known long ago?

One of my favorite features is the "When Hit..." option available on a breakpoint. You can print a message with the value of a variable along with lots of other information, such as:
$ADDRESS - Current Instruction
$CALLER - Previous Function Name
$CALLSTACK - Call Stack
$FUNCTION - Current Function Name
$PID - Process ID
$PNAME - Process Name
$TID - Thread ID
$TNAME - Thread Name
You can also have it run a macro, but I've never used that feature.

You can right-click an object in the Watch window and click Make Object ID.
It will assign that instance an ID number, allowing you to see, in a complicated object graph, which objects refer to the same instance.

For .net applications System.Diagnostics has lots of useful debugging things. The Debugger class for example:
Debugger.Break(); // Programmatically set a break point
Debugger.Launch(); // Launch the debugger if not already attached
Debugger.IsAttached // Check if the debugger is attached
System.Diagnostics also has lots of good attributes. The two I've used are the debugger display attribute for changing the details put into the locals window and the step through attribute for skipping code you don't care about debugging:
// Displays the value of Property1 for any "MyClass" instance in the debugger
[DebuggerDisplay("{Property1}")]
public class MyClass {
public string Property1 { get; set; }
[DebuggerStepThrough]
public void DontStepInto() {
// An action we don't want to debug
}
}

As a web developer who works with Web Services that are within the same solution as my front-end code most of the time, I found the ability to "attach" to a process to be a HUGE time saver.
Before I found this hidden gem, I would always have to set a breakpoint on some front-end code that called a web service method and step into it. Now that I know about this trick/feature I can easily set breakpoints on any part of my code that I want to which saves me loads of time and effort.

$exception in the watch window will show the exception that is currently being processed even if you don't have a catch that assign the Exception instance to a named variable.

The threads window, from Debug -> Windows -> Threads. You can Freeze and Thaw threads, and switch the active thread. This is awesome when debugging or replicating an issue with a multithreading application.
You can drag & drop the yellow "Next Statement" arrow to another place. When the program resumes, it will resume execution at that statement. You can add it to the toolbar, a blue arrow called Set Next Statement, but it's not there by default.
You can "undo" the navigation you did, like scrolling, going to another file, or jumping to a reference. The shortcut is ctrl-- (control minus.) That way you can jump into a function, examine the code there, and go back to where you were without looking.

Conditional breakpoints.

You can load windbg extensions into the Visual Studio debugger and use them from the immediate window.

As posted in another post Sara Ford is doing a current series on the VS debugger.
Her blog is the best source of VS tips: http://blogs.msdn.com/saraford/archive/tags/Visual+Studio+2008+Tip+of+the+Day/default.aspx

This is kind of an old one. If you add a watch expression err,hr, then this will hold the result of GetLastError(), formatted as an HRESULT (VC++ debugger only).

You can drag current line cursor (yellow arrow) up and down your code when execution is paused.
Additionally, in order to enable this during pause on exception you have to click "enable editing" on exception details first.
You can also make VS break on handled exceptions by checking one's of interest under:
Debug->Exceptions : Thrown column

Some useful shortcut keys.
F11 to step into a method.
Shift-F11 to step out of a method.
F10 to step over a method.

Things I use often:
Click the menu item "Debug | Exceptions" (or Ctrl-D, E for short) and you can enable breaking at the time that any exception is thrown, or choose to not break on certain exceptions.
You can set up the debugger to download some of the framework source code and symbols from a MS server and step into the framework code. (Some libraries, like System.ServiceModel, are not yet available). It in the Options windows under Debugging. See MSDN How-To.
You can use the VS.NET debugger to debug Javascript running in IE. You just need to install the IE javascript debugger, and enable javascript debugging in IE's settings. Then on a JS error it will pop up a "do you want to debug" dialog box, and you can choose to debug in VS.NET.

You can open and place a breakpoint in a source file if the file belongs to another solution (external file). The debugger can still hit the breakpoint. No need to open another Visual Studio instance to debug the external file. Helpful in debugging web services which you source to. This works as long as all the sources are current and compiled.

Related

How to analyze UWP application UI freeze?

My UWP app goes into UI freeze state sometimes and I don't know why。 I've checked the code about view model and async-await calls. And I've tried to use the performance profile tool in Visual Studio to get timeline but it only shows the time and duration time about the UI freeze. I have run out of ideas now.
I tried the dotTrace but it seems that I cannot use it to profile UWP application. Even I " disable the Compile with .NET Native tool chain option in Visual Studio (via the menu Project | Properties... | Build) and rebuild the project."
https://learn.microsoft.com/en-gb/visualstudio/profiling/profiling-feature-tour?view=vs-2019
There are many reasons for UI freezing, including code endless loops, asynchronous methods are not handled properly, program errors, etc.
Most of them occur in asynchronous method processing and UI rendering.
When calling asynchronous methods, use the async/await keywords, like:
//define
public async Task asyncMethod()
{ }
//use
await asyncMethod();
Reduce resource consumption when rendering a large number of data templates through virtualization.
If you have a large list to render, if virtualization is not enabled (referring to controls with virtualization, such as ListView), or used, but the conditions of virtualization are destroyed (such as adding ScrollViewer outside ListView ), This will also cause the UI to freeze and will not return to normal until the list is rendered.
Please check your code for the above problems, or provide a minimal reproducible demo so that we can analyze where the problem occurs.
Best regards.
I would suggest you try to use the Visual Studio debugger to find out what the code is doing.
First, make sure that you are set "Debug" mode and that the debugger is going to run on "Local Machine" (there are other options here, but I'm trying to keep things simple).
Then, click on the "Local Machine" button to run your app using the debugger.
Once your app freezes, click on Debug-Break All:
After that, I suggest you use the various Debug commands to further debug your application.
For example, you can use the "Call Stack" menu item/window to view what your code is doing. You can also use the "Threads" menu to see what threads are running. If you have suspect areas in your code, you might consider adding System.Diagnostics.Debug.WriteLine() statements to print out informative messages, and then use the "Output" menu item/window to see what is happening.
If your app first freezes, and then crashes after some time, then this could be because your tasks don't have correct exception handling. You might consider adding an UnobservedTaskException handler to your code to help you find this problem.

How Can Watch Variables be Configured in a Watch Window Before Running a Debug Session in VS2017?

In all of my searching, I have not come across any trick, plug-in, or setting that would allow me to pre-populate a Watch Window for use during debugging.
The well-known steps to watch a variable in Visual Studio 2017 is to set a breakpoint (perhaps on the first instance of a variable being assigned a value), then, adding the variable to a Watch Window. On subsequent runs, that watched variable should remain in the Watch Window.
Is there a way to accomplish pre-populating the Watch Window before a debugging session? I have code that runs in a timed sequence. Taking the extended time during an execution break to pause and set up a watch causes the program to crash. Such timeout crashes while setting up variable watch objects makes for difficult interaction with the debugger. Pre-populating the watch list would help considerably.
I know that I could use a technique such as using Debug.Print(...) statements, which are printed to the Output Window during code execution. However, this doesn't allow me the control and visual feedback to my debugging efforts that comes from a Watch Window.
Watches can only be evaluated when you are paused in the debugger, say on a breakpoint. They can't be evaluated during normal execution. Your options to get around this limiation are:
Add Debug.Print(...) or something similar to your code that outputs a value.
Similar to #1 add a TracePoint which you'll find in the actions setting of a breakpoints setting (that's the gear icon when you hover over a breakpoint). When the TracePoints are hit they will then evaluate the expression that you specficied in the actions window and log it to the Output window. The advantage of TracePoints over adding your own logging is that you can turn it off and on without building your code. More info at: https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019#BKMK_Print_to_the_Output_window_with_tracepoints
Use the VS Enterprise only feature Snapshots which is part of IntelliTrace. Basically set your breakpoints but rather than stopping on them to look at the watch just continue. Each time you stop a snapshot of the process will be taken capturing the state of your application at that time. Then once you're finished use the Diagnostic Tools window to select each of the snasphots and activate them. For each snapshot you can use the debugger just as if you stopped the application. So you can use watches and inspect etc. Of course you can't step as the app has already ran but you can go to the next snapshot etc. More info at: https://learn.microsoft.com/en-us/visualstudio/debugger/view-snapshots-with-intellitrace?view=vs-2019 and https://devblogs.microsoft.com/visualstudio/step-back-while-debugging-with-intellitrace/
How Can Watch Variables be Configured in a Watch Window Before Running
a Debug Session in VS2017?
I'm afraid the answer is negative.For now,the Watch window can only be configured after the debug session start.It's like a runtime window only occurs during debugging.
So we can't pre-populate it before debug session for now. In other words, it's by design.
As alternative ways,you can follow Andy's detailed suggestions above.
And since your needs is meaningful in some specific debugging situation, you can also post your suggestion on development community like a user voice to add a new feature.

Visual Studio 2010 - Memory Window - Edit Value

I tried looking on MSDN, Google and Stack Overflow and I couldn't find an answer to what I'm looking for.
Is there a way to edit, through the Memory Window, the code at a given address? I use the Disassembly Window to get the address of the instruction I would like to overwrite, find it in the Memory Window but "Edit Value" is grayed out. Any reason why? Is it because my code gets cached and VS prevents me to edit it? Is there a way to change that through project settings?
Thank you
The application is consisted of data parts and executable parts of code. Windows forbids the changes to executable parts by default, but this can be changed from the code with VirtualProtect function (also pay attention to remarks and FlushInstructionCache).
Maybe your ultimate goal is not to change some code from debugger, but something else that can be achieved differently. What do you really want?

Can VS be made to eval a debug watch even while the application is still running?

Normally in Visual Studio, a watch cannot be evaluated unless the debugger is stopped at a breakpoint. Is there a trick or add-on to make Visual Studio evaluate a watch while the application is still running? For example, evaluate the watch every time execution passes a point in the code while it's still running and without changing the code to insert statements like Debug.WriteLine.
Not sure this is possible, but I thought I'd ask.
Yes, this is possible. Set a breakpoint at the location where you'd want to see the value. Right-click the breakpoint and choose "When Hit...". Tick "Print a message" and write an expression like { value }. The message is displayed in the Output window while your program runs.
I would do that using compiler directives.
#if DEBUG
Debug.WriteLine
#end if
No this is not possible to do. The evaluation feature in Visual Studio is a stack frame based mechanism. That is that every evaluation is done in the context of a given stack frame (as viewed through the stack window). When the program is running the set of stack frames is currently changing and hence it's not possible to do a stable evaluation.
Additionally there are other limitations in the CLR which prevent this from managed code. It's not possible for instance to execute a function unless the debugee process is in a very specific state.

Debugging in Dynamics AX

I'm facing some troubles still while learning, so I guess it tends to get worse once I play with the big kids: warnings in dynamics aren't as precise and informative as VS's, there are no mouse-over tips, and exceptions to show me exactly where I've got it wrong.
I'm just too used to Visual Studio, it's intellisense and all the tools (dynamics is quite new when compared to Visual Studio)
More than solving simple code issues, i'd like to learn how to solve upcomming ones i might have in code not written by me or anything else i'd solve in 3 minutes in Visual Studio, as well as tips on how to survive in dynamics ax without all the Visual Studio tools.
The code editor in Dynamics AX has some intellisense, typing the name of a table or class variable followed by . or :: will give you a list of fields or methods available for that item. After you type the ( to start a method call, a tooltip pops up with parameters available on that method. When starting a new line, you can right click and List Tables, List Classes, List Types, etc. Most of those commands are also available via Shortcut Keys. Note that the intellisense only works if all the code in the method up to the location of your cursor is syntactically correct.
Make sure you have updated the cross reference in your development environment (Tools/Development tools/Cross-reference/Periodic/Update). With an updated cross reference, you can right click an any table, field, class, method, extended data type, or enum in the AOT and choose Add-Ins/Cross-reference/Used by to see where that item is used in the system.
You can also use Tools/Development tools/Code explorer to view the source to the application with all types, variables, and methods turned into hyperlinks so you can click to go right to the definition of that item.
Another useful tool is Application hierarchy tree, available either under Tools/Development tools, or on the right click Add-Ins menu. This will show you the class hierarchy, so you can easily see, for example, that SalesFormLetter derives from FormLetter, which derives from RunBaseBatch.
In the editor, you can highlight text and right click to Lookup Properties/Methods or Lookup Definition.
If you are trying to track down where in the system a particular infolog message is generated there are two strategies to use:
Set a breakpoint on the first line
of the method Info.add(). Then when
you run the code generating the
message, you will pop into the
debugger as soon as the infolog is
generated. You can then look at the stack
trace in the debugger to see where the code is that
generated the message.
Run Tools/Development
tools/Label/Label editor and search
for the text of the message. Select
the Label ID of the message, then
click Used by to see where that
message is used in the system.
There is also http://www.axassist.com/ which extends intellisense and many other extensions
What these guys said already is very interesting and helpful.
I'd like to add that within AX in real life you are probably working with multiple contexts. e.g. Code running in the client, code running in server, code running in p-code and in IL, COM integrations, Enterprise portal and so on.
My point is, if you want to figure something out through debugging, you must first understand where the code(s) you'd like to debug is running.
Knowing that is important because you might have to allow debugging or give permissions in multiple places.
Examples:
Windows AD debugging users (add yourself)
Allow debugging on client
Allow it on server
Disable IL if you want to use MorphX, otherwise attach the process in VS.
Allow World Wide Web Publishing Service to interact with desktop for EP.
One last thing, you are starting to work with ax right now, perhaps you will need to work with AX7(Dynamics 365 for Operations). This version of the system works only with visual studio. It is still x++, but you have a lot of the things VS provides you.
Take a look on EditorScripts Class,On AX Editor you can use it by right click and choose "Scripts". It is a kind of intellisense that can make by your self, for example: here is my in-line comment whenever I type "mycom" and press "tab"
public void template_flow_mycom(Editor editor)
{
xppSource xppSource = new xppSource(editor.columnNo());
int currentline = editor.currentLineNo();
int currentcol = editor.columnNo();
Source template = "//Partner comment "+date2str(today(),123,2,1,3,1,4, DateFlags::FormatAll )+" at "+time2str(timenow(), 1, 1)+" by MAX - Begin\n";
template+=strRep(" ", currentcol)+ "\n";
template+=strRep(" ", currentcol)+ "//Partner comment "+date2str(today(),123,2,1,3,1,4, DateFlags::FormatAll )+" at "+time2str(timenow(), 1, 1)+" by MAX - End\n";
editor.insertLines(template);
//move cursor to the empty line between the comments
editor.gotoLine(currentline+2);
editor.gotoCol(currentcol+4);
}

Resources