Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

How to Use the Visual Studio Code Analysis Tool FxCop

The integrated static code analysis tool an help you find and correct bugs in your software development.


advertisement
In today's world, software security is the first and foremost requirement of any customer when you are developing a new application. But you can develop a secure application by mitigating all the risks in the development cycle itself. The best way to mitigate software risks is by doing code reviews and code analysis throughout the development cycle.

Another positive aspect of code analysis is you can easily identify bugs early in the development cycle before those are identified by testers or even users of the application. Identifying and correcting critical bugs early in the software development cycle mitigates risks like reducing developer productivity, creating unnecessary bottlenecks in the software development lifecycle, increasing software development costs, etc. In this article I will discuss the integrated static code analysis tool (FxCop), introduced with Visual Studio 2010. Visual Studio code analysis rules are applicable for five different programming languages.

[login]

Code Analysis Rule Settings in Visual Studio 2010



Static code analysis is performed without executing the application source code. The Visual Studio 2010 static code analyzer is available with premium and ultimate editions only. But you will be able to see the analyze menu in the Visual Studio editor if Fxcop is installed. Plus, in project properties, you will get a code analysis tab.

Microsoft has divided almost 200+ code analysis rules in different groups or categories in Visual Studio 2010 -- for example: basic correctness rules, basic design guideline rules, globalization rules, etc. These rules are part of best practices. You can open all these rules from the code analysis tab under project properties. You can select specific rule groups that you want to apply for your project. To set all code analysis rules select "Microsoft All Rules' from the dropdown. To enable these code analysis rules on every build, check "Enable Code Analysis on Build (defines CODE_ANALYSIS constant)" option. You can also set the code analysis rules at the solution level.

All these rule groups are individual XML files found in following path. C:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\Rule Sets. Following is the source XML of basic correctness rules.

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Microsoft Basic Correctness Rules" Description="These rules focus on
logic errors and common mistakes made in the usage of framework APIs. Include this rule set to
expand on the list of
warnings reported by the minimum recommended rules." ToolsVersion="10.0">
 <Localization ResourceAssembly="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.dll"
  ResourceBaseName="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.Localized">
   <Name Resource="BasicCorrectnessRules_Name" />
   <Description Resource="BasicCorrectnessRules_Description" />  </Localization>
 <Include Path="minimumrecommendedrules.ruleset" Action="Default" />  <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace=
"Microsoft.Rules.Managed">    <Rule Id="CA1008" Action="Warning" />    <Rule Id="CA1013" Action="Warning" />    <Rule Id="CA1303" Action="Warning" />    <Rule Id="CA1308" Action="Warning" />    <Rule Id="CA1806" Action="Warning" />    <Rule Id="CA1816" Action="Warning" />    <Rule Id="CA1819" Action="Warning" />    <Rule Id="CA1820" Action="Warning" />    <Rule Id="CA1903" Action="Warning" />    <Rule Id="CA2004" Action="Warning" />    <Rule Id="CA2006" Action="Warning" />    <Rule Id="CA2102" Action="Warning" />    <Rule Id="CA2104" Action="Warning" />    <Rule Id="CA2105" Action="Warning" />    <Rule Id="CA2106" Action="Warning" />    <Rule Id="CA2115" Action="Warning" />    <Rule Id="CA2119" Action="Warning" />    <Rule Id="CA2120" Action="Warning" />    <Rule Id="CA2121" Action="Warning" />    <Rule Id="CA2130" Action="Warning" />    <Rule Id="CA2205" Action="Warning" />    <Rule Id="CA2215" Action="Warning" />    <Rule Id="CA2221" Action="Warning" />    <Rule Id="CA2222" Action="Warning" />    <Rule Id="CA2223" Action="Warning" />    <Rule Id="CA2224" Action="Warning" />    <Rule Id="CA2226" Action="Warning" />    <Rule Id="CA2227" Action="Warning" />    <Rule Id="CA2231" Action="Warning" />    <Rule Id="CA2239" Action="Warning" />  </Rules> </RuleSet>

Rule groups are again divided into rule sets, which are actually used to target specific coding related issues. All rule sets are uniquely identified by ID value.

Code analysis violation results are shown as warnings when you compile your application or run code analysis from the analyze menu. But you can configure these warnings as errors by adding a <CodeAnalysisTreatWarningsAsErrors>true </CodeAnalysisTreatWarningsAsErrors> tag to your project definition file (.csproj extension file).

