ReSharper Code Analysis Goes Beyond Visual Studio

One of ReSharper’s most notable features, Code Analysis, is now unleashed and ready to hunt for bad and dead code—without even opening Visual Studio. Dubbed as InspectCode, it is as simple as a command-line tool can be and requires a minimum of one parameter—your solution file. But as it runs it will apply all of ReSharper’s code inspections—that’s over 1,400 of them—to code in all languages supported by ReSharper!
Can’t wait to try it out? Find the latest ReSharper 8 EAP build, download and unzip the Command Line Tools package, and then run InspectCode [SolutionFile].

InspectCode at work

While the tool works its way through your code, let’s take a closer look at its features and use cases.

Output

Execution of InspectCode results in an XML file with code issues found within the specified scope (the whole solution or particular projects). The XML comprises two parts:

  • The list of found issue types where each type has a description, severity level, and a link to the corresponding Code Inspection Wiki entry where available. Also, each issue has a category that can be used to group similar issues.
  • The list of found issues where each issue has its type and place in a file. The issues are grouped by projects.

How the output should be processed is up to you. But here are a couple of recommended next steps: transform the output to an HTML report, or generate some messages on your continuous integration (CI) server based on number and types of detected issues.

Usage Scenarios

Now let’s see how we can use the tool and what exactly we can do with its output. It may be helpful to run it on your local machine, but only if you don’t have ReSharper, because with ReSharper you can get inspection results for a selected scope with a couple of clicks and, if necessary, export detected issues to a report file. A more promising case is to use InspectCode on a CI server where you can integrate it in the build script and add code inspection results to your build reports and messages.

The JetBrains Teamcity team, who is pioneering the use of this tool right now, has created the following visual presentation of the code issues detected by InspectCode:

Presentation of code issues in TeamCity

To learn more, refer to the TeamCity documentation or download the latest version to try it out.

By the way, if you come up with more usage scenarios as you try out InspectCode, please share them with us.

Settings

If you have previously worked on the target solution with ReSharper, you may have already configured code inspections settings. If so, InspectCode will find your custom settings in .DotSettings files and apply them. If there are no settings files, then the default severity levels will be used for all inspections.

Besides custom severity levels for code inspections, InspectCode looks for the following settings in .DotSettings files:

If you want to configure InspectCode on a CI server, you can make all configurations locally with ReSharper, save the settings to the Solution Team-Shared layer, and then commit the resulting SolutonName.sln.DotSettings file in your VCS. InspectCode on the server will find and apply these settings.

As an alternative, you can configure InspectCode by specifying a shared .DotSettings file through the /profile (/p) parameter. In this case the specified settings layer will override settings in all other layers. (See this post to learn how to create and share a common settings file.)

Optional parameters

We have already mentioned two optional parameters: /profile (/p) and /no-swea. Among other optional parameters (which you can see by typing InspectCode /help) the following may come in handy:

  • /output (/o) – lets you set the output file. By default, the output file is saved in the %TEMP% directory.
  • /project – allows analyzing particular project(s) instead of the whole solution. After this parameter, you can type a project name or a wildcard that matches several projects within your solution.
  • /no-buildin-settings – can be used to ignore settings from the Solution Team-Shared layer (SolutonName.sln.DotSettings file).
  • /caches-home – lets you specify a custom location for the data that InspectCode caches. By default, the %TEMP% directory is used, unless there are settings files, in which case the one specified there is used. This parameter can be helpful if you want to use a fast SSD disk for the cache or if you want to store all your build processing data in a single place.

So our command line could look like this:
InspectCode C:ProjectsReSharperresharper.sln /project=Documents /o="C:temp dataResults.xml" /no-swea

Q & A

