Paging Doctor Roslyn!

Ever thought "Wow! It would be cool to be analyze code & get some feedback on it." Then you think "Wow! That would be insanely hard & complicated". Look no further. We now have Roslyn or better known as the .Net Compiler Platform. So where to start.

First, we need to get the Nuget package that will allow us to use the Roslyn APIs to do some code analysis & return diagnostics. You can either use the NuGet Package manager (below picture) or from the Package Manager Console & issue the following command: Install-Package Microsoft.CodeAnalysis.


Now that we have the package installed we need to include some libraries in our application. For this demo I'm just using a standard Console Application. You only need one using for Microsoft.CodeAnalysis.CSharp in your Program.cs file & you are ready to rock & roll. Below is the code to analyze a string & print out diagnostics

using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace CodeAnalyzer
{
    class Program
    {
        static void Main(string[] args)
        {
            var tree = CSharpSyntaxTree.ParseText(@"
                public void DoSomething()
                {
                
                ");
            var results = tree.GetDiagnostics().Where(x => x.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error);
 
            Console.WriteLine(results.FirstOrDefault().ToString());
            Console.ReadLine();
 
        }
    }
}
Seriously that is it. Simply create a syntax tree & get diagnostics. The compiler takes care of everything. Now in this case we are only grabbing the first error. Without the FirstOrDefault() we would get a collection (IEnumerable<Diagnostic>) of results. You can see that the above method does not have a closing bracket. So let's run the program & see what we get.
Now ain't that cool! The cool part is you could pass in any string to the ParseText() method for analysis. Say you have an ASP.Net MVC app that someone can insert custom logic. Simply call a method that has a string overload from an Controller & return the results to the user. 

Now if you want to see a pretty awesome example of using Roslyn, go to omealive.io. This is a plugin for Visual Studio that utilized Roslyn for real time code analysis without debugging or running the program. I'l let you see for youself.

Happy coding!
Comments are closed