Saturday, December 20, 2014

How To - Roslyn (Microsoft.CodeAnalysis) Console project from scratch on Visual Studio 2013

So I had a requirement where I needed to extract method call information from C# files. Microsoft's Compiler Platform Roslyn was the way to go. The following software will need to be installed on your machine.

Installing required tools

  • Visual Studio 2013 ( the official page mentions that you require Visual Studio 2015 Preview - but one can work with 2013)
  • To use MSBuildWorkspace class to load up solutions you need the MSBuild tools 2014 version - which can currently only be obtained through the Visual Studio 2014 CTP iso, As mentioned here you will need to install the 2014 MSBuild  from the Visual Studio "2014 CTP" iso from here.

Creating the project

  1. Create a new Console Application Project
  2. Install the required Nuget packages
    • Microsoft.CodeAnalysis -Pre
      • This can either be done using the Nuget Package Manager Console with the following command
                              Install-Package Microsoft.CodeAnalysis -Pre

                              The -Pre indicates that it is a PreRelease package
      • You can use the Nuget Package Manager UI. Set the 'Include PreRelease' option to enable finding the Microsoft.CodeAnalysis pre-release package as below.
    • Microsoft.Composition package
      • Without this package you end up getting the exception shown below about unable to load the assembly System.Composition.TypedParts. I wonder if MS should make this a dependent package for the CodeAnalysis package ...

Some Code

I use the following code to load a solution

var ws = MSBuildWorkspace.Create();
ws.OpenSolutionAsync(solutionName).Wait();

That's pretty much it.

Roslyn allows you to compile projects, resolves project dependencies so that projects within a solution can be compiled in correct order, get detailed error information and more.

I also use the Nuget.Core package to download and install all packages required for each project. Note also that Roslyn only supports C# and VB currently.

No comments:

Post a Comment