Each code analysis violation displayed in the error list contains detailed information on the violation, like code file name, project name, line number etc. You can either fix the violation or suppress the violation. Double clicking on the error list will redirect you to the specific line where violation occurred. You can suppress a violation if that is not applicable for your project either selecting 'In source' or 'In Project' option.

Example of Code Analysis Violations and Fixes

To demonstrate code analysis violations I have created a MVC test application using visual studio 2010 applied "Microsoft All Rules" from code analysis tab under project properties and configured my project file to show code violation warnings as errors. After running code analysis on my test MVC application I found few code violation errors. Out of these errors I have picked up Error 13, which is

"CA1054 : Microsoft.Design : Change the type of parameter
'returnUrl' of method 'AccountController.LogOn(LogOnModel, string)'
from string to System.Uri, or provide an overload of 'AccountController.LogOn(LogOnModel, string)',
that allows 'returnUrl' to be passed as a System.Uri object".

CA1054 violation is shown when a string parameter is declared and variable name contains "uri", "Uri", "urn", "Urn", "url", or "Url". This rule splits the parameter name into tokens and checks any of these tokens equals to "uri", "Uri", "urn", "Urn", "url", or "Url". From my AccountController.LogOn method of test MVC application I am returning a string URL as ActionResult when user validation is passed. To fix this code violation warning I have changed the type of returnUrl parameter from string to System.Uri and did necessary modification in the function body. Source code of the modified function is as follows.

public ActionResult LogOn ( LogOnModel model, System.Uri returnUrl )            {            if ( model == null )                {                throw new ArgumentNullException ( "model" );                }            if ( returnUrl == null )                {                throw new ArgumentNullException ( "returnUrl" );                }            if ( ModelState.IsValid )                {                if ( MembershipService.ValidateUser ( model.UserName, model.Password ) )                    {                    FormsService.SignIn ( model.UserName, model.RememberMe );                    if ( !String.IsNullOrEmpty ( returnUrl.ToString() ) )                        {                        return Redirect ( returnUrl.ToString() );                        }                    else                        {                        return RedirectToAction ( "Index", "Home" );                        }                    }                else                    {                    ModelState.AddModelError ( "", "The user name or password provided is incorrect."                    );                    }                }            // If we got this far, something failed, redisplay form            return View ( model );            }    

Next I want to show you code analysis warning "CA2100: Review SQL queries for security vulnerabilities". As per this rule:

An SQL command string that is built from user input is vulnerable to SQL injection attacks. To fix a violation, use a parameterized query instead of inline SQL query. To fix this code violation warning I have changed the following inline SQL query.

Command.CommandText = "SELECT BankaccountNumber FROM Users " +                 "WHERE Username='" + name +                 "' AND Password='" + password + "'";

Source code of the modified function is as follows.

public object DataQuery (string connectionstring, string name, string password )            {            if ( connectionstring == null )                {                throw new ArgumentNullException ( "connectionstring" );                }            if ( name == null )                {                throw new ArgumentNullException ( "name" );                }            if ( password == null )                {                throw new ArgumentNullException ( "password" );                }            SqlConnection Connection  = null;            SqlCommand Command = null;            SqlTransaction trn = null;            object accountNumber = null;            try                {                Connection = new SqlConnection ( connectionstring );                Command = new SqlCommand ( );                Command.Connection = Connection;                Command.Parameters.Add (                "@username", SqlDbType.NChar ).Value = name;                Command.Parameters.Add (                "@password", SqlDbType.NChar ).Value = password;                Command.CommandText = "SELECT AccountNumber FROM Users " +                "WHERE Username=@username AND Password=@password";                Connection.Open ( );                trn = Connection.BeginTransaction ( );                accountNumber = Command.ExecuteScalar ( );                trn.Commit ( );                return accountNumber;                }            catch ( SqlException )                {                trn.Rollback ( );                }            finally                {                                if ( Connection != null ) Connection.Dispose ( );                if ( Command != null ) Command.Dispose ( );                if ( trn != null ) trn.Dispose ( );                }            return accountNumber;            }

Conclusion

Developers can now create customized FxCop rule sets as per the project requirement using the Visual Studio editor. You have options to configure customized rules up to the Visual Studio solution level.



   
Tapas Pal is a Microsoft Platform technical professional with Tata Consultancy Services, India. He has with seven years of experience, holds Microsoft certifications in .NET 1.1 and .NET 2.0.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap