Using the code analysis feature that comes with Visual Studio (VS) 2010 is definitely beneficial as it improves application and code quality by providing the ability to discover potential issues in your code, such as non-secure data access, usage violations, and design problems. Of course there may be times where you want a hybrid of these already established rules as well as the capability to incorporate these rules into your automated build processes that are running within Team Foundation Server (TFS). Creating policies for code that’s being checked in by developers is extremely important and should also be implemented (among others). That said, let’s walk through a scenario which covers all of these areas.
First, you’ll need to create a custom rule set. Select one of the predefined rule sets and then save that rule set as “MyCustomRuleset.ruleset.” At this point I’d recommended adding a description as that’s an easy way to determine what this rule set encompasses. Once saved, open the file using VS and select the rules that you want to include. I’ve created a custom rule set with only 1 performance related rule (i.e. “CA1800: Do not cast unnecessarily”) which isn’t very practical but lends itself well for this example.
Once saved, you can now associate that rule set with your project by going to the “Code Analysis” tab and selecting it. Don’t forget to check off “Enable Code Analysis…” otherwise this (or for that matter any rule set) will not execute.
Now that the project is using this rule set let’s go one step further and make sure it’s going to be utilized by the automated build. For that to occur you’ll have to edit the build definition property of “Perform Code Analysis.” 3 options are available:
- “Never” – Using this setting will never run code analysis
- “AsConfigured” – Using this setting will run code analysis according to project settings
- “Always” – Using this setting will always run code analysis
Note that if the solution/project code analysis properties change to not run any rules and the “Always” setting is set, no rules will be executed. Therefore security should be implemented via Source Control so that the lead developers or the Build Master/Release Lead are the only team members who can change these settings.
Finally, creating a check-in policy can be done by using Team Explorer. Select “Team Project Settings -> Source Control” and add a new check-in policy. Here though, instead of directly choosing the file from your hard drive, you will be selecting it from Source Control. In order to do this, check-in the “MyCustomRuleset.ruleset,” for instance: “$/MyProject/Rules/MyCustomRuleset.ruleset”
Now all that’s left to do is to enter the path and this policy will be enabled.
With just a few minutes of work, it’s possible to establish best practices and standards throughout the development lifecycle. Additional information can be found on MSDN regarding “Analyzing Application Quality by Using Code Analysis Tools.”