Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

FXCop Static Code Analysis For ASP.NET Preventive Action

Posted By: Ajay Saptaputre, 20 Oct,2015  |  Total View : 3911

In my previous article I discussed about NLog to provide custom tracing for your ASP.NET and CRUD Operations Using NHibernate with ASP.NET MVC 5 and Scheduled Tasks In ASP.NET With Quartz.Net

In this article I am going to discuss what static code analysis is or how to prevent FXCop warnings/errors while writing dotnet code. How you can take some preventive action during coding to easily avoid some basic error/warning during FXCop static code analysis.

What is static code analysis?

Microsoft defines some set of rules that mainly targets best practices in writing code. Each rules belongs to different categories that targeting .NET Framework design guidelines like security, design, Interoperability, globalizations and others. Analysis of code, examine your managed code against these predefined rules and through warning or errors with specific number.

What is FXCop?

FxCop is a free static code analysis tool developed by Microsoft available here . FXCop one of the great tool for static code analysis, developed by Microsoft that analysis managed .Net code targeting .NET Framework design guidelines. FxCop analyzes the compiled object code, not the original source code. In this article I am going to discuss about some common errors and warning and how to take preventive action to avoid them during development phase.

FxCop Preventions

FxCop provides warnings/errors that indicate rule violations in managed code libraries. The warnings are organized into rule areas such as design, localization, performance, security and so forth. Each warning signifies a violation of an FxCop rule. We can take necessary action or follow bellow steps to prevent our code from basic FxCop rules violation.

CA1811 : Avoid uncalled private code
Cause : A private or internal (assembly-level) member does not have callers in the assembly, is not invoked by the common language runtime, and is not invoked by a delegate.
Fix Violations
To fix a violation of this rule, remove the non callable code or add code that calls it.

CA1820: Test for empty strings using string length
Cause : A string is compared to the empty string by using Object.Equals.
Fix Violations
To fix a violation of this rule, change the comparison to use the Length property and test for the null string. If targeting .NET Framework 2.0, use the IsNullOrEmpty method.

if (s1 == "")
{
Console.WriteLine("s1 equals empty string.");
}

// Satisfies rule: TestForEmptyStringsUsingStringLength.
if ( !String.IsNullOrEmpty(s1) )
{
Console.WriteLine("s1 != null and s1.Length != 0.");
}

// Satisfies rule: TestForEmptyStringsUsingStringLength.
if (s1 != null && s1.Length == 0)
{
Console.WriteLine("s1.Length == 0.");
}

CA1024: Use properties where appropriate
Cause : A public or protected method has a name that starts with Get, takes no parameters, and returns a value that is not an array.
Fix Violations
To fix a violation of this rule, change the method to a property.

// These methods will violate the rule, and should be properties.
// They each set or return a piece of the current object's state.
public DayOfWeek GetWeekDay ()
{
 return when.DayOfWeek;
}

public DayOfWeek GetWeekDay
{
 get { return when.DayOfWeek; }
}

CA1704 : Identifiers should be spelled correctly
Cause : The name of an identifier contains one or more words that are not recognized by the Microsoft spelling checker library. This rule does not check constructors or special-named members such as get and set property accessors.
Fix Violations
To fix a violation of this rule, correct the spelling of the word or add the word to a custom dictionary that is named CustomDictionary.xml. Place the dictionary in the installation directory of the tool, the project directory, or in the directory that is associated with the tool under the profile of the user (%USERPROFILE%\Application Data\...). To learn how to add the custom dictionary to a project in Visual Studio, see How to: Customize the Code Analysis Dictionary

  • Add words that should not cause a violation under the Dictionary/Words/Recognized path.
  • Add words that should cause a violation under the Dictionary/Words/Unrecognized path.
  • Add words that should be flagged as obsolete under the Dictionary/Words/Deprecated path. See the related rule topic CA1726: Use preferred terms for more information.
  • Add exceptions to the acronym casing rules to the Dictionary/Acronyms/CasingExceptions path.

CA1045: Do not pass types by reference
Cause : A public or protected method in a public type has a ref parameter that takes a primitive type, a reference type, or a value type that is not one of the built-in types.
Fix Violations
To fix a violation of this rule that is caused by a value type, have the method return the object as its return value. If the method must return multiple values, redesign it to return a single instance of an object that holds the values. To fix a violation of this rule that is caused by a reference type, make sure that the behaviour that you want is to return a new instance of the reference. If it is, the method should use its return value to do this.

public static void PassTheReference(ref string argument)
{
 argument = argument + " ABCDE";
}

// The following syntax will work and is a better design.
// It returns the altered argument as a new instance of string.

public static string BetterThanPassTheReference(string argument)
{
 return argument + " ABCDE";
}

CA1059 : Members should not expose certain concrete types
Cause : An externally visible member is a certain concrete type or exposes certain concrete types through one of its parameters or return value. Currently, this rule reports exposure of the following concrete types: A type derived from System.Xml.XmlNode.
Fix Violations
To fix a violation of this rule, change the concrete type to the suggested interface.

System.Xml.XPath.IXPathNavigable .

CA1707 : Identifiers should not contain underscores
Cause : The name of an identifier contains the underscore (_) character.
Fix Violations
Remove all underscore characters from the name.

CA1822 : Mark members as static
Cause : A member that does not access instance data is not marked as static (Shared in Visual Basic).
Fix Violations
Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body, if appropriate.

public class StaticTest
{
   // ... implementation
    // fires CA 1822
    public void Log1(string message)
    {
        Trace.TraceError(message);
    }
    // does not use instance and is static
    public static void Log2(string message)
    {
        Trace.TraceError(message);
    }
}

CA1020 : Avoid namespaces with few types
Cause : A namespace other than the global namespace contains fewer than five types.
Fix Violations
To fix a violation of this rule, try to combine namespaces that contain just a few types into a single namespace.

CA1021 : Avoid out parameters
Cause : A public or protected method in a public type has an out parameter.
Fix Violations
To fix a violation of this rule that is caused by a value type, have the method return the object as its return value. If the method must return multiple values, redesign it to return a single instance of an object that holds the values. To fix a violation of this rule that is caused by a reference type, make sure that the desired behaviour is to return a new instance of the reference. If it is, the method should use its return value to do this.

CA1709 : Identifiers should be cased correctly
Cause : The name of an identifier is not cased correctly. - or - The name of an identifier contains a two-letter acronym and the second letter is lowercase. - or - The name of an identifier contains an acronym of three or more uppercase letters.
Fix Violations
Change the name so that it is cased correctly.

Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...