How to Use the Visual Studio Code Analysis Tool FxCop

How to Use the Visual Studio Code Analysis Tool FxCop

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.


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 FilesMicrosoft Visual Studio 10.0Team ToolsStatic Analysis ToolsRule Sets. Following is the source XML of basic correctness rules.

? ??ResourceBaseName="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.Localized">
??? ?

? ?"Microsoft.Rules.Managed"> ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ?

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 true 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 [email protected] AND [email protected]"; ???????????????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; ???????????}


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.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as