I am trying to write some code to find all the method calls for any given method, as I am looking to create an open source UML sequence diagram toolkit. However, I am having trouble passing the first few lines of code: /
The API seems to have changed a lot, and I can't imagine how to use it correctly while looking at the code.
When I do this:
var workspace = new CustomWorkspace(); string solutionPath = @"C:\Workspace\RoslynTest\RoslynTest.sln"; var solution = workspace.CurrentSolution;
I find that workspace.CurrentSolution has 0 projects. I figured this would be equivalent to what Workspace.LoadSolution( string solutionFile ) was earlier, which would then supposedly contain any projects in the solution, but I don't find any success in this way.
I'm terribly confused 0.o
If someone can offer further recommendations on how I can use the FindReferences API to identify all calls to a particular method, that would be very helpful!
Alternatively, would it be better to use a static analysis approach? I would like to support things like lambdas, iterator methods and async.
==================================================== ===================
Edit -
Here is a complete example based on the accepted answer:
using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.FindSymbols; using System.Diagnostics; namespace RoslynTest { class Program { static void Main(string[] args) { string solutionPath = @"C:\Workspace\RoslynTest\RoslynTest.sln"; var workspace = MSBuildWorkspace.Create(); var solution = workspace.OpenSolutionAsync(solutionPath).Result; var project = solution.Projects.Where(p => p.Name == "RoslynTest").First(); var compilation = project.GetCompilationAsync().Result; var programClass = compilation.GetTypeByMetadataName("RoslynTest.Program"); var barMethod = programClass.GetMembers("Bar").First(); var fooMethod = programClass.GetMembers("Foo").First(); var barResult = SymbolFinder.FindReferencesAsync(barMethod, solution).Result.ToList(); var fooResult = SymbolFinder.FindReferencesAsync(fooMethod, solution).Result.ToList(); Debug.Assert(barResult.First().Locations.Count() == 1); Debug.Assert(fooResult.First().Locations.Count() == 0); } public bool Foo() { return "Bar" == Bar(); } public string Bar() { return "Bar"; } } }
source share