Created
August 3, 2015 09:17
-
-
Save JoshVarty/2554896b76acbe9c3dc5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(Analyzer1CodeFixProvider)), Shared] | |
public class Analyzer1CodeFixProvider : CodeFixProvider | |
{ | |
... | |
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<TypeDeclarationSyntax>().First(); | |
// Register a code action that will invoke the fix. | |
context.RegisterCodeFix( | |
CodeAction.Create( | |
title: title, | |
createChangedSolution: c => MakeUppercaseAsync(context.Document, declaration, c), | |
equivalenceKey: title), | |
diagnostic); | |
} | |
private async Task<Solution> MakeUppercaseAsync(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken) | |
{ | |
// Compute new uppercase name. | |
var identifierToken = typeDecl.Identifier; | |
var newName = identifierToken.Text.ToUpperInvariant(); | |
// Get the symbol representing the type to be renamed. | |
var semanticModel = await document.GetSemanticModelAsync(cancellationToken); | |
var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken); | |
// Produce a new solution that has all references to that type renamed, including the declaration. | |
var originalSolution = document.Project.Solution; | |
var optionSet = originalSolution.Workspace.Options; | |
var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false); | |
// Return the new solution with the now-uppercase type name. | |
return newSolution; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment