Search code examples
c#code-analysisroslyn

Applying multiple changes to a solution in roslyn


I want to apply changes to several documents of a solution but only the first change is reflected and rest of them are rejected.This link shows how only once can changes be applied to a solution. What would be a work around for this. I would appreciate a link directing to a solution or a code snippet.

Here is my function :

public static async Task<bool> AddMethod(string solutionPath)
{
    var workspace = MSBuildWorkspace.Create(); 
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    ClassDeclarationSyntax cls = SyntaxFactory.ClassDeclaration("someclass");

    foreach (var project in solution.Projects)
    {
        foreach(var document in project.Documents)
        {
            Document doc = project.GetDocument(document.Id);
            var root = await doc.GetSyntaxRootAsync();
            var classes = root.DescendantNodes().Where(n => n.IsKind(SyntaxKind.ClassDeclaration));
            if (classes.Count() != 0)
            {
                SyntaxNode FirstClass = classes.First() as ClassDeclarationSyntax;
                if (FirstClass != null)
                {
                    var newRoot = root.ReplaceNode(FirstClass, cls);
                    doc = doc.WithText(newRoot.GetText());
                    Project proj = doc.Project;
                    var abc = workspace.TryApplyChanges(proj.Solution);
                }
            }
        }
    }
    return true;
}

Solution

  • The workaround proper way to do this is to use ProjectId and DocumentId and apply all your changes to the workspace at one time.

    Try the following:

    public static async Task<bool> AddMethod(string solutionPath)
    {
        var workspace = MSBuildWorkspace.Create();
        var solution = await workspace.OpenSolutionAsync(solutionPath);
        ClassDeclarationSyntax cls = SyntaxFactory.ClassDeclaration("someclass");
    
        foreach (var projectId in solution.ProjectIds)
        {
            var project = solution.GetProject(projectId);
            foreach (var documentId in project.DocumentIds)
            {
                Document doc = project.GetDocument(documentId);
                var root = await doc.GetSyntaxRootAsync();
                var firstClass = root.DescendantNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault();
                if (firstClass == null)
                    return true;
    
                var newRoot = root.ReplaceNode(firstClass, cls);
                doc = doc.WithText(newRoot.GetText());
                //Persist your changes to the current project
                project = doc.Project;
            }
    
            //Persist the project changes to the current solution
            solution = project.Solution;
        }
        //Finally, apply all your changes to the workspace at once.
        var abc = workspace.TryApplyChanges(solution);
        return true;
    }