Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 15 Next »

The C# Ecosystem can be extended with custom rules either by:

  • defining your own rules directly through the Sonar web interface using XPath expressions
  • or by reusing custom rules defined in external tools

Extending Coding Rules using XPath (since version 2.0)

Migrating XPath rules from version 2.0 to 2.1+

Icon

Since version 2.1, grammar rule names are in uppercase, and each word in seperated by an underscore, such as: "COMPILATION_UNIT"
In version 2.0, camel cases was used, such as: "compilationUnit"
To convert XPath expressions written for version 2.0 to ones valid in 2.1, simply add underscores between words and uppercase.

New coding rules can be added using XPath. See the related documentation.

To navigate the AST, download the SSLR CSharp Toolkit.

Reusing Custom Rules from External Tools

Once you have packaged your custom rule in a dll file and added it to your FxCop/Gendarme/StyleCop installation, you need to:

  • add an XML file describing this rule in the "$SONAR_HOME/extensions/rules/ENGINE" where $SONAR_HOME is the root directory of your sonar installation and ENGINE is either "fxcop", "gendarme" or "stylecop".
  • restart Sonar
  • add those new rules to your quality profiles so that they are used during the next Sonar analysis.

Below details on the format of these files.

FxCop XML Format

RULE_CLASS being the name of the .net rule class.
ASSEMBLY.DLL being the name of the dll assembly file containing the rule class.
The XML fragment above assumes that the dll is located in the same directory as the standard fxcop assembly rules files.

Note: to help writing this XML files, "vladonemo" has written a C# program that generates this file based on your custom rules DLL. You can check this out on GitHub, but be aware that this comes with no garanty.

Example

Let's assume you have implemented a rule that checks if variable name follows a naming convention. You have implemented it in a class called "VariableConventionNameCheck", and you have compiled it into a "MyNamingConvetions.dll" assembly file.

Then, you should write the following code snippet in the XML file:

Gendarme XML Format

RULE_CLASS being the name of the .net rule class.
ASSEMBLY.DLL being the name of the dll assembly file containing the rule class. This file should be located in the installation directory of Gendarme, among the dll files provided by Gendarme out of the box.

See the example of FxCop XML format, this is the same principle.

StyleCop XML Format

Example:

  • No labels