Good code is out of the pipeline ——. NET code specification tools and their use

Source: Internet
Author: User
Tags coding standards dotnet visual studio installer

The previous article introduced some of the commonly used tools in coding standards, and this article specifically describes how to use them to accomplish code management.
The main contents of this article are:

    • Roslyn Introduction
      • Developing Roslyn-based code analyzers
      • Common Roslyn-based code analyzers
    • Using code analyzers in. Net Framework Projects
      • Installing STYLECOP Analyser
      • Set rules
      • Using custom rules for the entire solution
      • Fix code
      • Using Stylecop.json
    • Using a code parser in a. Net core/.net Standard Project
    • Code specification solutions across the IDE
      • Using Editorconfig in VS2017
      • Using the Code specification tool in the VS code
    • Code refactoring &codemaid
    • Summary
Roslyn Introduction

Roslyn is an open source C #, VB compiler that provides a rich code analysis API that third-party applications can use to develop their own code analysis tools. Roslyn is used in VS2015 and above.

Developing Roslyn-based code analyzers

Roslyn provides the relevant SDK to develop its own code analyzer through the SDK:
1. First you need to install the. Net Compiler Platform SDK:
Versions prior to VS2017 15.5 can be downloaded and installed via the following connection:
Https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.NETCompilerPlatformSDK
Versions after VS2017 15.5 can be installed through visual Studio Installer:

  

2. Create an analyzer with Code fix project:

  

3. Introduction to Parser Code:

    • Code structure:

There are three sub-projects in a project that are created, namely, the parser, the parser test project, and the VSIX installation package project as shown in:

  

Where the parser project contains the parser (Analyzer1analyzer), the Code fix (Analyzer1codefixprovider), and the associated resources (RESOURCES.RESX).

    • Analyzer (Analyzer1analyzer):

The core of the parser code is to register a named symbol processor (for processing the class name, interface name, and so on), and the processor's job is to determine if the parse's compliance (name) contains lowercase characters, and if so, give diagnostic information (the diagnostic information definition is included in the resource file).

  

    • Code FIX:

Convert lowercase characters to uppercase:

  

    • Code debugging:

By setting the VSIX project as the startup project, you can debug the parser, and at debug time vs will launch a new vs instance in the sandbox, and with this vs create a project, you can see the diagnostic results and code fixes given by the parser when you write the code:

  

Diagnostic information:

  

Repair results:

  

To view the syntax tree:

  

Common Roslyn-based code analyzers
    • Microsoft.CodeAnalysis.FxCopAnalyzers:

FxCop is an application in the. Net framework that analyzes managed code, which focuses on the design, internationalization, maintainability, performance, and security aspects of the Code, and defines a rule set according to these categories: https:// Docs.microsoft.com/en-us/visualstudio/code-quality/code-analysis-for-managed-code-warnings
Fxcopanalyzers Installation: Https://www.nuget.org/packages/Microsoft.CodeAnalysis.FxCopAnalyzers

    • Stylecop.analyzers

StyleCop itself is a tool for standardizing code formatting, so its rules are also code-oriented , such as annotations, layout, naming, sorting, maintainability, readability, and so on, StyleCop's ruleset reference: https://github.com/ Dotnetanalyzers/stylecopanalyzers/tree/master/documentation
Stylecop.analyzers's Project home: Https://github.com/DotNetAnalyzers/StyleCopAnalyzers

    • Codecracker.csharp:

Codecracker.csharp is also an open source code parser, its rules are mainly design, naming, performance, code style, code usage and refactoring, see: http://code-cracker.github.io/diagnostics.html
Project home: Https://github.com/code-cracker/code-cracker

Note: Codecracker.csharp can implement code analysis by installing the VS extension tool: Https://marketplace.visualstudio.com/items?itemName= Giovannibassi-mvp.codecrackerforc, most of the other Roslyn analyzers need to install nuget packages.

    • Sonaranalyzer.csharp:

Sonaranalyzer.csharp is a very powerful Code analyzer, it has a total of 343 specifications at this stage and mainly for the use of code, including flaw detection, performance, contract, error handling, events, asynchronous, testing and many other kinds of rules, Rules See also: Https://rules.sonarsource.com/csharp
In addition, Sonaranalyzer also has a parser for other languages, and also keeps up to date, project home: https://www.sonarsource.com/products/codeanalyzers/sonarcsharp.html

Using code analyzers in. Net Framework Projects

This article uses stylecop.analyzers as an example to add a code parser to a project.

Installing StyleCop Analyzer

One of the ways to use Roslyn's Code Analyzer in VS is to add the appropriate parser to each project through the NuGet package, as described in StyleCop Analyzer as an example:
To install Stylecop.analyzers through the Package Manager:

  

After the completion of the installation, the parser will return to the code file for analysis, is STYLECOP Analyzer analysis of the default file:

  

At the same time, you can see the newly installed parser under the references/analyzers of the project:

  

Set rules

Each parser has its own set of rules, but not every rule is appropriate for itself or the team, so the severity of the corresponding rule set needs to be: None, Hidden, Info, Warning, Error, where none is the ignore rule not detected, Hidden is detecting but hiding errors.
The rule settings for. Net Framework projects in VS are only required to select Open Active rule set in the right-click menu of analyzers:

  

A ruleset file is then opened with an edit window containing the set of rules that are in effect:

  

  Note: In addition to STYLECOP analyzers, the other is the set of rules built into VS (minimum requirement rule set), vs built-in ruleset information can be selected one of the rules and then viewed in the Properties window (including the rule set description, name, resource file, the path of the Assembly, and so on):

  

The ruleset editing window allows you to edit the rules simply by checking and setting the severity, and when the modifications are complete, a ruleset file is created based on the project name:

  

After you modify the severity of the rule, the original code appears with an error message:

  

A ruleset file called App.ruleset is also generated:

  

Using custom rules for the entire solution

The above approach requires a separate configuration for each project, not only a large amount of work, but also error-prone, resulting in inconsistent rule sets in different projects, in order to solve this problem, you need to share the same ruleset file in one solution.
1. Move the edited ruleset file to a fixed location (the App.ruleset file is placed in a directory that is parallel to the project directory):

2. In the Project Properties window, in the Code Analysis tab, set the rule set for the project, using the rule set placed in a fixed location:

  

  Note: You need to repeat the above actions to set all the project rule sets within the solution.
3. Turn the Code Analysis feature on or off for the full solution:
The General Code analysis tool is only available for open code files, and if you need to parse all code files in the solution you need to check the "Enable" in the menu: Tools->options->text editor->c#->advanced Full Solution Analysis ":

When full solution code analysis is enabled, all code is parsed automatically without opening any code files, and the corresponding results are given:

  

Fix code

When the Code Analyzer finds that it does not conform to the rule, it displays the appropriate information (including normal, warning, error 3 different levels) to the Error List window, double-clicking the information to reach the problematic code, and repairing the code by quickly action. Is the code fix that puts the using statement under the namespace:

  

 Note: When fixing code, the hotfix provides 3 types of fixes, namely the current document, the current project, and the solution, and if the code that does not conform to the rules is in the solution, then choosing a fix solution saves a lot of time.

  

Repair results:

  

You can suppress an error if you encounter an error in the code that cannot be repaired or repaired (suppress)

  

Suppress in source code:

  

To use a global suppression file:

    Note: The Suppress menu appears only on the Shortcut Activity tab at the far left of the corresponding line of code:

  No suppressed menus:

  There are suppressed menus:

  

Using Stylecop.json

In addition to supporting ruleset file configuration rules, STYLECOP analyzers also supports its own Stylecop.json file configuration, and STYLECOP analyzers provides a feature that automatically adds a file header to your code ( The file header contains the file and the modification information).
1. Add a Stylecop.json file with the SA1633 warning:

