Search code examples
c#visual-studiostylecop

Is it possible to run StyleCop when I save source with Visual Studio2013?


I always do run StyleCop of menu or build the project when I have used StyleCop.
I want to run StyleCop when the program has been saved.

Is it possible?


Solution

  • Unfortunately macros have been dropped but to write an add-in is pretty easy. First of all create a new C# Add-In project (when finished you'll need to deploy your DLL into Visual Studio AddIns folder and restart VS).

    Edit generated template to attach to DocumentSaved event:

    private DocumentEvents _documentEvents;
    
    public void OnConnection(object application,
                             ext_ConnectMode connectMode,
                             object addInInst,
                             ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        _documentEvents = _applicationObject.Events.DocumentEvents;
        _documentEvents.DocumentSaved += DocumentEvents_DocumentSaved;
    
    }
    
    public void OnDisconnection(ext_DisconnectMode disconnectMode,
                                ref Array custom)
    {
        _documentEvents.DocumentSaved -= DocumentEvents_DocumentSaved;
    }
    

    Your DocumentEvents_DocumentSaved method will just need to invoke right VS command (please note command name varies with Visual Studio version you're using).

    private void DocumentEvents_DocumentSaved(Document Document)
    {
        document.DTE.ExecuteCommand("Build.RunCodeAnalysisonSelection", "");
    }
    

    In this case you'll run Code Analysis only on current project (assuming it's what you saved then it's also what you want to test). This assumption fails for Save All so you may need to use "Build.RunCodeAnalysisonSolution". Of course there is a lot of space for improvements (for example when multiple near sequential saves occur).

    If you're targeting VS 2013 then you shouldn't use AddIns because they have been deprecated in favor of Packages. You have same thing to do but you have that notification through IVsRunningDocTableEvents. Override Initialize() in your Package (that will implement IVsRunningDocTableEvents interface). Call AdviseRunningDocTableEvents() from IVsRunningDocumentTable (obtain with GetService()) and you're done.

    Finally note that same technique applies also for any other event (after successful build, before deployment, when closing solution, and so on).