Search code examples
c#.net.net-4.0cil

How to validate C# code?


I'm working on a WPF application that validates C# code from files.

I was able to get the file and, for a different need, instantiate its type.

Now what I need is validate that code against some criteria I set. What do I mean?

Let's say I have a file "Test.cs" and this file has the following code:

using xpto;
using abcd;

public class Test
{
    public static void Testing()
    {
        Iqueryable<XYZ> var1 = ctx.Where(c => c.IdSomething == number);
        var1 = var1.Where(v => v.Count(x => x.ValZ) > 0);
    }
}

In my app I would instantiate this file (already being done) and then validate it against some rules. For instance, in this line:

var1 = var1.Where(v => v.Count(x => x.ValZ) > 0);

I want to tell that the file is using Count(...) > 0 instead of Any(). I know that can be done by text reading the file, but I wanted to know if that's possible using reflection, or any other way that would not require such hard coding. This is what I do to instantiate the file (this is a working example):

CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile.FullName);
Type instanceType = cr.CompiledAssembly.GetExportedTypes()
    .FirstOrDefault(e => e.Name.Equals(className));

If this is not clear, please let me know so I can try to elaborate.


Solution

  • Well, even if question tends to be too general, you can do it with Microsoft Roslyn. The compiler as a service which you can use to get AST from the code provided and recieve all nececssary information you need.

    As this is big stuff, it's hardly can be presented here with some short and self explanatory answer. It's easier to have a look on concrete example for "how to run stuff", for example here:

    Roslyn CTP: Three Introductory Projects