Static Code Analysis for XNA Applications

This tutorial assumes familiarity with the .NET Framework, C#, Visual C# 2005 Express Edition, and XNA.

There are many tools for making better software. One of the more recent innovations in software development tools is the idea of static code analysis. A program examines the source or object code of another program looking for potential problems. These potential problems are not syntax errors; compilers can catch those. Instead, static code analysis tools look for patterns of usage, defined by rules. Once a code pattern matching a rule has been located, it is flagged. At that point the software developer has a chance to evaluate the potential problem and fix it or leave a special mark in the source code that identifies to the reader (as well as the static analysis tool) that the potential problem is not a concern.

Notice that I explicitly stated that static code analysis is used to find “potential problems.” In truth, the tool only matches patterns of code to rules. The rules are formulated by experts, and while they can help identify problems from security issues to code style issues, they are not perfect.

For .NET programming, a team at Microsoft has developed and released, for free, a static code analysis tool called FxCop. FxCop’s rule set is based on Microsoft’s .NET Class Library Design Guidelines. These guidelines are available in the book “Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries” by Krzysztof Cwalina and Brad Abrams.” There is also an excerpt of the book available online at MSDN.

The FxCop team maintains a website, where you can download the tool, as well as read the documentation, post in a user’s forum, and read the developer’s weblog. Note: if you are reading this after July of 2007, it is probable that the FxCop team website has been moved. Hopefully I have been back to update the link, but if not a quick search should dig it up. I would anticipate it’s on MSDN somewhere.

Now, you should download and install the software. Also note that some of the rules that FxCop is checking are for spelling. In order to enforce those rules, FxCop will need to have a spell checking component installed from Microsoft Office. It is probably sufficient to only install Microsoft Word. It will be necessary on all computers that are going to run FxCop, including build machines.

Now that we have FxCop installed, let’s put it through its paces. For now, we are going to start with the simplest XNA application possible.

Start Visual C# 2005 Express Edition. Go to the “Tools” menu and select “External Tools…” This brings up the following dialog box.

The Add Tool Dialog box of Microsoft Visual C# 2005 Express Edition.

You should click “Add” and then fill out the text boxes as I have. The clipped out portion of the Command text box is “fxcop.exe” Unfortunately, we have to hard-code the path to the tool. Once you’re done, click “OK”.

Now, we need a program to analyze. Create a new Project (I called mine FxCop Test,) and select Windows Game as its template. Now, build the program. FxCop examines compiled assemblies code using the metadata stored in the assembly. It does not matter if you build “Debug” or “Release.” FxCop works for both. Once the build is done, go to the “Tools” menu and start FxCop. Once you do, you will see a window like this.

The main Window of Microsoft's FxCop static code analysis tool.

You will see in the “Targets” tab your assembly’s exe file name. From this tree view, you can browse through the members of the assembly. At each point, clicking on the tree view node will bring up a list of the properties of that member in the properties window. As many FxCop messages deal with the assembly metadata, it is convenient to be able to easily browse it.

Go ahead and click “Analyze.” You will need to help FxCop resolve the reference to Microsoft.Xna.Framework.Game. Just browse to the References directory in your XNA install to resolve it. Once you do, you will see some messages generated. Even this most simple of XNA applications seems to have some potential problems! Here are the messages.

The Messages generated by FxCop for a simple XNA application.

You’ll see columns in the messages panel identify which rule has been broken, as well as “Certainty,” “Fix Category,” and “Level.” These can all be used to try to make decisions about which rules violations should be looked at first, or if a violation should be examined at all. For now, because there are only 4 messages, we’ll fix them all.

The bottom message is the most benign, and it’s also the easiest to fix. It’s simply reminding you that there is a parameter to a method that is not being used. In this case, it’s the auto-generated “args” parameter to Main. Fixing this message is as simple as just removing the parameter from the method.

The top message is perplexing. If you click on the message, in the properties window, you’ll see some information about the rule that has been violated. The “Info” and “Help” properties are especially useful. In FxCop 1.35, the default links in the Help URLs are broken, but are redirected to the proper documents on MSDN.

