Calculate Code Metrics for .NET Core Projects?

2019-04-18 15:18发布

问题:

I am playing arround with ASP.NET Core and .NET Core projects. For classic C# projects Visual Studio 2015 has got the feature to calculate code metrics. For .NET Core the support is missing in the Preview 2 Tooling.

Does anybody know a workaround until the tooling is more complete?

回答1:

It is now available in VS 2019 Preview 1, according to this:

https://developercommunity.visualstudio.com/idea/351625/netcore-code-metrics.html?childToView=404758



回答2:

NDepend supports .NET core as per this

Also, SonarQube can provide some of the metrics (e.g. Lines of Code, Cyclomatic Complexity) you are looking for. According to the release notes, version 2.3+ supports .NET Core



回答3:

I added the Microsoft.CodeAnalysis.FxCopAnalyzers nuget package to my .Net Core project. This allowed me to right click and run code analysis, which works great.

The next challenge was getting the Calculate Code Metrics menu option to work.

Unfortunately this still generates the error:

An error occurred while calculating code metrics for target file '.dll' in project . Could not identify platform

The bad news is that this will not be fixed for Visual Studio 2017 however it does work as expected in Visual Studio 2019 (currently Preview 2).

The good news I managed to calculate metrics using the Roslyn Analyzers github project. I cloned the repo (https://github.com/dotnet/roslyn-analyzers.git). And then build the solution. One of the artifacts created is Metrics.exe in the path <your dev root>\roslyn-analyzers\artifacts\bin\Metrics\Debug\net46\Metrics.exe

Opening a command prompt and running Metrics.exe yields useful help text. Remember to specify a project or sln file and /out:<metrics fine name>.xml

Usage: Metrics.exe <arguments>

Help for command-line arguments:

/project:<project-file>  [Short form: /p:<project-file>]
Project(s) to analyze.

/solution:<solution-file>  [Short form: /s:<solution-file>]
Solution(s) to analyze.

/out:<file>  [Short form: /o:<file>]
Metrics results XML output file.

/quiet  [Short form: /q]
Silence all console output other than error reporting.

/help  [Short form: /?]
Display this help message.

This generates a rather unwieldy XML file which can then be parsed to extract the metrics you are after. It's a bit painful but worked for me since all I wanted was to do a one-off set of analysis on a rather extensive .Net Core 2 codebase.