2. Set "Build Action" to "Additionalfiles"(note: the. NET Standard or. NET core needs to choose C # Analyzer additional file):

  

3. Edit Stylecop.json:

  

  Note: The smart hints in the configuration file are controlled by "$schema" and can be reloaded by the right-click menu when the file is opened.

4. Generate File header information:

  

5. Reuse ruleset files and Stylecop.json in the form of NuGet package for more information view documents: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/ Blob/master/documentation/configuration.md sharing Configuration among Solutions section.

Using a code parser in a. Net core/.net Standard Project

Using a code parser in a. NET core project is similar to using methods in a. NET Framework project, but there are a few different places.
1. It is also necessary to install analyzers for all projects within the solution first:

  

After installation, a warning message appears:

 

2. Modify the rule set:
  Note: the. Net core project does not have an Open Active rule set menu and can only initially set the severity for specific rules for a specific parser:

At the same time, the current project generates a ruleset file named after the project name:

  

When you double-click the file to open it, you can modify the rule set by using the Rule editing window:

  

  Note: There are some details of the VS. Net Core Project's code analysis support so far, this example uses the VS17 15.7.3 version to demonstrate that some versions of the relative older vs version may appear unable to create the ruleset file (manually created according to the project name):

  

Or when editing a ruleset file, the contents of the rule cannot be displayed:

  

When you edit a ruleset file, you need to select all for project to see all the rule sets.
3. Solution share a rule set:
  Note: vs. Net core types of projects, there is no Code Analysis tab when viewing their project properties, so if you are sharing a rule set, you will need to manually add the following XML fragment to each project file in addition to moving the ruleset to a fixed location first:

 <PropertyGroupCondition= "' $ (Configuration) |$ (Platform) ' = = ' release| AnyCPU ' ">    <Codeanalysisruleset>.. \rulesets\my.ruleset</Codeanalysisruleset>  </PropertyGroup>  <PropertyGroupCondition= "' $ (Configuration) |$ (Platform) ' = = ' debug| AnyCPU ' ">    <Codeanalysisruleset>.. \rulesets\my.ruleset</Codeanalysisruleset>  </PropertyGroup>

A rule set file that specifies a relative path for the project.
When the ruleset is configured, the other usage methods are consistent with the methods used in the. Net framework.

Code specification solutions across the IDE

Editorconfig is a project for defining and maintaining code consistency between different editors or Ides, consisting of a code-defined format file and a series of plug-ins, and Microsoft introduces support for Editorconfig in VS2017.

Using Editorconfig in VS2017

To be able to quickly add and edit editorconfig files, you can first install an extension tool called Editorconfig Language Service, which will not only create editorconfig files quickly, but also provide smart hints when editing:

  

Create a Editorconfig file:

  

Edit Editorconfig File:

    

  Note: After modifying the editorconfig, it is necessary to restart vs before it takes effect and is not determined because of individual environmental impact.
VS supports editorconfig Standard Rules (except for the maximum length per line), C # Analysis rules, and. NET analysis rules, the Standard rules are primarily used for uniform code layout styles, while C # and. NET analysis rules are some of the best practices that take advantage of the features of C # and. Net. The same content can also be set through the Tools->options->text Editor->c#->code style:

  

is the field needs to be accessed through this rule, the error message is detected:

  

Using the Code specification tool in the VS code

VS code is a lightweight cross-platform editor that uses vs code to develop a. Net core project is a great choice, and the support for code specification tools is constantly evolving over time vs code.

Using the Roslyn Code Analyzer

When a project is configured with a corresponding ruleset through VS, the project is opened and compiled with VS code, and if the code has unmodified code, the following prompt message appears:

  

VS code is passive compared to the active analysis code, need to be compiled to know which code is problematic, VS code in C # development is supported by C # components:

  

At the same time the component is also concerned about the function of real-time detection code, more information reference: HTTPS://GITHUB.COM/OMNISHARP/OMNISHARP-VSCODE/ISSUES/43

Using Editorconfig

Install the editorconfig extension in vs code:

  

You can then use the Editorconfig canonical code format in VS, but be aware that the VS code in editor only supports Editorconfig's Standard rules.

codemaid& Code Refactoring

Codemaid is a vs extension tool for cleaning and simplifying code, using Codemaid to set code styles (including blank lines, spaces, accessors, file headers, and even support for StyleCop SA1504 and SA1502 rules). The most important thing is that Codemaid can automatically format the code when it is saved:

  

Configuration of the Codemaid (partial):

  

Before the code is saved:

  

After the code is saved:

  

In addition to the ability to automatically format code styles, Codemaid provides some useful features for refactoring code, such as sorting code content by type (such as fields, methods, etc.) (automatic or manual drag). In addition, the code has a cyclomatic complexity (ref.: https://baike.baidu.com/item/%E5%9C%88%E5%A4%8D%E6%9D%82%E5%BA%A6) analysis, and the higher the Cyclomatic complexity is, the more difficult it is to maintain the code.
  Note: Cyclomatic complexity is concerned with the testability and maintainability of code, which is different from the complexity of spatial/temporal complexity that concerns performance.

Summary

This paper mainly introduces the. NET common code specification tools, respectively, are based on Roslyn Code Analyzer, vs and Editorconfig-based code specification tools, and code maid a class of VS extension tools.
One of the most powerful tools is the Roslyn-based code parser, which handles code-style specifications as well as handler performance, security, and so on, and if the code is detected as an error, the code fails to compile successfully, and the only drawback is that each project installs the appropriate code parser ( Note: There are some analyzers that can be installed with the VS extension and can be applied to all projects only once, but both vs and VS code can use Roslyn's Code Analyzer.
Editorconfig is a lightweight code specification tool that, in addition to the code layout rules, takes into account some of the features of the language itself, and Editorconfig is a great choice if you simply have a simple style requirement for your code and use VS as a development tool.
And Codemaid is a different tool than the first two, it is more straightforward, you can apply the corresponding rules when saving.
Reasonable use of code specification tools can greatly improve the quality of code and improve development efficiency.

Reference:

Https://docs.microsoft.com/en-us/visualstudio/code-quality/code-analysis-for-managed-code-warnings
Https://docs.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers
https://codehollow.com/2016/08/use-code-analyzers-csharp-improve-code-quality/
Https://github.com/dotnet/roslyn
https://www.c-sharpcorner.com/UploadFile/vendettamit/introducing-stylecop-with-code-analyzer-in-visual-studio-201/
Https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview
Https://blogs.msdn.microsoft.com/devfish/2017/11/09/rigging-up-roslyn-analyzers-in-net-core/
Https://www.guru99.com/cyclomatic-complexity.html
Https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options
https://msdn.microsoft.com/en-us/library/bb429476 (v=vs.80). aspx
Https://docs.microsoft.com/zh-cn/visualstudio/code-quality/how-to-configure-code-analysis-for-a-managed-code-project
https://msdn.microsoft.com/en-us/library/bb429476 (v=vs.80). aspx
Https://www.linkedin.com/pulse/stylecop-analyzer-better-code-optimization-arpit-gupta
Https://github.com/OmniSharp/omnisharp-vscode/issues/43

This article link: https://www.cnblogs.com/selimsong/p/9209254.html

Good code is out of the box--talking about the code management method of. Net core and landing (update ... )

Good code is out of the pipeline ——. NET code specification tools and their use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.