Run resharper silent cleanup on save fails

1k Views Asked by At

I'm trying to clean up my code on save using Resharper's Cleanup Code function. I made a macro that handles DocumentSaved events. The important parts:

Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
                                         Handles DocumentEvents.DocumentSaved
    ...
    DTE.ExecuteCommand("ReSharper_SilentCleanupCode")
    document.Save()
End Sub

Every time I save, I get an exception message that says Error HRESULT E_FAIL has been returned from a call to a COM component. Any ideas?

Note: I see How can I configure ReSharper's code cleanup on save? and it won't work in my situation because I need to respond to the save event. Mapping a macro to CTRL+S isn't enough.

1

There are 1 best solutions below

0
On

I think this is because when you call document.Save() it is recursing and saving again and then it falls over. Try this:

Private Sub DocumentEvents_DocumentSaved(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
    Static currentDocument As EnvDTE.Document

    If Not currentDocument Is Document Then
        currentDocument = Document
        DTE.Windows.Item(Document.Name).Activate()
        DTE.ExecuteCommand("ReSharper_SilentCleanupCode")
        DTE.ActiveDocument.Save()
    End If
End Sub

This worked for me