I have coded something like the following:
[Attrib(typeof(MyCustomType))]
public class TargetType
{
// .....
}
I want to use EnvDTE
to get a reference to the CodeElement
referenced by the typeof
. I know how to get a reference to the attribute argument, and I can use Value
, but that gives me the string typeof(MyCustomType)
.
If I use Value
, I have to break down the string and then try to find the type, which gets hairy if there are two types with the same name but different namespaces.
Is there an easier way to do this?
No, I don't think so, atleast for a <= VS2013, it seems that the
CodeAttributeArgument
doesn't go any further, which is shame. They should've releasedCodeAttributeArgument2
that hasValue
asCodeExpr
:\..If you use >=VS2014, you can get access to Roslyn, and it should become easier - don't know exactly how you can access roslyn inside VS extension, have to wait and see.
In order to get attributes, you can use VS helper:
Original source: https://github.com/PombeirP/T4Factories/blob/master/T4Factories.Testbed/CodeTemplates/VisualStudioAutomationHelper.ttinclude
In a meanwhile, you could use backtracking solution, this is not nice, but it should work, haven't tested it exactly 100%. The basic idea is to start tracking backwards from the class, and keep track of different namespaces/usings that arein the path of a class. This tries to simulate pretty much what a real compiler would do, if it's going to resolve a type:
You need EnvDTETypeLocator too.
For VS2015, an example of roslyn integration can be found from here: https://github.com/tomasr/roslyn-colorizer/blob/master/RoslynColorizer/RoslynColorizer.cs
It'll definitely be A lot easier than it is with current
CodeModel
.You can try to use a way described Get all methods that are decorated with a specific attribute using T4/EnvDTE