0

I have written a fix provider which adds members elements resx file. I noticed when visual studio generates the expected changes it calls the method in which add the resource keys to the file.

I'm registering my FixProvider I'm looking for a way to tell if the fix was called from a preview

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
    var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

    // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
    var diagnostic = context.Diagnostics.First();
    var diagnosticSpan = diagnostic.Location.SourceSpan;

    // Find the type declaration identified by the diagnostic.
    var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();

    // Register a code action that will invoke the fix.
    context.RegisterCodeFix(
        CodeAction.Create(
            title: title,
            createChangedDocument: c => this.MakeConstAsync(context.Document, declaration, c),
            equivalenceKey: title),
        diagnostic);
}

How can I tell if the code fix is coming from an action which is mean to fix code and not just generate a preview, I'm assuming there is a way through the CodeFixContext if not the call stack could work too?

johnny 5
  • 19,893
  • 50
  • 121
  • 195

1 Answers1

0

This is not safe, not fully tested but it works. So you may use at you're own risk. You can check up the call stack to see if the path is being called from the preview window:

public static bool IsCallFinal()
{
    var currentStack = new StackTrace();
    return false == currentStack.GetFrames()
              .Any(x => x.GetMethod().Name == "<GetPreviewOperationsAsync>b__0");
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195