Clear Stack in Visual Studio Immediate Window - c#

When working with the immediate window, one has to differ between runtime and designtime.
If I use the immediate Window on design time and put a local variable in stack:
string s = "test";
VS will start the compiler and create a new variable called s on the Heap and place a Pointer to it on a temporary stackframe it uses during designtime. (At least I think thats how it works, at least simplified. Please correct me if I'm wrong, though)
From now on, I am not able to use s for anything else, until I run my application or close VS:
int s = 12;
A local variable named 's' is already defined in this scope
I can use the contextmenu to clear the immediate window, but this really just clears the window itself. My local variables still stay on the stack.
I was wondering, if there is really not way to clear all variables I previously created inside the immediate window?
(Im using VS 2012 SP1 Prof. but I guess the issue stays the same with every version of VS)

I don't know the exact underpinnings of exactly what happens in visual studio, but it appears that VS keeps a compiled version in a vshost.exe process.
If you kill the associated process (i.e. WindowsFormsApplication1.vshost.exe *32), it will clear the stack and allow you to reuse the variable without having to restart VS.

Design-time debugging is described in this MSDN page. It is rather short on specific help that would address your issue. The example of Visual Basic code is not entirely by accident, this was an important feature in the VB6 IDE of old. And certainly more practical in that programming environment since it was common to write procedural code that was easy to test and debug with the Immediate window.
The quickest way I can think of clearing the execution state of the interpreter is to press F11 (Debug + Step Into) and cancel debugging. Or typing >Debug.StepInto and >Debug.StopDebugging. Not ideal.

Related

Start debugging specific project programmatically using EnvDTE.ExecuteCommand

I have a solution with multiple start-up projects, and I am trying to relaunch one of them automatically on a nightly basis, while keeping the new process attached to the same debugger.
I was able to restart the process (using Process.Start) and attach the current debugger to it, but it has not been highly reliable so far, and by design, clicking on the Stop button only detaches from the process rather than terminating it.
I am aware the Visual Studio team has released a Visual Studio extension that allows automatically attaching child processes to the current debugger, which may work better than my code, but it would not be portable as it requires a local configuration.
The easiest way to achieve what I need seems to programmatically relaunch the project using the IDE itself, as I would do manually by right clicking on the project and selecting Debug > Start New Instance. I have access to the relevant DTE object in my code (when in development).
Hence, is there any way to make the following pseudo-code work, asking Visual Studio to start debugging a specific project/exe by passing it as a command argument?
DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance", "ProjectToBeRestarted");
DTE.ExecuteCommand("Debug.Start", "ProjectToBeRestarted");
DTE.ExecuteCommand("Debug.Start", "ProjectToBeRestarted.exe");
I would like to avoid as much as possible manipulating the UI (like storing the original start-up projects, setting an new one, and restoring the start-up projects).
The problem you are facing is there are very few Visual Studio commands that accept arguments as input. This makes sense considering commands typically use the current IDE context (e.g. selection, caret position, etc.) to infer what should actually be done. For instance, the ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance command relies on the currently selected item in the Solution Explorer to know which project to start debugging, and it does not accept an argument.
For reference, you can find the full list of Visual Studio commands accepting arguments here: https://msdn.microsoft.com/en-us/library/c338aexd.aspx
To solve your issue, you will need to use the DTE object to set the current project selection first, and then execute the Startnewinstance command.
DTE.ToolWindows.SolutionExplorer.GetItem("SolutionNameHere\\ProjectNameHere").Select(vsUISelectionType.vsUISelectionTypeSelect)
DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance")
Note: Depending on your programming language, the double backslash escape may or may not be needed. The final string should only have a single backslash.

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.

Call stack time machine in Visual Studio 2010

I know the title is a bit ambitious, but I am wondering if there is a way, after displaying a previous state in the call stack window (Visual Studio 2010) when debugging a C# program, to restart (like when hitting "Continue"/F5) from there.
This would be particularly useful to debug a lambda expression that generates an exception, as there is no way to move outside.
For a real OO code time machine, the historical state of all objects would need to be stored in memory, so I doubt it is feasible at this stage.
Now if the state of all objects has not changed much, then we could keep the current state and jump back in time (as a shortcut to doing the same thing with "edit and continue").
Some times, you can right click on a stack frame and choose "Unwind to here" (or very similar wording). It's not always possible, and I'm not sure what the necessary conditions are, but I'm going to make a guess as to what might prevent it:
A native code frame on the call stack in the middle
Being halted at a StackOverflowException (obviously, death to a process in any case)
Maybe lambda expressions or other things that prevent Edit-and-Continue from working (?)
Basically, anything "unusual".
Other than that, if it works, then there you go!
This is a bit kludgy but:
While viewing the previous state in the call stack window, open the disassembly window (Debug | Windows | Disassembly or CTRL+ALT+D). Now you should be able to create a breakpoint which will stop execution when you get back to that location.
If you don't care what else executes, press F5 and allow the code to run back to your new breakpoint.
Now right click on the statement you want to restart from and select Set Next Statement. Press F5 to restart from there.
If you do care about what else executes on your way back to the new breakpoint you could use Set Next Statement to set the program counter to the end of the function you are in and use Shift+F11 to step out of that function (thus not executing any of the remaining logic in that function). Repeat as needed until you get back to your new breakpoint.
Note the various dire warnings about using Set Next Statement
Edit 6/18 When I tested the above I was running Visual Studio 2010 Ultimate. I just checked Visual Studio Express C# and it does not support the Disassembly Debug Window. When I can I'll check Visual Studio 2010 Professional and update this answer again. If you have Visual Studio Ultimate then the Intellitrace suggestion by #Hans is maybe a better bet.

Viewing variable values at runtime in VisualStudio

Is there any tool I can use to view the values of variables live as the code executes in VS?
Right now I can see them only when I keep a breakpoint.But,the problem is that the code works perfectly fine when I keep a breakpoint.it messes up only when it runs fast.
Any help would be appreciated.
Thanks
You can only view variables when you have a breakpoint, however you could just manually write the variable values to the Visual Studios Output window:
System.Diagnostics.Debug.WriteLine(variable);
I my opinion , rather than setting break points, you can use Debug.Write(yourVariable) under the Debug mode, so you can watch the value in the output windows.
Cheers.
Sounds like you need a conditional breakpoint. Aside from printing the values (console, debug output, trace) as the code runs there is nothing that will show you live data slow enough for you to see it. Put a conditional statement in detecting when the values are no longer valid and stick a programmatic break point on that.
Use Debug.Write to print out the variables. You can also use profiler.
All the aforementioned methods (dumping to console, using Debug.Write, custom logging, etc. etc.) to dump the contents of variables will do the trick .
From your problem description however (i.e. "...works fine with breakpoints, fails when left alone to run..."), it sounds like you have a threaded scenario with synchronization issues. If that's the case, inspecting the synchronization methods used might yield better results.
In visual studio 2010 (maybe in earlier versions, I didn't check) the conditional breakpoint can be set to print a variable value and continue running. It is done by right clicking the breakpoint and choosing 'When hit'. Then it opens a dialog in which you can specify what and how to print.
It worked fine for me in a native C project.

Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit?

I am writing a multi-threaded Windows application in Microsoft Visual C# 2008 Express Edition. Recently, the debugger has been acting strangely.
While I am Stepping Over lines of code using the F10, sometimes it will interpret my Step Over (F10) command just like a Continue command (F5) and then the program will resume running and the debugging session will be done.
Does anyone know why this happening? In what circumstances can the Step Over command result in the debugger stopping?
It's not a problem with the code being debugged: it doesn't just happen on particular lines of code. It happens on a random line that is different each time I run the debugger.
It's not a problem with my keyboard: the same thing happens when I just click Step Over in the Debug toolbar.
It may be a problem with the other threads in my program. Maybe one of them is randomly doing something that has a side effect of interrupting the debugger. Is that possible?
Thanks in advance!
You ought to take a look at this KB article and consider its matching hotfix.
EDIT: the hotfix does solve these kind of debugging problems. Unfortunately, the source code changes for the hotfix didn't make it back into the main branch and VS2010 shipped with the exact same problems. This got corrected again by its Service Pack 1.
I've seen this a few times. It generally happens when there's a context switch to another thread. So you might be stepping through thread with ID 11, you hit F10, and there's a pre-emptive context switch so now you're running on thread ID 12 and so Visual Studio merrily allows the code to continue.
There are some good debugging tips here:
Tip: Break only when a specific thread calls a method: To set a per-thread breakpoint, you need to uniquely identify a particular thread that you have given a name with its Name property. You can set a conditional breakpoint for a thread by creating a conditional expression such as "ThreadToStopOn" == Thread.CurrentThread.Name .
You can manually change the name of a thread in the Watch window by watching variable "myThread" and entering a Name value for it in the value window. If you don't have a current thread variable to work with, you can use Thread.CurrentThread.Name to set the current thread's name. There is also a private integer variable in the Thread class, DONT_USE_InternalThread, this is unique to each thread. You can use the Threads window to get to the thread you want to stop on, and in the Watch window, enter Thread.CurrentThread.DONT_USE_InternalThread to see the value of it so you can create the right conditional breakpoint expression.
EDIT: There are also some good tips here. I found this by googling for 'visual studio prevent thread switch while debugging'.
I find using a logfile is very handy when dealing with multiple threads.
Debugging threads is like the Huysenberg principle - observe too closely and you'll change the outcome !
Try this http://support.microsoft.com/kb/957912. Worked for me.

Categories

Resources