2

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.

0

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

7 Comments

I just took a look at the Syntax Analysis document. It looks like this is what I need. I'm gonna take some time reading that info and see how I can apply that to my scope. Thanks for your answer.
I tried to download to test it, but it looks like it works only for VS2012, is this true or I didn't search enough? microsoft.com/en-us/download/details.aspx?id=34685 Under Required Pre-installed Products (I have VS2010)
@eestein: no no, I used actually with-in 2010 too.
Older versions of Roslyn worked under VS 2010, the current one doesn't.
@svick Do you know where I can get an older version or is it deprecated?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.