GeneratedCode attribute, but other generated code (like Windows Forms) isn’t marked and will be
considered in the metric’s results.
ManaGed code analysis tool
This is a tool based on FxCop, a Microsoft internal tool released to the public a few years ago and
finally integrated into the IDE. It allows you to perform static code analysis using a set of rules that
define the quality decisions that you want to apply to your code. You can configure which set of
rules to apply to each project from the project property page shown in Figure 55-2.
fiGure 55-2
To use it you can right - click a project and select Run Code Analysis, or if you selected Enable Code
Analysis on Build in the project ’ s property window, you can simply compile it. The rules will be
evaluated and if there is any violation (and believe me, there will be sooner or later) you will have a
set of warnings in the Error List window.
By default each violation will appear as a warning, but you can change this
behavior.
If you right - click a warning and select Show Error Help, you will have a description of the rule, the
cause, steps on how to fi x violations, and suggestions on when to suppress warnings. Suppressing
warnings is done with the System.Diagnostics.CodeAnalysis.SuppressMessageAttribute ,
which can be applied to the offending member or to the assembly as a whole. You can quickly and
easily generate these attributes by selecting one of the Suppress Message menu options from the
right - click menu in the Errors window.
More than 200 rules are conveniently organized into 11 categories, and you can add custom rules if
needed. Depending on your project, you might want to exclude some categories or some particular
rules. For example, if you don ’ t need globalization and don ’ t have plans in the future to support it,
you might exclude that category. You can even create your own sets of rules (Add New Item . Code
Analysis Rule Set) if the ones provided by Microsoft don ’ t meet your needs.
When you fi rst get started with Code Analysis tools, you should turn on all the rules and either
exclude or suppress the warnings as needed. This is an excellent way of learning best practices.
After a couple of iterations, new code written will be less prone to violate a rule. If you are starting
a new project you might want to add a check - in policy, which prevents code with Analysis warnings
from being checked in.
Never suppress a warning unless you have a very good reason. Finding these
violations again can be quite diffi cult.
c/c++ code analysis tool
This tool is similar to the Managed Code Analysis Tool, but works for unmanaged code. To
activate it simply go to your C++ project ’ s properties window, look for the Code Analysis node
inside the Confi guration Properties, and select Yes for Enable Code Analysis for C/C++ on Build.
Every time you compile your project, the tool will intercept the process and attempt to analyze
each execution path.
It will help you detect crashes that are otherwise hard to fi nd with other techniques like debugging
that are very time consuming. It ’ s able to detect memory leaks, uninitialized variables, pointer
management problems, and buffer over/under runs.
C/C++ Code analysis Tool . 1079
1080 .
chaPter 55 ViSuAl STudio ulTimATe For deVeloperS
ProfilinG tools
Profiling tools enable you to detect and correct performance and memory issues in your projects.
You can start a profiling session by selecting Launch Performance Wizard from the Analyze menu.
The first step of the wizard asks you to select one of four profiling methods:
.
CPU Sampling reports the CPU utilization at regular intervals while your application
is running. This type of profiling is good for initial analysis or for identifying issues
specifically related to CPU usage.
.
Instrumentation actually inserts additional lines of code into your assembly to report on
the length of time each method call takes. You can use this sort of profiling to get a detailed
look at where your application spends most of its time.
.
The .NET Memory profiler collects data about objects as they are created and as they are
cleared up by the garbage collector.
.
Concurrency profiling collects information about multi-threaded applications and provides
some visualizations that you can use to explore several concurrency-related issues.
Next you need to select a project, executable, DLL, or web site to profile. With that information, the
Performance Wizard creates a performance session and opens the Performance Explorer window.
You could also create a blank session from the Performance Explorer or from a test in the Test
Results window.
In the Performance Explorer (Figure 55-3) you can change between
instrumentation and sampling. Using the combo box, you could start
the wizard again or manually create a new performance session.
Although you can instrument or sample a DLL, you need a point of
entry for your application to run when you start the session, so be sure
to include an executable, web site, or test project as a target.
fiGure 55-3
If you have high code coverage, profiling unit test projects can give you a good
insight into which methods take the longest to execute or use the most memory.
Be wary of reacting to this information, though, because long-running
methods may be called infrequently and improving an already fast method that
is called many times will have a greater impact on overall application
performance.
configuring Profiler sessions
To configure your session, simply right-click and select Properties. In the General section you can
change between Sampling, Instrumentation, and Concurrency (Figure 55-4), and choose if you want
to activate .NET memory profiling collection, the output for the reports, and the report names.
Profiling Tools .
1081
fiGure 55-4
In the Sampling section, you can select when to take samples; by default this is set to 10,000,000
clock cycles. Depending on what you want to track, you can change the sample event to page faults,
system calls, or a particular performance counter.
Enabling Tier Interaction Profiling (TIP) allows you collect information about synchronous ADO.NET
calls between your application and SQL Server. This includes the number of times each query is made
and how long each one took. If you are profiling an ASP.NET WebForms application, TIP is also able
to provide data about page request counts and generation times.
The Instrumentation section is used to specify pre- and post-instrument events, for example signing
an assembly with a strong name. These settings are set on a per-target basis. The last section in the
property page, Advanced, is also used when instrumentation is selected, and there you can specify
additional command arguments. To see a list of available options, search for VSInstr on MSDN.
VSInstr is the tool used to instrument binaries.
The remaining sections are used to specify the collection of different counters or events. CPU
Counters will let you capture additional low-level information and will be displayed as extra columns
in the different report views. These are only available for instrumentation. The Windows Counters
are system performance counters and you will be able to see the results in the Marks report view.
1082 .
chaPter 55 ViSuAl STudio ulTimATe For deVeloperS
The Windows Events section will let you specify event trace providers. To see the information on
Windows events, you would need to manually get a text report using the following command:
Vsperfreport c:\<path>ReportName.vsp /calltrace /output:c:\<path>
reports
Once you are all set, you can start the application, test, or web site from the Performance Explorer.
It will run as usual, but will be collecting data. Once your application terminates, a report will be
generated. Table 55-1 shows a description of some of the report views and Figure 55-5 shows the
Summary View.
table 55-1: Some Report Views
View naMe descriPtion
Summary Shows function information Sampling it will show functions causing the most
work and functions with the most individual work With instrumentation it will
show the most called functions with the most individual work and functions
taking the longest From here you can navigate to the Functions view If Collect
NET Object Allocation Information is selected as shown in Figure 55-4, it will
show functions allocating the most memory and types with the most memory
allocated and most instances
Call Tree Contains a hierarchy of the functions called The Call Tree has a feature called
Hot Spot that will point you to child functions taking the most time
Modules Shows information about the module sampled or instrumented
Caller/Callee Shows you which functions a particular function called and which functions
called it
Functions Presents a list of all the functions sampled or instrumented Double-clicking
each function lets you navigate to the caller/callee window
Allocations Shows the number of instances and bytes allocated of a particular type
Additional reports can be generated using the command-line tool VSPerfReport. For more information,
consult the MSDN documentation.
Allocation and Object Lifetime are only available if you select Collect .NET Object Allocation
Information and Also Collect .NET Object Lifetime Information, respectively, in the session’s
property page. Some of the report views are different depending on the configuration. To see
a description of a particular column, simply hover over its title. You should go through the
documentation on MSDN to get a thorough description on each report.
stand-alone Profiler .
1083
fiGure 55-5
In all the views, you can use the filter from the toolbar to get to specific information. You can add
or remove columns by right-clicking a header and sort using a particular column. Reports can
be exported to either XML or CSV and successive reports can be compared against one another,
allowing you to spot changes in your application’s performance.
stand-alone Profiler
This is a command-line tool that is useful when you need to profile an application without
installing Visual Studio on the machine — for example, in a production environment. To install this
tool, you need to execute vs_profiler.exe from the Visual Studio installation media located in
the Standalone Profiler folder. It will install the tools in the directory %ProgramFiles%\Microsoft
Visual Studio 10.0\Team Tools\Performance Tools. If you are going to use the command-line
profiler often, you could add this path to the system path.
The following commands profile an application using sampling with the default settings. The first
line enables the trace. The next command switches the profiler to use CPU Sampling and to output
a report. In this case the report will be saved in the ApplicationToProfile directory on a file named
1084 .
chaPter 55 ViSuAl STudio ulTimATe For deVeloperS
Report.vsp. Then you launch the application, interact with it as usual, and when you are done you
finally shut down the Profiler. You can then open and inspect the generated report in Visual Studio.
C:\ApplicationToProfile > vsperfclrenv /traceon
Enabling VSPerf Trace Profiling of managed applications (excluding allocation
profiling).
...
C:\ApplicationToProfile > vsperfcmd -start:sample -output:Report
Microsoft (R) VSPerf Command Version 10.0.30128 x86
...
C:\ApplicationToProfile > vsperfcmd -launch:Application.exe
Microsoft (R) VSPerf Command Version 10.0. 30128 x86
...
Successfully launched process ID:4144 Application.exe
C:\ApplicationToProfile > vsperfcmd -shutdown
Microsoft (R) VSPerf Command Version 10.0. 30128 x86
...
Shutting down the Profile Monitor
intellitrace
IntelliTrace is a new tool in Visual Studio 2010 Ultimate that makes debugging your application a lot
easier. It operates like a flight recorder while you are in a debug session and allows you to look back
at historical values and state. In addition to this, you can save IntelliTrace sessions and load them
back up at a later time. Testers who are using Microsoft Test and Lab Manager can also collect
IntelliTrace information while they run through test cases, providing you with the exact state of the
system when a bug is reported.
IntelliTrace currently supports C# and VB projects with experimental support
for F#. You cannot use IntelliTrace by using the Attach To Process command or
in remote debugging scenarios.
When a debugging session is started and IntelliTrace
is enabled (Tools . Options . IntelliTrace) the
IntelliTrace window (Figure 55-6) is shown. This
window maintains a list of diagnostic events that
IntelliSense is able to detect.
As each new diagnostic event occurs, Visual Studio adds
it to the end of the list. If you pause the execution or hit
a breakpoint, the IntelliTrace window becomes active.
If you click any of the diagnostic events, it expands to
show a little more information. This expanded view
contains a list of Related Views, which have been
updated by IntelliTrace to reflect the state of the
fiGure 55-6
intelliTrace .
1085
application at the time of the event. You can check the
call -stack, add watches, check locals, and generally
perform any of the tasks that you would normally be
able to during a normal debugging session. When you
are ready to resume execution of the application you can
click the Return to Live Debugging button.
IntelliTrace is able capture two types of information
during a debugging session. IntelliTrace Events are
enabled by default and include Visual Studio debugger
events such as application start and hitting breakpoints.
Throwing and catching exceptions are also IntelliTrace
events. When a tester is collecting IntelliTrace
information, the beginning and end of a test along with
any failures form contextual events that are covered
under the label of IntelliTrace Events. Finally, the