ASP.NET VERSIONS: 1.0 | 1.1
Patrol Your Code for .NET Rules Violations
By Ken McNamee
Unless you're an expert in every facet of .NET programming, you're probably left with a nagging feeling at the end of many projects that your code is not as optimized as it could be. You may also wonder whether it's adequately secure. Although Visual Studio.NET and the .NET language compilers can ensure that your code compiles, and may even warn you of issues such as unused variables, they don't really analyze your code for ways to make it better.
If only there were a tool that could inspect your code and give you advice on how to improve its performance, security, readability, and overall conformity to the ".NET way." Well, Microsoft has created a free tool called FxCop for just this purpose.
What Is FxCop?
FxCop is a fairly simple tool that can load any number of assemblies, analyze the Common Intermediate Language (CIL) within, and compare the structure, content, and coding style of the CIL to a list of rules. It is these rules that are at the heart of FxCop, since the entire purpose of the tool is to notify you when your code violates one of the rules. For instance, the code in Figure 1 looks fairly innocent; it merely checks that the contents of a TextBox control are not empty. If the TextBox is empty, then the code sets a corresponding label to red.
private bool validateTextBox(TextBox textBox, Label label)
if (textBox.Text == "")
label.ForeColor = Color.Red;
Figure 1: Run FxCop against this code sample to check for rule violations.
However, if you run FxCop against the assembly that contains this code, you'll see a message like the one highlighted in Figure 2: "Test for empty strings using System.String.Length." Of course, this short message may briefly tell you how to fix the rule violation, but not why there was a violation in the first place. For greater detail, look in the text area underneath the list of violations. Or, as you can see in Figure 3, you can double-click on the violation and find information about the reason for the violation, the location in the code where the violation occurred, and some advice for how best to resolve the violation. In this case, we discover that checking the Length property of a string to see if it is greater than zero is far more efficient than comparing it to String.Empty.
Figure 2: FxCop displays a list of all the default and custom rules that an assembly is suspected of violating.
Figure 3: Double-clicking one of the rule violations gives you more information on the exact location in the code and advice on how to resolve it.
Why You Should Use FxCop
The previous string comparison example was a fairly innocuous rule violation. However, if the string comparison occurred in a significant loop structure, then the performance hit for that piece of code could be greatly magnified. So, depending on your situation, FxCop may give you important advice on how to optimize your code. It can also find dead code, i.e. code that is no longer being called from anywhere in your application. If FxCop finds any dead code it will warn you to "avoid building non-callable code into assemblies." This may not make your code perform any better, or make it more secure, but it does help make it more readable. FxCop can even check for spelling mistakes, although at this time it hasn't reached the Microsoft Word level of sophistication by making spelling suggestions.
One important set of violations that FxCop is diligent about is to ensure that your code is consistent with the .NET Framework. For instance, FxCop likes event handlers to return void and accept two parameters: an object type named "sender" and an EventArgs type or derivative named "e". Also, the event handler suffix should be "EventHandler" whenever possible.
FxCop will warn you if your assemblies are not marked CLSCompliant, do not have strong names or version numbers, or do not have the COMVisible attribute explicitly set. FxCop can also help minimize strange behavior in your applications or significant performance degradation by ensuring that any classes that allocate unmanaged resources implement the IDisposable interface. In this way, those resources can be released much earlier than if they had to wait until the object was garbage collected.
Integrating FxCop into Your Build Process
There are a few ways to use FxCop while you're developing your application. First, you can open the FxCop GUI application, create a project that includes the assemblies you'll want to have analyzed, and explicitly click the Analyze button to see if any rules were violated. Second, you can use the FxCopCmd command-line tool if you want to integrate it into your own custom build process. Third, you can add FxCopCmd as an external tool in Visual Studio.NET, which is fairly simple to do. If used in this way, FxCopCmd will send all analysis results to Visual Studio.NET's output window.
Unfortunately, I've only been able to show you a small amount of FxCop's capabilities. One of its most significant features is its extensibility. FxCop comes installed with many default rules for COM, design, globalization, naming conventions, performance, usage, and security. These rules are contained in their own assemblies and conform to certain interfaces that allow them to be called by the FxCop engine. However, it's fairly easy to create your own rules, as long as the assemblies conform to the same interfaces as the default rules. For example, your company may impose a set of naming conventions that all applications need to follow. You could create a rules assembly that analyzes all code and enforces the naming conventions. Imagine the savings in time and eye strain by using FxCop instead of manually inspecting every line of code for conformity. For more information, or to download FxCop, visit http://www.gotdotnet.com/team/fxcop.
Ken McNamee is a Senior Software Developer with Vertigo Software, Inc., a leading provider of software development and consulting services on the Microsoft platform. Prior to this, he led a team of developers in re-architecting the Home Shopping Network's e-commerce site, http://www.HSN.com, to 100% ASP.NET with C#. Readers can contact him at [email protected].