Reading more, we learn that Microsoft recommends that assemblies be given a “strong name.” We can resolve this problem through Visual C#. Go to the property page for your project, and select the “Signing” tab. Check the “Sign the assembly” check box, and in the “Choose a strong name key file:” combo box, select “…” In the resulting dialog box, type in a name for the new key pair file you will be creating. Usually, these files have a .pfx extension; Personal inFormation eXchange. Make sure you choose a password as well to protect the key pair file. Click OK, and a new file will be created and added to your project. Now, re-build. Your assembly is now strongly named. If you return to the FxCop GUI and click “Analyze” again, you will see only one message left.

Now, what exactly did we just do? .NET security is a very complicated topic, and strong naming alone is worth an entire blog post. However, in summary, we have created a public key encryption key pair. That pair is stored in the pfx file. Because a private key is stored in the file as well as the public key, it should be kept as secret as possible. That is why we have added password protection to the key file. (Don’t forget the password!) The assembly is signed as part of the build process, which is the naming. One of the benefits of this code signing is your assemblies are now more resilient to tampering. There are other benefits, and a few challenges. I’ll cover all of this in a later post. For now, I recommend using strong names. I do believe that you should not re-distribute the pfx file, however, if you are going to share your game’s code.

Our final message that we need to deal with is “Mark assemblies with CLSCompliant.” This message is referring to CLS, which is the Common Language Specification. A subset of Microsoft’s .NET has been submitted to various standards bodies. Part of the standard is the idea that code can be written and shared amongst multiple languages (the IL is shared, not the source!) The CLS enforces the rules necessary for that sharing to occur. Unfortunately, one of the CLS rules is that CLS compliant classes must only derive from other CLS compliant classes. As Microsoft.Xna.Framework.Game is not CLS compliant, then our game cannot be compliant either. You can indicate this to the complier by adding the following attribute to Program.cs.


using System;
[assembly: CLSCompliant(false)]
namespace FxCopTest

Originally, I was planning on adding this attribute to AssemblyInfo.cs (it seemed the logical choice.) However, it appears the CLSCompliant attribute must be attached to namespaces (despite no reference to namespaces in the FxCop message.) If anyone can explain this, let me know.

At this point, if we rebuild and re-analyze the code, we will see no messages. We are FxCop clean. By introducing FxCop right from the get-go in our development process, we can handle the messages as they come. In my follow up post, we will see that in a source code base of only moderate size, the messages can pile up fast! We’ll also take a look at the mechanism for marking code as safe without fixing the message, as well as the command line FxCop and integration with Visual C# 2005 Express Edition’s build process.

OE

Other links of interest:

  • FxCop, Your .NET Cop Another FxCop basic intro, this article covers the GUI in more details, and includes some helpful information on the command line tool.
  • FxCop In Depth A transcript of a talk given by Michael Murray and Jeffery Van Gogh, FxCop developers. It includes some insider background on how FxCop came to be, how it works, and how the rules work.
  • Strong-Named Assemblies One of the several partial treatments of Strong-Named Assemblies on MSDN.
  • Common Language Specification CLS documentation on MSDN.
Advertisement

One Comment

  1. Posted May 3, 2007 at 3:40 am | Permalink

    Folks interested in FxCop might be interested by the tool NDepend:
    http://www.NDepend.com

    NDepend analyses source code and .NET assemblies. It allows controlling the complexity, the internal dependencies and the quality of .NET code.

    NDepend provides a language (CQL Code Query Language) dedicated to query and constraint a codebase.

    It also comes from with advanced code visualization (Dependencies Matrix, Metric treemap, Box and Arrows graph…), more than 60 metrics, facilities to generate reports and to be integrated with mainstream build technologies and development tools.

    NDepend also allows to compare precisely different versions of your codebase.


One Trackback/Pingback

  1. [...] Code Analysis for XNA Applications Part 2: Spelling In the first post in this series, we introduced FxCop a .NET static code analysis tool. We ran the GUI version of [...]

Post a Comment

Required fields are marked *
*
*

Follow

Get every new post delivered to your Inbox.