Debugging C# applications - c#

I´m coming from a PHP background where my debugging "tools" are basically echo, var_dump and exit. While I know the importance of debugging, I never tried to use/learn a debugging tool.
Now I´m learning C# and I think I can´t really program without an extensive knowledge of this area.
So my question is: where can I learn what is and how to do debugging? I know what is a breakpoint (conceptually), but how to use it? How to use Step into and Step over? Basic things like that.
As a related question, there is anything like var_dump in C# (Visual Studio), where I can inspect any object.
I find very difficult and painful to do a foreach for every array/list to see the contents, specially now that I´m still learning the language.

Microsoft has an extensive guide on C# debugging in Visual Studio that might be helpful. VS has a lot of powerful debugging functionality; for example, rather than doing a foreach to see the contents of an array as you were describing, you could set a breakpoint (pausing the execution of the program) and select the variable you wish to see the contents of (array or list or whatever) and see what it contains, without having to write any extra code. Step Into and Step Over can be used to continue execution of the program but only incrementally so that you can continue to see how variables change, where the flow of execution currently is, etc.

This has been covered earlier on StackOverflow:
Best Visual Studio 2008 Debugging Tutorial?

So, your compiled applications can be run in a "debug" mode from which visual studio can monitor the internal workings of the application and even control it.
A break point can be placed just about anywhere in your code by clicking to the far left of the line (kinda in the margin of the visual studio text editor). When that line of code has been reached, the visual studio debugger will actually pause the execution of your program and bring you back to the editor where you can literally hover over a variable or object or whatever and see everything about it.
There is also a "Locals" window available that will give you the break down of all of your locally scoped items - this should pop up by default at the bottom of your screen when debugging.
In debug mode you can navigate the execution of your code line-by-line
F10 will continue with the next line of code.
F11 will attempt to drill down into what ever functions are on the current line of code
Ctrl-D will bring up a "Quick Watch" window giving you all information about the currently selected variable/object.
Once you are in debug mode there are tons of things you can do - in some cases you can even edit the code as you go.
The easiest way to get into debug mode is to use the little "play" button up at the top of visual studio - and when a break point is reached it will enter debug mode and highlight the currently executing line of code.
You can also hit F10 from the editor and your application will be started and paused on the very first line of code.
By comparison, in PHP, you had to actually write "debugging code" into your application - using Visual Studio you can actually monitor the execution of your code without adding a thing to your existing code.
I hope that gets you started.
You might want to also read up on your IDE a bit to. There is a metric ton of stuff in visual studio that will help you navigate your code in ways you never imagined in most PHP editors.

If you've already downloaded Microsoft Visual Studio, you'd might want to check out the Visual C# Express Library available for free over at: http://msdn.com/express/
It's located down the bottom of the page and is very useful. It contains pretty much every answer you might be looking for as a beginner to the C# Language. ...Welcome to C#, my friend :-D

Related

C# Step Into variable list

There usually is a variable list at the bottom of the screen that helps me follow the value of different variables in my app while using the f11 'step into' function, but since I updated to web developer 2012 I can't seem to find this list. Was it removed? or is there a way to open it? thanks!
Set a break point in the project, start debugging your application, once you hit the break point, go to Visual web developer, Under Deubg-> Windows, see if you find Locals option. That will show the local variables during debugging.

Getting debugger context in C# interactive

C# Interactive seems a lot more powerful than the Immediate Window (at least it handles lambda expressions that are often used in LINQ - see Visual Studio debugging "quick watch" tool and lambda expressions), but it looks like it can't be used as a replacement as it doesn't know about the debugger context. Is there a way to have access to the debugger context?
I've seen Getting debugger context in F# interactive and it might require the same things, but maybe there are new/different things available.
http://extendedimmediatewin.codeplex.com/ could be useful but looks quite dead, although someone said on Oct 18 2011 that he was planning to port it to VB.Net ( http://extendedimmediatewin.codeplex.com/discussions/75589 ).
Not a complete solution, but in VS2015, after you've run Initialize Interactive with Project, you can use Debug > Attach to Process to connect to the InteractiveHost.exe process.
You can then debug functions from your project. You won't be able to debug one-off functions in the Interactive window, though, as Kevin explained.
As as side note, https://stackoverflow.com/a/40650343/467110 points out that you may have to have a C# Interactive window open before you open your solution in order to successfully Initialize Interactive with Project
Disclaimer: I work for Microsoft on the Roslyn team.
Unfortunately, we don't have a way to get the debugger context right now. We are aware that it would useful, and as we get more of the core deliverables for Roslyn completed we hope to investigate more and see what can be done.
Inside C# Interactive you can run
System.Diagnostics.Debugger.Launch();
to request a debuger, whereby you will get a window asking you to choose one of the open Visual Studio instances or a new instance to attach. Assuming you used "Load Interactive with the Project" option of Visual Studio - any breakpoints in the open Solution will now be hit when code is ran by Interactive.
If you need the debugger without pre-existing code - you can now insert
System.Diagnostics.Debugger.Debug();
calls into the code you put into Interactive (but it does have to go in one 'chunk', i.e. one press of 'enter'), and you will be able to examine local vars via 'locals' window and run code against interactive context via 'immediate' window.

VS 2010 - Error when opening User Control / Form with Designer

C#, VS2010, WinForm application:
Sometimes I do have the problem that I get an error message when opening some of my controls / forms. All code compiles and the application runs properly. Opening the control in the designer gives me:
The designer loader did not provide a root component but has not indicated why.
From my experience I can tell, it is usually something in my code which does not get properly initialized, e.g. a property is not set which is somehow available at runtime, but not when opened with the designer. The only issue is, that the root cause is hard to find.
Q: Is there a chance to somehow use the debugger when the designer opens my component in Visual Studio 2010? That would help a lot and the problem tackling is most likely a matter of minutes then.
Remark: Just to make this clear, I know how to use the debugger ;-), I only have no idea how I could tell VS2010's designer to open my control in Debug mode.
As of 2nd SEP 2010 added:
Thanks for your help. Basically it is the MSDN Library article describing how to do it.
I have managed to set it up and run the second instance
(there was not much to understand how to do it).
It only fails in my case, because the 2nd VS2010 instance (debugging Design Time) fails to find the
symbols for my custom control. I have added the symbols manually under Debugging / symbols. No
result, still "Breakpoint won't be hit because of missing symbols"
BTW, using this approach it is helpful to exclude some stuff from the symbol loading (via modules window), because this will safe a lot of time.
Now if have to figure out how to get the symbols resolved and then I can tackle the issue.....
The vast majority of design time problems with custom controls are caused by code in the event handlers or method overrides in your control running at design time as well as run time. That's normally desirable, you get instant feedback when you change a property in the Properties window for example.
But not desirable when the code depends on something that's available at runtime but not design time. Like a dbase connection or a file that's stored in the build folder. That can generate exceptions and Visual Studio isn't very robust against handling exceptions at design time. Worst case, you can crash VS to the desktop without any diagnostic. But anything is possible.
Review the code in your control and make sure that the bits of code that should only run at runtime are wrapped like this:
if (!DesignMode) {
// etc..
}
Hard cases can be diagnosed with the debugging tips in this MSDN Library article.
To debug your control in design mode, you need two instances of Visual Studio. In the first instance, open the project which contains this control source code. In the Project Properties, Debugger, set command line which calls another Visual Studio instance (msdev? don't know exactly for VS2010 - take it from the shortcut), Then execute "Start Debugging" command. Another Visual Studio instance starts. In this instance open client project which uses your control on the form.

Displaying console output?

I am currently creating a customer application for a local company. I have a datagridview linked to the customers table, and I am trying to link it up so that updates, inserts and deletions are handled correctly. I am very new to c# so I am starting with the basics (like about 2 days ago I knew nothing - I know vb.net, Java and several other languages though..).
Anywho from what I understand anything output through Debug.WriteLine should only appear when in debug mode (common sense really) but anything output through Concole.WriteLine should appear whether or not in debug mode. However I have checked the immediate and output windows and nothing is being output when in normal mode. Does anyone have any idea why this is??
Edit: I have event handlers for clicking a cell - it should output CellClicked and set the gridview to invisible when a cell is clicked. The latter works whichever mode I am in, but CellClicked is only output in debug mode. I am using Console.WriteLine("CellClicked").
Edit: Seems I may have solved it - I just set the output to Console Application in the project settings pages. It now opens a command line window as well as a windows form, but I can change the output back again when I compile for distribution. Thanks for the help.
Console.WriteLine() outputs to the console window in the case of a console app only.
You are probably looking for Trace.WriteLine().
Getting the output of Console.Write/Line() written to the Visual Studio Output window is a feature of the Visual Studio Hosting process. Project + Properties, Debug tab. This will not work if you run your app without a debugger, the hosting process isn't being used.
Using Console.WriteLine for debugging isn't the greatest solution. That code will still run in your Release build and take time formatting the output string. And prevent the JIT optimizer from doing a good job generating the most efficient machine code. Output will fall in the bit bucket, nothing to actually write it to.
And it is unnecessary, the debugger gives you much better tools to find out what is going on in your program. Take some time to familiarize yourself with its capabilities. If you want to find out if an event handler runs, just set a breakpoint. Such a breakpoint can even trace output without actually breaking. Right-click the red dot, click "When hit" and use the "Print message" option.
I think you'll like the tracing infrastructure a lot better than Console.WriteLine. Tracing gives you many different options for where the trace messages can go, as well as being able to turn them on or off. You can also set different levels of tracing output so that you can adjust how much logging actually gets done. The built in tracing in .NET is very flexible, and is well worth the investment to learn.
Here are a couple of references to help you get started:
http://msdn.microsoft.com/en-us/library/ms228993.aspx
http://msdn.microsoft.com/en-us/library/ms228984.aspx
http://www.code-magazine.com/Article.aspx?quickid=0409081
HTH!
Chris
You could go to Tools | Options | Look for Debugging, General, Choose the Redirect all Output Window text to the immediate window, or try to log the console-intended output to a file and view it there instead.

Is there a way to *completely* disable Edit and Continue?

I was wondering if there was a way to completely lock my code while debugging it within Visual Studio 2008. The code documents lock automatically when running as 64 bit applications, which I greatly prefer; however, I do most of my coding making add-ins for Excel, which is 32 bit. The result is that even though I target 'AnyCPU', the VS host knows that it is running within a 32 bit process and, therefore, the source code is not locked while the code is running hosted in Visual Studio.
I can turn off Edit and Continue by going to Tools > Options > Debugging > Edit and Continue, and then unchecking the 'Enabled Edit and Continue' check box. This does not completely lock the code, however. This does prevent any edits in the code from being executed in the current run, but it does not prevent mouse clicks or keystrokes from actually changing the code.
Again, when working with 64 bit applications this does not occur -- the code is completely locked. I greatly prefer the code to be completely locked for at least a couple of reasons:
I can accidentally hit a key or the like while debugging, which I definitely do not want to do. It's rare, but it is an issue.
Many of my automated tests drive the user interface via SendKeys. When stepping through such a test using the debugger, however, I can sometimes forget that some of the aspects involve SendKeys, which means that keystrokes wind up getting sent to the Visual Studio IDE instead of Excel.
In issue #2, above, the unit test fails, which is fine -- my bad -- but having all the keystrokes sent to the code module and destroying my code is completely unacceptable.
Does anyone have any ideas here? Can one completely lock the code when running hosted in Visual Studio while compiled against a 32 bit CPU?
Some related posts on this issue, but none of which directly address this:
How to: Enable and Disable Edit and Continue
“Changes to 64-bit applications are not allowed” when debugging in Visual Studio 2008
How do I enable file editing in Visual Studio’s debug mode?
How does “Edit and continue” work in Visual Studio?
Can we edit our code while running the application
Editing C# while debugging
Thanks in advance for any help or ideas...
Mike
Here is a trick I use under Visual Studio 2005 (don't have a chance to test under Visual Studio 2008, but it should work):
Open the executable assembly's properties
Go to the Debug tab
Check the Enable unmanaged code debugging checkbox
The code documents should stay locked, even when a breakpoint is hit, and any attempt to change it should trigger a popup saying "Changes are not allowed when unmanaged debugging is enabled".
Hey there - sorry I can't help you with completely locking your code - I have the opposite desire: to completely UNLOCK it during debug, but I can help you with your second issue.
I suggest that you consider checking the active window before sending any keys and if the active window is other than your target site, pause the execution of your test until focus is returned that that window.
I know it's not the solution you want, but it probably wouldn't hurt to prevent other similar issues.
Best of luck!
Adam
Here is the best I could come up with. It works, but there are some steps you may not want to take.
Essentially, the technique is to set the files of your project to Read-Only when you run the application, and then set them back to writable once your application ends.
However, in VS2k8, by default, setting a file to Read-Only still allows you to edit the file. You need to first turn off the setting "Allow editing of read-only files..." in Tools > Options > Environment > Documents.
Second, you need to add the following key to the registry as a DWORD and set its value to 1:
HKCU\Sofware\Microsoft\Visual Studio\9.0\Source Control\UncontrolledInMemoryEditDialogSuppressed
This still won't work completely. What you then have to do is set your Source Control for that project to Visual Source Safe. (<-- this is the step I'm assuming you won't like.)
Then restart VS2k8.
At this point if you set one of your files to read-only, you will see that Visual Studio will not let you edit this file at all. When you try, it plays your computer's exception music.
Now, to make your files read-only when you run the app, set a post-build process to do this. That's easy.
Harder, is to set them back to writable once your app finishes running. The simplest solution is probably a batch file shortcut.

Categories