That’s about all for the introduction of InspectCode. Now let us try and answer some questions you might ask:

  • How are command line tools licensed?
    The EAP version is a free 30-day trial. We are still working on the licensing policy and it will be announced soon.
  • Can I configure InspectCode without ReSharper?
    Currently, configuration without the use of ReSharper is restricted to some basic settings like enabling solution-wide analysis, selecting projects to be analyzed, choosing the output file, and specifying cache location.
  • Does InspectCode consider the Visual Studio project setting ‘Treat warnings as errors’?
    Yes. It will change the severity of issues corresponding to compiler warnings.
  • Will InspectCode analyze a solution that fails to build?
    Yes. In this case you will see all compiler errors in the output in addition to ReSharper-specific issues. The only requirement for correct analysis is that all dependent libraries be referenced correctly.

If you have more questions or feedback about the Command Line Tools, we’ll be happy to hear from you.

This entry was posted in How-To's, Links and Opinions, News and Events and tagged , , , . Bookmark the permalink.

45 Responses to ReSharper Code Analysis Goes Beyond Visual Studio

  1. Andy says:

    so here how i have used the tools. They do nothing for me what is wrong?

    C:UsersBlablaDownloadsR#jb-commandline-8.0.0.15>dupfinder “C:Pathto solutionMy Solution.sln” /debug
    JetBrains Duplicates Finder for .NET
    Running in 64-bit mode, .NET runtime 4.0.30319.18034 under Microsoft Windows NT 6.1.7601 Service Pack 1

    C:UsersBlablaDownloadsR#jb-commandline-8.0.0.15>inspectcode “C:Pathto solutionMy Solution.sln” /debug
    JetBrains InspectCode for .NET
    Running in 64-bit mode, .NET runtime 4.0.30319.18034 under Microsoft Windows NT 6.1.7601 Service Pack 1

  2. Dmitry Matveev says:

    The problem is in the ‘#’ symbol in the path.

  3. Robert Ellison says:

    Thanks for listening! This is what we need to really make effective use of ReSharper. Can’t wait to try it out.

  4. Steven Evans says:

    This is pretty awesome. Really hope the licensing policy works nicely both for open source solutions where everything needs to live in source control since build servers likely are shared, and enterprise environments where having to install things on a build server is possible.

  5. Andy says:

    @DmitryMatveev. Yes, thank you, it was a problem.
    Another question to dupfinder. Why the following command line ignores exclude patterns:
    dupfinder.exe /idle-priority /show-stats /show-text /discard-local-vars /discard-cost=70 /debug /normalize-types /exclude-code-regions=”Windows Form Designer generated code;Component Designer generated code” /o=”dupfinder.xml” “C:PathToMy Solution.sln” /e=”**/*.Designer.cs;**/*.generated.cs;**/Model.cs;”

    I have also tried patterns just like *.Designer.cs, or */*.Designer.cs, but they appear anyway

  6. ta.speot.is says:

    I know that to an extent TeamCity competes with Bamboo, but I’d love to see this integrated with Bamboo.

    It appears dotCover has some experimental integration, care of the community: https://bitbucket.org/squirmy/bamboo-dotnet-plugin

    If the support was there, out-of-the-box, it would likely go some ways to having ReSharper deployed more widely where I work.

  7. Vinod Soni says:

    I think Resharper Command Line failed to write data at the shared location
    I am using following command
    inspectcode \LOUCLRCS03DM02WEB_PHARMACYBuildsPCMSTESTWebSrcPCMS.sln /o=”\LOUCLRCS03DM02WEB_PHARMACYBuildsPCMSTESTWebCode AnalysisResults.xml”

    and getting following error
    Failed to write data to the output file “\LOUCLRCS03DM02WEB_PHARMACYBuildsPCMSTESTWebCode AnalysisResults.xml”

    Kindly help if somebody faced the same kind of problem, It’s working fine if I mention some location of my local machine like C:Results.xml

  8. @Vinod
    Thanks for letting us know! Here’s a bug report based on your feedback.

  9. @Vinod, do you have write access to that shared folder?

  10. Dmitry Matveev says:

    @Andy,
    Sorry for answering you so late and thanks for your question anyway.
    We didn’t announce dupFinder yet so its help is incomplete. Actually everything should work if you specify absolute paths or paths relative to the dupfinder.exe, not to the solution file. This is because dupfinder, unlike InspectCode, doesn’t base its analysis on the solution file. We’ll announce this tool and come up with all details in the nearest future.

  11. Sarrasim says:

    Is there any news about licensing policy for this tool?

  12. @Sarrasim Not yet, please hold on a little more.

  13. Alexander says:

    Can you please update command line tools build for EAP? The last one is expired.

  14. @Alexander, will do, thanks for noticing.

  15. Dan says:

    Is there an InspectCode mode that would be suitable for use in a source control plugin. In other words, I would like to configure my source control system to evaluate all prospective source code submissions against my Resharper rules and reject submissions that do not conform. This would require something more granular than evaluation at the project or solution levels.

  16. Nils says:

    Any updates regarding licensing?

  17. Dmitry Matveev says:

    @Dan,
    Your scenario looks very interesting, but currently inspectCode can only take Visual Studio solutions as input.
    Anyway, I logged your request to our issue tracker so you can watch it there: http://youtrack.jetbrains.com/issue/RSRP-375162

  18. @Nils
    At this point, we’ll make the command-line tools for free. We’ll be looking at ways to provide additional tooling for them, and if we come up with ideas, there might be a paid edition. However, it’s too early to talk about that right now. In the scope if 8.0, they’re going to be free. We’re working on a license agreement reflecting this.

  19. Jesse Houwing says:

    I love what this offers, I’d love to see a few things added:
    - Allow me to run the inspectcode/dupfinder on a .csproj without having to specify the solution file or the project name. Just the file.
    - Allow me to specify a list of .csproj files so that I can work without having a solution context.
    - Give me an output shaping option that outputs MsBuild compatible warnings/errors, that makes it much easier to integrate into workflows that already know how to handle those.
    - Can I somehow specify the Configuration/Platform to analyze?
    - Are you guys planning to allow me to specify a logger/formatter type,assembly that I can pass to the commandline so that warnings and errors can be streamed to the host. Running the tool, then parsing the xml is so 1992 ;).

  20. Dmitry Matveev says:

    @Jesse, thanks for the feedback. I logged everything in our issue tracker.
    Note to others: if you have feature suggestions, please feel free to sign up and use the issue tracker – they won’t get lost there.

  21. Rachel says:

    We have a fairly detailed project structure with a lot of shared .targets files. Each of these is imported by referring to $(SolutionDir).

    However, it seems that the tool(s) subsitute ProjectDir which means that almost none of solution is actually inspected.

    Is this a “feature” :) ?

  22. offler says:

    How can I use the dupfinder from within Resharper 8.0?

  23. @offler
    Duplicate Finder is not a part of ReSharper as an extension to Visual Studio, it’s only available as part of ReSharper Command Line Tools.

  24. yasin says:

    Hi,

    Above i see InspectCode C:ProjectsReSharperresharper.sln /project=Documents /o=”C:temp dataResults.xml” /no-swea

    I try this example with my solution and projects, but when there are more than one project i cant run this command. How can i do like this ?

    C:ProjectsReSharperresharper.sln /project=Documents /project=XxxProject
    /project=YyyProject /o=”C:temp dataResults.xml” /no-swea

  25. Dmitry Matveev says:

    Hi yasin,
    Just use the semicolon (;) to separate multiple project wildcards. So:
    C:ProjectsReSharperresharper.sln /project=Documents;XxxProject;YyyProject /o=”C:temp dataResults.xml” /no-swea
    To make sure that it works correctly, take the latest 8.1 EAP build

  26. yasin says:

    Thanks Dmitry , it work.

    but there is another problem. When i run thşs command with two project, there are two project under issues tag. One of them is correctly produce output but the other don’t produce output correctly. Output is below.

    ….
    File=”..DocumentsVisual Studio 2012ProjectsDeneme2PeakScreen1App.cs” –>(..) Here when i try to find this path i catch the FileNotFoundException normally.
    What can i do to achieve this problem ?

  27. Dmitry Matveev says:

    @yasin, If the tool misbihaves with the correct parameters, please log a bug in our issue tracker, choose ReSharper Automation Tools (Command Line) as a subsystem.

  28. yasin says:

    @Dmitry ,
    I created a bug and i have a question . I have two project and i want to produce xml document. How can it produce output.xml immediately? (like xml flush)

  29. Dmitry Matveev says:

    @yasin, Sorry, I didn’t get you. You mean, two projects in different solutions or get it from R# user interface?

  30. yasin says:

    @Dmitry , i have a solution and two projects in it. R# command line tool produce xml file but when process finish xml isnt published. I have code like;

    using (Process process = new Process())
    {
    StringBuilder argumentLineBuilder = new StringBuilder();
    foreach (string programArg in programArgs)
    argumentLineBuilder.AppendFormat(“{0} “, programArg);

    ProcessStartInfo processStartInfo = new ProcessStartInfo(@”D:YasinProgramlarResharper-commandline-8.0.0.39inspectcode.exe”, argumentLineBuilder.ToString());
    processStartInfo.CreateNoWindow = true;
    processStartInfo.ErrorDialog = false;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.UseShellExecute = false;

    process.StartInfo = processStartInfo;
    process.Start();
    //process.WaitForExit();
    }

    How can the tool produce xml file immediately?

  31. Bernhard says:

    Seems to work reasonable well. I have two questions,

    1) How can I get the same behaviour as resharper if i have incorporated the StyleCop rules? Which setting file should I reference?

    2) I use some legacy files, which very high number of code issues. How can I exclude certain files?

    best regards
    Bernhard

  32. Dmitry Matveev says:

    Thanks for the feedback, Bernhard

    1. If the StyleCop rules are set with ReSharper options, then you should get the same results as if you inspect code with ReSharper, provided that you do not move your solution from the local machine. If you want to run the analysis on a server, then the local settings will not apply. To apply all the necessary settings on the server, you need to save all of them in a single settings fiile and then use this file through the /profile (/p) parameter.
    2. You can use the settings to exlude specific files, here is how to exclude files from code analyis. If you run InspectCode on a server, save the configuration of excluded files to the same settings file, together with your StyleCop rules.

    • Pete says:

      Can you provide a sample config with exclusions? I got the tool to generate a default config but it is not clear how to add exclusions (The link you supplied seems to assume I already have ReSharper and can create the config file via the GUI, which I currently don’t have access to from my current location):

      false

      false
      false

      false

      • dmitry.matveev says:

        Hi, Pete
        Sorry for being away for so long. InspectCode options and the generated XML configs only allow to exclude projects. To exclude files, you need to do it with ReSharper. Unfortunately, ReSharper settings files are not designed to be edited manually, so my only suggestion is to install a trial version of ReSharper to make the necessary configurations.

  33. yasin says:

    Hi,

    When I run inspectcode.exe it produce like this xml content

    But it generally produce well format. File attribute has a problem so it produce relative path. Is it a bug?

    How can i achieve this problem?

    Thanks.

  34. yasin says:

    Xml content like :

    Issue TypeId=”RedundantUsingDirective” File=”..DocumentsVisual Studio 2012ProjectsDeneme2PeakScreen1App.cs” Offset=”0-13″ Message=”Using directive is not required by the code and can be safely removed”

  35. Dmitry Matveev says:

    Hi yasin,
    Check out the Command Line Tools package in the latest R# 8.1 EAP. The file attribute now shows the path relative to the solution.

  36. yasin says:

    Hi Dmitry,

    In my opinion there are still some problem.When i run exe twice, one of output like :
    Issue TypeId=”InconsistentNaming” File=”…………_Xxxx.Tfs.UgaltCodePeakCommonPeak.CommonApplicationInformation.cs” Offset=”981-1001″ Line=”31″ Message=”Name ‘getSiteDirectoryName’ does not match rule ‘Methods, properties and events’. Suggested name is ‘GetSiteDirectoryName’.”
    D:_Xxxx.Tfs.UgCodePeakAppServicePeak.App.Service.MevduatPeak.App.Service.Mevduat.sln

    The other is :
    Solution>…………PeakCommonPeak.CommonPeak.Common.sln
    ApplicationInformation.cs

    File=”D:WorkUGALT2UGALTCodeALMCodePackageALM.Code.Package.CodeAnalysisbinDebugApplicationInformation.cs”

    Can i take absolute path from file attribute ?

    • dmitry.matveev says:

      Hi yasin,
      No, the ‘File’ attribute in the report can only show paths relative to the solution. Could you tell me why you need absolute paths? How are you going to use or process the report?

  37. Peter Stevens says:

    When running InspectCode I get the following failure on some files
    5:04:52.897 INFO – WARN Internal error: The condition (!mySaving) is false.
    15:04:52.898 INFO – WARN Internal exception thrown: The condition (!mySaving) is false.
    15:04:52.898 INFO –
    15:04:52.898 INFO – — EXCEPTION #1/1 [LoggerException]
    15:04:52.898 INFO – Message = “The condition (!mySaving) is false.”
    15:04:52.898 INFO – ExceptionPath = Root
    15:04:52.898 INFO – ClassName = JetBrains.Util.LoggerException
    15:04:52.898 INFO – HResult = COR_E_APPLICATION=80131600
    15:04:52.898 INFO – StackTraceString = ”
    15:04:52.898 INFO – at JetBrains.Util.Logging.Logger.Fail(String messageText)
    15:04:52.898 INFO – at JetBrains.Util.Logging.Logger.Assert(Boolean condition, String message)
    15:04:52.898 INFO – at JetBrains.ReSharper.Psi.Util.Caches.AbstractPersistentCache2.FetchDataForKey(TKey key, TData& data)
    15:04:52.899 INFO - at JetBrains.ReSharper.Daemon.SolutionAnalysis.AnalysisResultsManager.FetchFileResults(IProjectFileWrapper file, DependenciesInfo& dependencies, AdditionalAnalysisInfo& additionalInfo)
    15:04:52.899 INFO - at JetBrains.ReSharper.Daemon.SolutionAnalysis.SolutionAnalysisManager.FetchGlobalUsageAnalysisData(IProjectFile file, IGlobalUsageChecker& usageChecker, IFileContentInfo& fileContentInfo)
    15:04:52.899 INFO - at JetBrains.ReSharper.Daemon.SolutionAnalysis.SolutionAnalysisServiceImpl.FetchGlobalUsageAnalysisData(IPsiSourceFile sourceFile, IGlobalUsageChecker& usageChecker, IFileContentInfo& fileContentInfo)
    15:04:52.899 INFO - at JetBrains.ReSharper.Daemon.UsageChecking.UnusedGlobalDeclarationStage.IsSupported(IPsiSourceFile sourceFile, IGlobalUsageChecker& checker, IFileContentInfo& fileContentInfo)
    15:04:52.899 INFO - at JetBrains.ReSharper.Daemon.UsageChecking.UnusedGlobalDeclarationStage.d__0.MoveNext()
    15:04:52.899 INFO - at System.Linq.Buffer
    1..ctor(IEnumerable1 source)
    15:04:52.899 INFO - at System.Linq.Enumerable.ToArray[TSource](IEnumerable
    1 source)
    15:04:52.899 INFO – at JetBrains.Util.CollectionUtil.AsArray[T](IEnumerable`1 collection)
    15:04:52.899 INFO – at JetBrains.ReSharper.Daemon.Impl.DaemonProcessBase.c__DisplayClassf.b__5(IDaemonStage stage)
    15:04:52.899 INFO – at JetBrains.ReSharper.Daemon.Impl.DaemonProcessBase.c__DisplayClassf.c__DisplayClass16.b__9()
    15:04:52.899 INFO – at JetBrains.Application.Threading.MultiCoreFibersEx.c__DisplayClass4.c__DisplayClass6.b__2()
    15:04:52.899 INFO – at JetBrains.Application.Threading.MultiCoreFibersPool.Fibers.c__DisplayClass8.b__6()
    15:04:52.899 INFO – at JetBrains.Application.Threading.MultiCoreFibersPool.FiberProc()
    15:04:52.899 INFO – at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    15:04:52.899 INFO – at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    15:04:52.899 INFO – at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    15:04:52.899 INFO – at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    15:04:52.899 INFO – at System.Threading.ThreadHelper.ThreadStart()

    When that starts happening, it seems to fail at all next files

  38. Dmitry Matveev says:

    Thanks for the feedback, Peter.
    I logged the exception in ouir issue tracker.

  39. Bill H says:

    Problem was not with the inspectcode, but the idiot user. Should have unblocked the download before unzipping. Erased the installation, unblocked the zip, unzipped and all was good. Sorry ’bout that, you should delete my previous posts before someone gets the wrong impression.
    Cheers,
    Bill

  40. Yasin says:

    Hi,

    When i run inspectcode.exe from cmd i take output as below.

    ERROR: Referenced project with guid ’66c17914-ebeb-413d-af22-a0eef30fd70a’ not found in solution, it’s output assembly wasn’t found either.
    ERROR: Referenced project with guid ‘c77fa773-eec7-409a-9941-f9b777a7098a’ not found in solution, it’s output assembly wasn’t found either.
    ERROR: Referenced project with guid ’38a67e95-4716-4de8-afb3-e373a1229fd3′ not found in solution, it’s output assembly wasn’t found either.
    ERROR: Referenced project with guid ’66c17914-ebeb-413d-af22-a0eef30fd70a’ not found in solution, it’s output assembly wasn’t found either.
    ERROR: Referenced project with guid ’630e5f1d-382b-4362-869b-addd4429a77d’ not found in solution, it’s output assembly wasn’t found either.
    ERROR: Referenced project with guid ’38a67e95-4716-4de8-afb3-e373a1229fd3′ not found in solution, it’s output assembly wasn’t found either.

    Although there are above errors output file is produced.

    And when i run inspectcode.exe from c# code like ;

    using (Process process = new Process())
    {
    StringBuilder argumentLineBuilder = new StringBuilder();
    foreach (string programArg in programArgs)
    argumentLineBuilder.AppendFormat(“{0} “, programArg);
    ProcessStartInfo processStartInfo = new ProcessStartInfo(reSharperPath,
    argumentLineBuilder.ToString());
    processStartInfo.CreateNoWindow = true;
    processStartInfo.ErrorDialog = false;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.UseShellExecute = false;
    process.StartInfo = processStartInfo;
    process.Start();
    }

    Here argumentLineBuilder is “D:\ALM.CodeAnalysis.Solution.20131231093957.sln” /project=”SECLEKYEXC;Xxxx.App.Service.Security;Xxxx.App.Service.Workflow” /o=”C:\Users\vb52401\AppData\Local\Microsoft\Windows\Temporary Internet Files\CodeAnalysis\Peak.CodeAnalysis.ReSharper.20131231094033.xml” /no-swea

    I can’t take output. In my opinion some projects in solution dont have right references so it dont produce output. But in cmd it can produce output.

    How can i take output from c# code even though projects in solution have some reference problems.
    In my case, build errors are not important.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">