views:

705

answers:

1

Hi all,

I'm using VS2008 and would like to create a compile time warning / error based on custom attributes on a property (if it is possible).

There are two cases which interest me currently:

  [MyAttribute (typeof(MyClass)]

Where MyClass has to implement an interface. Currently I assert this in the constructor of the attribute, however this doesn't make it easy to track down, due to the nature of the stack trace:

 public MyAttribute (Type MyClassType)
    {
         System.Diagnostics.Debug.Assert(typeof(MyInterface).IsAssignableFrom(MyClassType),
                                         "Editor must implement interface: " + typeof(MyInterface).Name);

    }

The second case which interests me is where I have a type defined in an attribute, if that type implements an interface, then a warning should be displayed if another attribute isn't present.

I.E. if (MyClass.Implements(SomeInterface) && !Exists(SomeAttibute)) { Generate Warning }

[MyAttribute(typeof(MyClass)] 
// Comment next line to generate warning
[Foo ("Bar")]

Thanks!

+2  A: 

You can do that with PostSharp.

I've once done it, and explained how to do it here

Frederik Gheysels
Thanks a lot for that! I had looked at post sharp before (for another problem) and decided it against it, however now I think I will be re-evaluating ;)
Courtney de Lautour
I have just discovered a bit of an issue - it seems that GetCustomAttributes() no longer returns the attribute when it derives from PostSharp.Laos.OnMethodInvocationAspect rather than System.Attribute
Courtney de Lautour
You mean it returns System.Attribute ? Can't you cast it to your own attribute ? (GetCustomAttributes always returns an array of System.Attribute AFAIK, so you always have to cast i think ?
Frederik Gheysels
No, PostShap strips the Aspect attribute out of the metadata when it does its post compilation stage (ILDSAM confirms this). I did get around it by using CompoundAspect rather than OnMethodInvocationAspect as the base class. Then overriding ProvideAspects to re-insert itself into the metadata. -Phew-. Thanks Again :)
Courtney de Lautour
I have just discovered that using '[MulticastAttributeUsage(MulticastTargets.Property, PersistMetaData = true)]' removes the need for the CompoundAspect.
Courtney de Lautour