2

I'm trying to use Roslyn to do some mass refactoring on my code.

The idea is to remove a specific using and insert them directly in the code.

For example

using My.Awesome.Namespace;
...
var temp = MyType.Prop;

would become

var temp = My.Awesome.Namespace.MyType.Prop;

I already have a working solution for .cs files using MSBuildWorkspace to parse my solution, find the using reference and replace them in the file. But I can't find how to do the same on the cshtml files.

They do not appear in the Documents property of my project.

Any idea?

Here is the code I'm using to parse the solution

public void Process(string solutionPath, string projectName, string baseNamespace)
{
    //Force import csharp projects
    MSBuildLocator.RegisterDefaults();
    var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOption
    using (var msWorkspace = MSBuildWorkspace.Create())
    {
        var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;

        var project = solution.Projects.FirstOrDefault(x => x.Name == projectName)
        if (project == null)
            throw new InvalidOperationException();

        foreach (var document in project.Documents)
        {
            if (document.SourceCodeKind != SourceCodeKind.Regular)
                continue;

            Console.WriteLine("Fixing file " + document.Name);

            // Remove using of baseNamespace from doc
            var newDoc = RemoveUsing(document, baseNamespace);
            solution = solution.WithDocumentSyntaxRoot(document.Id, newDoc);
        }
        msWorkspace.TryApplyChanges(solution);
    }

}

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
cpaulus
  • 284
  • 1
  • 14
  • I'm just curious: what prompted you to remove the `usings` at the top and insert the namespaces everywhere? Is it a style choice? I'm not offering any argument, just curious. –  Nov 08 '19 at 15:28
  • We are migrating from resources to po to do the translation of our app. All our resources are in a "Project.Translations" folder. Most of the time we use the complete path with the namespace to reference a resource in our code. But sometimes we did made a using with Project.Translations. So as a first step I just want to replace them all with the full path. – cpaulus Nov 08 '19 at 15:37

1 Answers1

0

Here is a decent solution for scanning, parsing, compiling, and getting the semantic models for a solution's .cshtml files: Getting a SemanticModel of a cshtml file?

blaster
  • 8,876
  • 11
  • 48
  • 77