Sei sulla pagina 1di 12

Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .

NET 1

Continuous code analysis with


FxCop

Have you ever head a project you had to take over, fix a bug, or code a feature? How often
you felt uncertain, lost, or upset? How many times you wanted to find the guy that originally
wrote the piece of code you’re working on and simply… thank him warmly? If you are living
in the same world as we are, it has happened to you at least few times.

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
2 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

Figure 1 Always code as if the guy who ends up maintaining your code will be a violent psychopath who
knows where you live (art: www.kkphoto.art.pl).

Do you ever wonder why you felt like this? Is it because the code didn't do what it
supposed to do? If it wasn't a bug, it was probably something else. The software smelled.
And nothing is worse than smelly code. The good news is you are not the first one that
thought about it. There are static code analyze tools that help to ensure your code doesn’t
smell. FxCop analyzes the IL code, StyleCop dos the same with C# and NDepend goes over
IL using special code query language. FxCop is the most popular one of the three so let’s
have a look how to use it and how to do a continuous code analyze with it.

1 Analyzing object code with FxCop


FxCop is a free Microsoft tool for code analysis. It examines the compiled .NET assemblies for
things like performance, naming conventions, library design, globalization, and security.
Often times these types of issues aren’t found until either your customer tries to run the
application or when you attempt to maintain or enhance the code.
FxCop started as a standalone program that enforced the rules from Design Guidelines for
Class Library Developers1, a document that contains good coding practices for developers
writing .NET code. FxCop was incorporated into Visual Studio Team System 2008 and Visual
Studio Premium 2010 as Code Analysis. The good news is, it can still available as a
standalone program which will be very helpful in our CI scenario. Let's have a look at FxCop
in action.

1.1 Using Visual Studio Code Analysis


If you have an edition of Visual Studio 2010 that includes Code Analysis, the usage of Code
Analysis is quite straight forward. Go to project properties. Switch to the Code Analysis tab
and switch on the flag Enable Code Analysis. See Figure 2.

1
http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .NET 3

Figure 2 FxCop is built into Visual Studio 2010 Premium or Ultimate editions as Code Analysis

The good fellows from Microsoft suggest that by default you use the Microsoft Minimum
Recommended Rules. It is up to you what set of rules to use. You can even define your own.
Keep in mind that the rules are come from a document that contains "guidelines" in its title.
So it is really up to you what rules are you use and what you ignore. What is important is
that you are making a conscious decision about this. You can see the rules that are working
if you click Open. You can modify the list according to your needs and save the output file for
future use in other projects (Figure 3).

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
4 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

Figure 3 When you define a set of Code Analysis rules in Visual Studio 201, you need to save them to a
rule set file so they can be applied to the project.

You can decide what rules will break your build and what will only be compiler warnings.
Unfortunately, at the time of writing this article with Visual Studio 2010, Beta 2, the “Treat
warnings as errors” project property was not working together with code analysis. Once you
turn on Code Analysis, every time your project compiles the analysis will be done.
But, what about situations where you want to generally check some rule but in particular
place you are sure you have to broken it? To do this you can use suppressions. FxCop
messages can be suppressed directly in the code where they occur or in a global suppression
file. Visual Studio comes with neat functionality to make is easier. To suppress a particular
issue, right-click on it in the Error List window and select Suppress Message(s) (Figure 4).

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .NET 5

Figure 4 Suppressing a code analysis message right out of the Error List windows in Visual Studio 2010.

Using Code Analysis is all fine and good, but what if it isn’t included in your edition of
Visual Studio or you need it running on the CI server where you want it to run automatically?
The answer is to use FxCop.

1.2 Setting up continuous FxCop code analysis


As you have seen, FxCop was dressed up nicely as Code Analysis and migrated to Visual
Studio. Fortunately the FxCop source project didn't die. It is still actively supported. Even if
you don't have the full blown Visual Studio you can still use FxCop. You just have to
download2 and install it. Of course it will not be as friction free as Visual Studio Code
Analysis, but it still is doable. Using standalone FxCop you can customize your CI process as
you wish. And using the FxCop GUI (Figure 5), you can do basically everything that is
possible with Code Analysis in Visual Studio.

2
You can get FxCop at http://go.microsoft.com/fwlink/?LinkId=70294
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
6 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

Figure 5 Standalone FxCop does the same analysis as Code Analysis in Visual Studio and allows you to
create FxCop project files for use in your CI process.

