pixelbat
pixelbat

Reputation:

Deriving Cyclomatic Complexity in .NET

I know that I can access the cyclomatic complexity to my code in Visual Studio 2008 Team Explorer by right clicking and selecting "Calculate Code Metrics". I would like to expose this data for a web application to display it. Does anybody know of any way of accessing this data through an API?

Thanks for your help!

Upvotes: 5

Views: 1626

Answers (4)

nulltoken
nulltoken

Reputation: 67589

As described in this answer, one can leverage the API of the Gendarme open source tool to calculate the cyclomatic complexity of a method

ModuleDefinition module = ModuleDefinition.ReadModule(fullPathToTheAssembly);

foreach (var type in module.Types)
{
    foreach (var me in type.Methods)
    {
        if (!me.HasBody || me.IsGeneratedCode() || me.IsCompilerControlled)
            continue;
        var r = AvoidComplexMethodsRule.GetCyclomaticComplexity(me);

        Console.WriteLine("{0}: {1}", me.ToString(), r);
    }
}

Upvotes: 2

Lee Harold
Lee Harold

Reputation: 1147

There is no API. But you can read an XML file generated by the Code Metrics Power Tool. So you would generate the code metrics XML file by command line like:

metrics /f:MyAssembly.dll /o:MetricsResults.xml

Then grab the data you want out of MetricsResults.xml.

More info on the power tool here.

If you want to run code metrics in your TFS build, see here and here for options.

Upvotes: 1

Paco
Paco

Reputation: 8381

I use NDepend for stuff like that. You can create CQL queries in NDepend and execute them.
Example:

SELECT METHODS  WHERE CC > 8

returns the methods with a cyclomatic complexity greater than 8.

Upvotes: 2

Charlie Martin
Charlie Martin

Reputation: 112366

I don't -- does Visual Studio have any APIs of that sort? -- but computing cyclomatic complexity is reasonably easy. Gendarme might be your answer.

Upvotes: -1

Related Questions