Mat
Mat

Reputation: 1500

Get project element code when saving project

This question will be decomposed into a few sections for understandability purposes and because I haven't found any article/tutorial for it.


Scenario

Let:

In ExistingClass there's absolutely nothing, the class is simply there. Also, ModClass has 2 fields name fieldA and fieldB respectively.


Question

(1) Is there a way to intercept the Save event to (2) get ModClass's code and then (3) parse it so I get the fields for example [I can do that part] and finally (4) automatically write related stuff directly in ExistingClass (or completely regenerate ExistingClass's code.

The question is broad but like I said, it's simply to show the context. What I really want to know is how point 1 can be achieved along with point 2, since the rest is material for another question/research on my side.


Example

I do not have any verifyable example because I do not really know where to start if all this is even possible. I can still demonstrate the concept however with something like shown below.

Before Save event:

namespace MyNamespace
{
    class ExistingClass
    {
    }
}

namespace MyNamespace
{
    class ModClass
    {
        public int myInt; // This hasn't been saved yet
    }
}

After Save event:

namespace MyNamespace
{
    class ExistingClass
    {
        enum MyEnum
        {
            myInt
        }
    }
}

namespace MyNamespace
{
    class ModClass
    {
        public int myInt;
    }
}

In this example, because ModClass was modified, all its code would somehow be thrown to a parser which would get the fields (in this case only myInt) and then ExistingClass would have an enum with all the parsed fields names in it.

Upvotes: 0

Views: 94

Answers (1)

Zhanglong Wu - MSFT
Zhanglong Wu - MSFT

Reputation: 1660

(1) Is there a way to intercept the Save event to

You can achieve it via DocumentEventsClass.DocumentSaved Event

(2) get ModClass's code and then

You can get code via roslyn, for more information, please refer to:

https://www.filipekberg.se/2011/10/20/using-roslyn-to-parse-c-code-files/

(3) parse it so I get the fields for example [I can do that part] and finally (4) automatically write related stuff directly in ExistingClass (or completely regenerate ExistingClass's code.

you can also generate new code via roslyn, the following sample for your reference.

Using the open source released "roslyn" to read code file and generate new code files

Upvotes: 1

Related Questions