views:

175

answers:

3

Taking a look at the following question, http://stackoverflow.com/questions/1023186/real-world-use-of-custom-net-attributes how would you implement the solution proposed by @Esteban?

I'm a little confused as to when and where the code would get executed I think. Could you please supply a good sample of code.

I've asked this question before but didn't properly phrase it I think so...

+1  A: 

On submit(save) of the html form(win form) you get back changed Customer class. For each property you check if it has custom attribute(inherited from ValidationAttribute or implementing IValiador interface or something like this) associated with it. For each such property you call the validate method of attribute(create appropriate validation class and call validate method) on the property value.

Alex Reitbort
+1 Thanks for your contribution @Alex.
griegs
+1  A: 

You would use reflection:

public class MyClass
{
     [Description("I'm an attribute!")]
     public int MyField;

     public Attribute GetAttribute(string fieldName)
     {
          FieldInfo field = typeof(MyClass).GetField("MyField");
          Attribute[] attributes = (Attribute[])field.GetCustomAttributes(typeof(Attribute), false);

          DescriptionAttribute desc = (DescriptionAttribute)attributes[0];
          return desc;
     }
}

If the attributed member is a field, you would use FieldInfo, as used in the example. If it's a property, you would use PropertyInfo, the members of FieldInfo and PropertyInfo are pretty much the same.

nasufara
+1 Thanks @darkassassin93. This also goes a long way to solving the mystery.
griegs
+3  A: 

With respect to the question/answer that you reference, I assume that there would be some code that runs either in the data layer or in the class itself that does validation. That code would use Reflection on the object being validated to find the properties with different attributes and run the specific validation logic associated with that attribute on that property.

It might look something like the following:

 public void Validate( object obj )
 {
       foreach (var property in obj.GetType().GetProperties())
       {
            var attribute = property.GetCustomAttributes(typeof(ValidationAttribute), false);
            var validator = ValidationFactory.GetValidator( attribute );
            validator.Validate( property.GetValue( obj, null ) );
       }
 }
tvanfosson
OK, that makes a lot of sense. I thought I was missing a crucial element but turns out I wasn't. Dang! :) Thanks @tvanfosson
griegs