FxCop stores information about the assemblies that it needs to analyze in an FxCop
project. You’ll recognize it by its .FxCop extension. It is created automatically as you add you
.NET assemblies into the FxCop GUI. You just need to remember to save the FxCop project
into the same directory as your .NET solution so that it can be checked into your source code
repository, where the CI process can grab it.
So let's configure our CI server to analyze our code. First, take the standalone FxCop tool
and copy it to the tools subdirectory. You should copy only the files that are needed on the
CI server. One important file is the FxCop command line tool, FxCopCmd.exe.
Next, you need to extend the MSBuild project file with a new code analysis task. With the
You can directly use the MSBuild Exec task with FxCopCmd.exe. There is a MSBuild
community task that automates the usage of command line FxCop (see
http://msbuildtasks.tigris.org/).
When running FxCop as part of your CI process, there are two issues with FxCop you
have to consider. First, if you are picky about the rules you are using, it is better to manage
them visually in the FxCop GUI. Second, getting information about the rules violations is not
so straight forward as it could be.
The command line tool, FxCopCmd, is able to take either the list of assemblies to analyze
and the list of rules to be checked or the FxCop project as an input parameter. If you are not
picky about the rules you want to check, the command to check your assembly is pretty
clear:

tools\FxCop\FxCopCmd.exe /f:CiDotNet.Calc/bin/Debug/CiDotNet.Calc.dll
[CA]/r:tools/FxCop/Rules /console

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .NET 7

This will take any library (CiDotNet.Calc.dll in this case) and run in through FxCop using
all the rules from tools/FxCop/Rules directory. The /console switch tells FxCopCmd to
output everything to the console. If you want to write it to a file, you need to specify the
filename with /o:FxCopReport.xml.
If you are more picky about what rules to use and what to leave out you can use the
/ruleid parameter along a the +/- notation to indicate which rules to include (put a + sign
in front of them) or ignor (put a – sign in front of the rule). For example, to ignore some
rules put a minus before its category and id number (writen Category#Id) like this:

tools\FxCop\FxCopCmd.exe /f:CiDotNet.Calc/bin/Debug/CiDotNet
[CA].Calc.dll /r:tools/FxCop/Rules /ruleid:-Microsoft.Design#CA2210
[CA]/console

This will turn off the rule that says you have to assign a strong name for your assembly.
You can customize this call as you wish. But it will be a bit of work. It is alot easier is to take
the FxCop GUI and filter the assemblies visually as shown in Figure 6.

Figure 6 Filtering FxCop rules. If you feel the need to follow only some of the FxCop rules, it is easier to
choose them visually and use the FxCop project file with command line than to write long FxCopCmd
command.

Let's say you’ve configured your FxCop project and saved it as CiDotNet.FxCop. You can
now use it with FxCopCmd.exe:
tools\FxCop\FxCopCmd.exe /project:CiDotNet.FxCop /out:FxCopReport.xml
Unfortunately the assemblies you want to analyze are hard coded to the FxCop project
file. No matter if you choose to have the relative or absolute path to the targets and you are
using the standard Debug or Release scenario, you will end up with one of the output
directories being written into the FxCop project file:

<Target Name="$(ProjectDir)/CiDotNet.Calc/bin/Debug/CiDotNet.Calc.dll"
Analyze="True" AnalyzeAllChildren="True" />

One way to resolve this is to have two FxCop project files, one for Debug and one for
Release. If you want to vary the analysis for both scenarios (not recommended from our
©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
8 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

experience becase Release tends to be neglected by developers) it should work for you. If
not, you have to think about a different solution.
MSBuild comes with a possible solution the Community tasks FileUpdate. It can be used
to change the assembly directory in the FxCop project file in a CI scenario as shown in
Listing 1.

Listing 1 FxCop run from command line using a manipulated project file
<Project DefaultTargets="Analyze"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask AssemblyFile= 1
"tools\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll" 1
TaskName="MSBuild.Community.Tasks.FileUpdate"> 1
</UsingTask> 1

<Target Name="Analyze">
<FileUpdate Files="CiDotNet.FxCop" 2
Regex="bin/Debug" 2
ReplacementText="bin/$(Configuration)" /> 2
<Exec Command="tools\FxCop\FxCopCmd.exe 3
[CA]/project:CiDotNet.FxCop /out:FxCopReport.xml" /> 3
</Target>
</Project>

1 Import the Community Tasks


2 Update the project file
3 Perform the analysis

Replace #1, #2, and #3 in the following paragraph with cueballs

First we import the community task #1 to use it to update the paths #2 according to
current configuration. We then call FxCopCmd #3 to perform the analysis.
We generally recommend that you incorporate all the rules provided and then exclude
specific rules that you think are not important. Nevertheless, if you are picky you can
incorporate our solution.
But as you will see by starting the MSBuild script, it will end up without error or warning
even if there are rules violations in your code. This is not acceptable because you can bet
that if the rule violation does not break the build, no one will bother to obey the rules at all.
You cannot expect the developer to check the FxCop results for a working build. You have to
break the build for the rules to be obeyed. Unfortunately, FxCopCmd doesn't provide a
straight forward way to do it. The ContinueOnError property in the Exec task reacts only
on exceptions during ExCopCmd run and not to the broken rules. One of the options is to
read the XML output of FxCopCmd to find the violations. But there is an easier way.
FxCopCmd produces an output file only if there is something to report, for example, broken
rules. So if the files exists, you can safely break the build like this:

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .NET 9

<Target Name="Analyze">
<Delete Condition="Exists('FxCopReport.xml')"
Files="FxCopReport.xml">
</Delete>
<Exec Command="tools\FxCop\FxCopCmd.exe /project:CiDotNet.FxCop
[CA] /out:FxCopReport.xml"/>
<Error Condition="Exists('FxCopReport.xml')"
Text="FxCop found some broken rules!" />
</Target>

You are now fully prepared to integrate your code analyze with your CI server of choice.
Let's find out how to do it.

1.3 Integrating FxCop with CI servers


CruiseControl.NET takes XML files and is able to show them on the Dashboard page.
Fortunately it comes with an XSD file to perform the transformation to HTML format. Make
sure you have this line in your dashboard.config file to include the FxCop XSD file.
<xslReportBuildPlugin description="FxCop Report"
actionName="FxCopBuildReport"
xslFileName="xsl\fxcop-report_1_36.xsl" />

You also need to merge the FxCopCmd output report file into the Dashboard.

<publishers>
<merge>
<files>
<file>FxCopReport.xml</file>
</files>
</merge>
<xmllogger />
</publishers>

After you check everything into your source code repository it should all work just fine
and you will be able to see the FxCop report like shown in Figure 7.

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
10 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

7 FxCop analysis report on CCNet Dashboard page. The output from FxCopCmd is formatted using the
XSD file supplied by CCNet to provide an easily readable report.

Integration with TeamCity requird an HTML file to merge with the TeamCity web page.
FxCopCmd is able to produce an HTML file instead of the standard XML file. You have to only
modify the call:

tools\FxCop\FxCopCmd.exe /project:CiDotNet.FxCop /out:FxCopReport.html


[CA]/axsl

The axsl parameter tells FxCopCmd to aply the XSL style sheet right away and produce
HTML output. When that’s done, you are ready to add a new tab to the TeamCity web site.
You will have to define new artifact FxCopReport.html and a new tab server configuration.
You will end up with this page being a part of the TeamCity build report (Figure 8).

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
Last saved: 10/12/2010 Marcin Kawalerowicz / CI in .NET 11

Figure 8 An FxCop analysis report in TeamCity.

If you are using TFS 2010 as your CI server, you probably are using the built in code
analysis tools. In fact you, can turn on code analysis even without the Visual Studio 2010
Premium edition. It's just a matter of adding a line to the project file:

<RunCodeAnalysis>true</RunCodeAnalysis>

You can also optionally specify the rule set to use:


<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>

You will not be able to benefit from code analysis right away on your development
machine, but TFS 2010 will snap in and perform the check for you when it performs a build.
So you will get what you need in end effect. Figure 8.9 shows the TFS build report.

Figure 9 The TFS build report with code analysis output on the Build summary page. If you want to break
the build on a given violation check , change the action to Error.

FxCop does a great job of checking the conformance of your assemblies to the Microsoft
.NET Framework Design Guidelines.

2 Summary
From experience, we know that the projects tend to grow. Developers have tendency to add
new lines of code to the projects. They sometimes even change the old lines of code to fix
something. Some projects live over many years and are modified by many developers. They
usually want to know what is going on in the project. But when they change the code, they
assist in the project growth.
But what if they are coming to a project that looks like a great ball of mud? One class
may be developed with great Cobol influence and looks just like functional programming.
There may be lines of 1000 characters or a previous developer used one character long
variable names. It is a pain to work with smelly code. The only way out of it is to enforce
some rules. Many software shops have written coding guidelines. But having the rules
doesn’t mean they will be obeyed. Developers are humans, they are working under time

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ
12 Marcin Kawalerowicz / CI in .NET Last saved: 10/12/2010

pressure, and sometimes they neglect or don't even understand the rules. Only if the coding
rules are enforced on them they will be obeyed.
There is nothing better than static code analysis to check the rules. Tools like FxCop are
great guards against bad coding habbits. Static code analysis as part of your CI process will
effectively fight any smell in the code you like. Even the ones only you can smell. You just
have to write your own rules. You need to guard yourself against that violent psychopath.

©Manning Publications Co. Please post comments or corrections to the Author Online forum:
http://www.manning-sandbox.com/forum.jspa?forumID=XYZ

Potrebbero piacerti anche