使用Visual Studio DNX项目(.xproj)进行代码分析

Axe*_*eer 9 code-analysis visual-studio visual-studio-2015 .net-core asp.net-core

在"普通"Visual Studio项目(.csproj)的属性中,可以说在Build上启用代码分析(以前称为FxCop).

自从我开始使用新的DNX项目(.xproj)后,我正在寻找类似的东西.我知道可能没有构建输出,所以旧的方法可能不适合这个,但我很确定Code Analysis/FxCop规则仍然适用.此外,应该有一些方法在新的"实际"项目文件(project.json)中注册自定义规则集(.ruleset)文件.

也许我会忽略一些基于Roslyn之类的更现代的东西?

Axe*_*eer 4

最终找到了一个解决方法,应该可以解决这个问题,直到他们(希望)使用下一版本的 .NET Core 和 Visual Studio 修复它。诀窍是执行经典 .NET Framework 构建的“好旧” FxCop,这是运行旧式代码分析所必需的。

库的project.json应该包含类似的内容:

{
  "frameworks": {
    "net46": {
      "buildOptions": {
        "define": [ "CODE_ANALYSIS" ]
      }
    },
    "netstandard1.3": {
      "dependencies": {
        "NETStandard.Library": "1.6.0"
      }
    }
  },

  "scripts": {
    "postcompile": "../../CodeAnalysis.cmd %compile:TargetFramework% %compile:Configuration% %compile:OutputFile% %compile:CompilerExitCode%"
  }
 }
Run Code Online (Sandbox Code Playgroud)

“apps”的project.json应包含实际的运行时

{
  "scripts": {
    "postcompile": "../../CodeAnalysis.cmd %compile:TargetFramework% %compile:Configuration% %compile:OutputFile% %compile:CompilerExitCode% %compile:RuntimeOutputDir%"
  }
 }
Run Code Online (Sandbox Code Playgroud)

因此,使用postcompile事件可以运行某种批处理脚本来执行经典的FxCop(需要 Visual Studio!)。我目前正在使用包含三个文件的设置:

  • 代码分析.cmd
  • 代码分析规则集
  • CodeAnalysis.xml(字典)

该批处理文件“支持”当前的 .NET Framework 4.6 版本,如下所示:

{
  "frameworks": {
    "net46": {
      "buildOptions": {
        "define": [ "CODE_ANALYSIS" ]
      }
    },
    "netstandard1.3": {
      "dependencies": {
        "NETStandard.Library": "1.6.0"
      }
    }
  },

  "scripts": {
    "postcompile": "../../CodeAnalysis.cmd %compile:TargetFramework% %compile:Configuration% %compile:OutputFile% %compile:CompilerExitCode%"
  }
 }
Run Code Online (Sandbox Code Playgroud)

它不像普通的内置东西那么方便,但是当使用Visual Studio时, FxCop的错误/警告会出现在错误列表中(有时需要第二次构建)。不过,它们不会导致构建失败(也许还有另一个技巧......)。

CodeAnalysis.ruleset 示例:

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="All Rules, except a few ones" ToolsVersion="14.0">
    <IncludeAll Action="Error" />
    <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
        <!-- CLS compliant -->
        <Rule Id="CA1014" Action="None" />
        <!-- COM visibility -->
        <Rule Id="CA1017" Action="None" />
    </Rules>
</RuleSet>
Run Code Online (Sandbox Code Playgroud)