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
var mscorlib = MetadataReference.CreateFromAssembly(typeof(object).Assembly); | |
var workspace = new AdhocWorkspace(); | |
var projectId = ProjectId.CreateNewId(); | |
var versionStamp = VersionStamp.Create(); | |
var projectInfo = ProjectInfo.Create(projectId, versionStamp, "NewProject", "projName", LanguageNames.CSharp); | |
var newProject = workspace.AddProject(projectInfo); | |
var sourceText = SourceText.From(@" | |
class C | |
{ | |
void M() | |
{ | |
char key = Console.ReadKey(); | |
if (key == 'A') | |
{ | |
Console.WriteLine(""You pressed A""); | |
} | |
else | |
{ | |
Console.WriteLine(""You didn't press A""); | |
} | |
} | |
}"); | |
var document = workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText); | |
var syntaxRoot = await document.GetSyntaxRootAsync(); | |
var ifStatement = syntaxRoot.DescendantNodes().OfType<IfStatementSyntax>().Single(); | |
var conditionWasTrueInvocation = | |
SyntaxFactory.ExpressionStatement( | |
SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName("LogConditionWasTrue")) | |
.WithArgumentList( | |
SyntaxFactory.ArgumentList() | |
.WithOpenParenToken( | |
SyntaxFactory.Token( | |
SyntaxKind.OpenParenToken)) | |
.WithCloseParenToken( | |
SyntaxFactory.Token( | |
SyntaxKind.CloseParenToken)))) | |
.WithSemicolonToken( | |
SyntaxFactory.Token( | |
SyntaxKind.SemicolonToken)); | |
var conditionWasFalseInvocation = | |
SyntaxFactory.ExpressionStatement( | |
SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName("LogConditionWasFalse")) | |
.WithArgumentList( | |
SyntaxFactory.ArgumentList() | |
.WithOpenParenToken( | |
SyntaxFactory.Token( | |
SyntaxKind.OpenParenToken)) | |
.WithCloseParenToken( | |
SyntaxFactory.Token( | |
SyntaxKind.CloseParenToken)))) | |
.WithSemicolonToken( | |
SyntaxFactory.Token( | |
SyntaxKind.SemicolonToken)); | |
//Finally... create the document editor | |
var documentEditor = await DocumentEditor.CreateAsync(document); | |
//Insert LogConditionWasTrue() before the Console.WriteLine() | |
documentEditor.InsertBefore(ifStatement.Statement.ChildNodes().Single(), conditionWasTrueInvocation); | |
//Insert LogConditionWasFalse() after the Console.WriteLine() | |
documentEditor.InsertAfter(ifStatement.Else.Statement.ChildNodes().Single(), conditionWasFalseInvocation); | |
var newDocument = documentEditor.GetChangedDocument(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment