lundi 5 juin 2017

How to go about VS Extension that executes logic based on reflection from C# code?

It has gotten into my head that I would like to write a Visual Studio Extension that adds specific comments into my currently opened file based on some logic to be executed over the code on the file. I've never developed an extension before so there are a few challanges that I've faced so far, but that's the one that concerns me the most.

So far I've tried compiling the code from the file using reflection, then work on the result to generate the comments that I want. Something along the lines of ...

CompilerParameters parameters = new CompilerParameters()
{
    GenerateExecutable = false,
    GenerateInMemory = true,
};

var provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);

if (results.Errors.HasErrors)
{
    return;
}

var assembly = results.CompiledAssembly;
var types = assembly.GetTypes();

// ... Examine types and do the rest of the logic

This works fine when the file is overly simple, but if it has any dependencies the compilation will fail because it can't find the references from the using statements, which makes perfect sense to me, but don't know how to solve it.

I tried to ditch this approach and use Roslyn (Microsoft's CodeAnalysis library, http://ift.tt/1ydx1gb) instead, but I actually need some object oriented details from the file's source code that I don't think I would have available this way.

At the end of the day, I want to be able to iterate over classes that are child of another specific class, get the methods that have some specific attributes, and augment the file with some comments on top of those methods.

How would you go about doing that? Are there any Open Source extensions out there that perform something similar that I could use as a reference?





Aucun commentaire:

Enregistrer un commentaire