public async Task ApplyFixAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (root.FindNode(context.Span).IsKind(SyntaxKind.AddExpression)) { var newRoot = root.ReplaceNode(root.FindNode(context.Span), SyntaxFactory.BinaryExpression( SyntaxKind.AddExpression, SyntaxFactory.ParseExpression("\"+\""), SyntaxFactory.ParseExpression(root.FindNode(context.Span).ToString().Substring(1)))); var newDocument = context.Document.WithSyntaxRoot(newRoot); context.RegisterFix(CodeAction.Create( title: "Replace + with +\"\"", createChangedDocument: _ => newDocument, equivalenceKey: "replace_plus_with_concatenation"), context.Diagnostics[0]); } }
public async Task ApplyFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); if (diagnostic.Id == AsyncMethodCallDiagnosticAnalyzer.MissingAwaitId) { var invocationExpression = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelfBoth of these code examples are part of the Microsoft.CodeAnalysis.CodeFixes package library.(); var newInvocationExpression = invocationExpression.WithExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocationExpression.Expression.WithoutTrivia(), SyntaxFactory.IdentifierName("Wait") ) ).WithTriviaFrom(invocationExpression); var newRoot = root.ReplaceNode(invocationExpression, newInvocationExpression); var document = context.Document.WithSyntaxRoot(newRoot); context.RegisterFix( CodeAction.Create( title: "Add 'await'", createChangedSolution: _ => Task.FromResult(document.WithSyntaxRoot(newRoot)) ), diagnostic); } }