While quite useful, it’s limited to providing a static view of your code, and it does not provide the detailed insight into your running program that debugging may require.. When debuggi
Trang 1150 Microsoft Visual Studio 2010: A Beginner’s Guide
If you’ve been working on your code and want to update the Call Hierarchy window, click Refresh Every time you view Call Hierarchy, the selected item is added to the list You can use the Remove Root button to delete an item from the list The Toggle Details Pane button shows and hides the Details pane, which shows the code and location of the call site
In Figure 6-1, the Main method is selected, which shows the call to GetOrderDiscounts off the cust instance of Customer from Listing 6-1 The actual code line is shown also You can
double-click the statement to navigate the editor to the location of that statement In fact, you can double-click any call site in the Call Hierarchy to navigate to the location of the call site
in the editor
The Call Hierarchy shows all of the possible paths you can take through a specific point in code While quite useful, it’s limited to providing a static view of your code, and
it does not provide the detailed insight into your running program that debugging may require When debugging, you typically need to view the running state of an application at
a specific point in time The following sections show you various features of the debugger that help you inspect the runtime behavior of code
Configuring Debug Mode
By default, VS creates projects with Debug mode enabled, which specifies project settings that make it possible for you to debug your application The VS toolbar shows you the current configuration settings you’re using; clicking the drop-down list will show Debug and Release configurations The Release configuration defines settings for your program that you want to use when you deploy it for production (actual) use You can also create
a custom configuration that allows you to set project properties how you want For the purposes of this chapter, we will use the Debug configuration
To understand what the Debug configuration gives you, ensure that the Debug configuration
is selected in the toolbar; you’ll need to have a project open to do this Then double-click the properties folder of your project and click the Build tab as shown in Figure 6-2
Figure 6-2 shows that optimizations are turned off and both TRACE and DEBUG are
defined Figure 6-2 shows the properties for a C# project, but in VB, the tab is called Compile When optimizations are turned on, the compiler will perform extra processing
on the code that makes it smaller and faster, altering the structure of the code When debugging, you don’t want optimizations because you need the code you’re stepping through to match what the compiler produces Compiler constants (also known as
compiler directives) such as TRACE and DEBUG are used by the compiler to enable or
disable blocks of code For example, the System.Diagnostics namespace has a Debug
class that will only work if DEBUG is defined.
Trang 2Do a build of your application, which will produce various files suitable for debugging
To view these files, right-click the solution, project, or folder in Solution Explorer and
select Open Folder in Windows Explorer Then navigate to the bin\Debug folder, which
should look similar to Figure 6-3
There are four files in Figure 6-3, two for the application and two to support running
in the debugger DebugAndTestDemoCS.exe is the executable console application, which
you might have already expected A *.pdb file is a symbol file that helps synchronize the
identifiers in your code with the executable file, making it easier to step through code with the VS debugger
There are two files with vshost in their name, which are instrumental to the debugging process A *.vshost file makes your application load faster during debugging, gives you
the ability to test your application with different security configurations, and allows you to evaluate expressions while debugging The vshost files are for debugging only, so you
Figure 6-2 The Build (C#) and Compile (VB) Properties tab
Trang 3152 Microsoft Visual Studio 2010: A Beginner’s Guide
should not deploy them with your application; they would just take up extra space and not serve a purpose You normally want vshost files in place when debugging in VS There are various debugger settings you can configure in VS that affect your session and modify the vshost configuration files Open the properties page and click the Debug tab, shown in Figure 6-4
In Figure 6-4, you can see that the Configuration is set to Debug and the Platform is set to x86 The Platform target can be Any CPU, x86, x64, or Itanium, depending on the CPU you are building the application on The compiler will perform optimizations for the CPU type you select If you’re running VS on a 64-bit operating system, your Active solution platform may show as Active (Any CPU)
The Start Action section of the Debug tab determines how the debugging session begins Start Project is the default, Start External Program allows you to attach your VS debugging session to an already-running application, and Start Browser With URL lets you debug a Figure 6-3 The Debug Output folder
Trang 4Web application Generally, you’ll only use Start Project for a desktop application The
property pages change for Web applications, which automatically run in a browser
You can add a space-separated list of values for command-line arguments If you’re
building an application that needs to be run from a command window or from a command
script, this method is very useful to test and debug a specific command-line configuration You can then read the values you’ve entered into the Command Line Arguments text box
by reading them from the args array passed to the Main method.
A working directory is the root location of where your program reads and writes files
By default, this location is bin\Debug for Debug configurations and bin\Release for Release configurations You can change the working directory location by putting a file path in the
Working Directory property box
Use Remote Machine is an advanced scenario where you can debug an application
running on a remote machine To do this, you would need to install remote debugging
software on the remote machine, ensure the Output path of the Build tab of the Properties
Figure 6-4 Debug properties
Trang 5154 Microsoft Visual Studio 2010: A Beginner’s Guide
window specifies the location of the executable file of the program to be debugged, that the output folder is shared, and that your application has permissions on the shared folder The focus of this book is on managed code, which runs on the NET CLR VS has the ability to debug unmanaged code, such as that written in C++ that communicates directly with the operating system Generally, you want to leave the Enable Managed Code Debugging box unchecked unless you are writing managed code that interoperates with unmanaged code, such as a COM DLL library, and need the ability to debug both VS will allow you to open SQL Server stored procedures, set a breakpoint, and step through the stored proc code for debugging If you need to debug stored procedures, make sure you check this box
NOTE
Managed code refers to code that runs on the NET Common Language Runtime
(CLR) The CLR is a virtual machine that provides several services such as memory
management, code execution, garbage collection, security, and more In contrast to
managed code, there is also code that is called unmanaged code Unmanaged code
does not use the NET CLR; instead it runs directly on the computer and communicates
with the operating system With unmanaged code, you must manage your own memory
and write low-level code to accommodate all of the services that the CLR would normally
give you You can use VS to write unmanaged code in C++, but this book focuses on
C# and VB, which produce executable files that run managed code on the CLR.
The Enable The Visual Studio Hosting Process setting is what caused the vshost files
to be generated in the output folder Normally, you want to leave this box checked because
of the benefits of vshosts, described previously The only exception might be if you had
a unique situation where the services provided by the vshosts process conflicted with the code you were running, which would be an advanced and rare scenario
TIP
In earlier versions of VS, you would occasionally get a file permission error on the
vshosts file, which was caused by the fact that there were file locks on the file This
can occur if you have attached to the running process from another instance of VS
or the process shut down improperly in a sequence that didn’t release the file lock on
vshosts One of the work-arounds is to uncheck the Enable The Visual Studio Hosting
Process box, rebuild, recheck the Enable The Visual Studio Hosting Process box, and
build again You also have the choice of restarting your OS, whichever you find easier
This scenario doesn’t point to a deficiency in VS or the operating system, because
the file locks are necessary when an application is running Rather, the scenario is a
consequence of having a bug in your code or improperly shutting down an application.
In addition to property settings, you have a plethora of options available via the Options window, which you can open by selecting Tools | Options, as shown in Figure 6-5
Trang 6As you can see in Figure 6-5, there are a variety of options that allow you to configure
debugging The primary difference between project settings and Options settings is that
project settings are for that one project, but Options settings let you change the settings for
all projects and have those settings, when applicable, apply to any new projects you create
Therefore, if there are default settings you want on all projects, visit the Options settings
to set them first The options are much too numerous to list here, and many of them deal
with advanced scenarios that are out of scope of this book If you ever have a question
about whether a capability is available or if you need to save settings, you should visit the
Options window to see if that capability is available Now that your system is configured
for debugging, you can set breakpoints and start the debugging process
Setting Breakpoints
Breakpoints are places in your code where you want the program to automatically pause
from running, similar to when you push the pause button while watching a movie with
your home DVD or Blu-ray player Once your program hits (stops on) your breakpoint,
you will be able to perform debugging tasks, which could be viewing the values of
variables at this frozen point in time (program state), evaluating expressions, or editing
code and continuing execution The following discussion shows you how to create and
manage breakpoints in your application
Figure 6-5 Debugging options
Trang 7156 Microsoft Visual Studio 2010: A Beginner’s Guide
Creating a Breakpoint
To create a breakpoint, you need to open a project and have a code file open in the editor A good project choice would be the example application with code from Listing 6-1 In the VS editor, there is a margin on the left side If you click in this margin, VS will set a breakpoint
on the matching code statement Clicking a statement in code to give it the focus and pressing
F9 sets a breakpoint too You’ll see a red dot in the margin and the matching statement highlighted in red, as shown in Figure 6-6 Note that you may only set a breakpoint on code that actually gets executed at runtime If you try to select a line of code that does not, such
as a namespace name definition, the red dot will not appear and you’ll see a message at the bottom of VS saying, “A breakpoint could not be inserted at this location.”
To ensure VS stops on a breakpoint, the application must be running in debug mode You can start the program running in debug mode by selecting Debug | Start Debugging, pressing F5, or clicking the Start With Debugging toolbar button (the one with the green
arrow) The breakpoint in Figure 6-6 is on the call to GetOrderDiscount in the Main
method When the program hits the breakpoint, the breakpoint line will turn yellow and there will be a yellow arrow on the red dot in the margin Clicking the Continue button (which is the same green arrow button used to start debugging) or pressing F5 will cause
VS to resume execution Any time you want to stop debugging, select Debug | Stop Debugging, press F5, or click the Stop Debugging toolbar button (small blue square)
Figure 6-6 A breakpoint
Trang 8If you write a program that is doing a lot of work, or very little work but is stuck in
an endless loop that you inadvertently created, you can pause execution by selecting
the blue pair of vertical bars button found to the left of the square blue stop button
When you do this, your program stops at whatever line of code it was executing at the
moment you selected the pause button You can then resume from that point This button
works much like the pause button on a remote control or a personal media player.
Customizing a Breakpoint
The preceding explanation described how to set a location breakpoint, where execution
stops on a designated line in code However, you can make a program stop executing
based on various criteria, such as hit count, conditions, and more To see what else is
available, set a location breakpoint and then right-click the dot in the margin to view
the context menu Table 6-1 describes each of the breakpoint options available from the
breakpoint context menu
You can also set a function breakpoint by clicking on the method to break on and
selecting Debug | New Breakpoint | Break At Function or pressing CTRL-D, N
Table 6-1 Options from the Breakpoint Context Menu
Delete Breakpoint Removes the breakpoint.
Disable/Enable
Breakpoint If you don’t want to delete the breakpoint because you’ll use it again, you can disable the breakpoint and then enable it later when you want to use it again.
Location This is set when you click in the margin You can change features of the location
through a dialog window.
Condition Allows you to enter an expression that can cause the program to stop if either the
expression evaluates to true or the value of a variable has changed The expression
is based on variables in your code.
Hit Count Makes the program break on that line every time, after a number of times the line
has executed, when the count is a multiple of a number (i.e., every nth time), or
when the number of hits is greater than or equal to a number.
Filter The breakpoint will only be hit (causing execution to pause) for any combination of
machine, process, or thread choice that you set.
When Hit Sets a tracepoint that prints a message to the output window The message is
configurable to include output of various system values like function, thread, and more You can view the message in the Output window by selecting View | Output Window or pressing CTRL - ALT - O You also have the option of running a macro when the breakpoint is hit.
Edit Labels You can associate breakpoints with labels to help organize breakpoints into groups.
Export Lets you export breakpoints into an external XML file.
Trang 9158 Microsoft Visual Studio 2010: A Beginner’s Guide
Figure 6-7 The Breakpoints window
Managing Breakpoints
Over time, breakpoints can be set across many locations in your project You can manage all of these breakpoints in a central location by selecting Debug | Windows | Breakpoints, which will show the window in Figure 6-7
Much of the functionality of the Breakpoints window has been explained already, except that the toolbar options apply to all of the breakpoints that are currently checked Clicking a column sorts the contents The Search box helps you filter breakpoints, and the
In Columns box helps focus on what the search applies to There are export and import buttons on the toolbar that allow you to respectively save and retrieve breakpoints to and from an XML file Double-clicking any breakpoint takes you to the location in the editor where the breakpoint is set Right-clicking a breakpoint shows a context menu with options that have already been discussed in this section
Once you set a breakpoint, you can step through code to see what the execution flow
of the program is, as is discussed in the next section
Stepping Through Code
Stepping through code is the process of executing one or more lines of code in a controlled manner At the most granular level, you can step through code line-by-line While moving line-by-line is often necessary, it could also be cumbersome, so there are ways to step over multiple lines of code, allowing them to silently and quickly execute
To step through code, open a project, set a breakpoint, and run with debugging until the program hits the breakpoint At that point in time, you can perform various operations such as step, step over, and step out Table 6-2 explains the stepping operations that are available The explanations in the table assume that a breakpoint has been hit with your executing program now paused before performing the step operation