Code Analysis using VS.Net 2010



The Code Analysis tool is available as part of Visual Studio. When we enable code analysis, our code is validated against the rule defined in Microsft FxCop (current version is 1.36). FxCop is a free code analysis tool from Microsoft available for a long time and now it is integrated within Visual Studio in the form of Code Analysis option which is available. There are many design rules, coding conventions, security, usage guidelines and localization rules defined in the form of rules and we can run our code through all these rules.

To understand this, lets dig into this. I have created a sample project called SampleCATest which has just one method. When I build this code, I get zero warnings and errors.

fig1.gif

Now, under project settings, go to Code Analysis tab.

I am enabling Code Analysis, ignoring code analysis rules for generated code and using Microsoft Minimum recommended rules.

fig2.gif

I didn't get any violations reported.

Now, I changed the rule set to Microsoft All Rules and I found some violations.

fig3.gif

------Build started: Project: SampleCATest, Configuration: Debug x86------

Running Code Analysis....

MSBUILD : warning :

CA2210 : Microsoft.Design : Sign 'SampleCATest.exe' with a strong name key.
CA1303 : Microsoft.Globalization : Method 'Program.Main(string[])' passes a literal string as parameter 'value' of a call to 'Console.WriteLine(string)'. Retrieve the following string(s) from a resource table instead: "Testing, Code Analysis".

CA1801 : Microsoft.Usage : Parameter 'args' of 'Program.Main(string[])' is never used. Remove the parameter or use it in the method body.

Code Analysis Complete -- 0 error(s), 3 warning(s)

========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

We have to address these warnings or coding violations reported. We will go deeper and see how to you can customize rules.

You can go to Code Analysis , open any rule set and customize the rules and save the rulesets.

fig4.gif

To suppress violations, go to Error List and right click on warnings and we find options to suppress warnings either at Source or project suppression file (GlobalSuppression.cs file will be placed under your project with all suppressions).

fig5.gif

You can also extend and define your own custom rules and integrate with Visual Studio.

You can also use FxCop directly from Visual Studio command prompt.

I find this tool very useful for knowing the bad coding practices or violations which we usually do without our knowledge.

I am attaching my sample code with this article.

Using this tool will definitely make our code more stable.

Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all