Skip to content

Instantly share code, notes, and snippets.

@JoshVarty
Created August 18, 2015 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshVarty/56ffc020fe23eff54c87 to your computer and use it in GitHub Desktop.
Save JoshVarty/56ffc020fe23eff54c87 to your computer and use it in GitHub Desktop.
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