Business Object Validation Using Attributes in C#

一劍平江湖發表於2014-11-13

Business Object Validation Using Attributes in C#

7/14/2009

Ok, so there are about 9,000,000 different implementations out there when it comes to validating business objects. Although most of the ones that I see out there are simply tweaked versions ofCSLA.Net. Personally I'm not a big fan of that approach. It works quite well but I just wanted to try something else, so instead I tried out the second most popular approach... Attributes. I know that usually I groan whenever I think about attributes but it actually works pretty well in this instance.

   1: public class Test
   2: {
   3:     [Between(1,4,"This item needs to be between 1 and 4")]
   4:     public int Value{get;set;}
   5: }

That's not that bad. Even if I have ten properties, that isn't that bad. And implementing the attributes themselves is simple as well:

   1: [AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
   2: public class BaseAttribute:Attribute
   3: {
   4:     public BaseAttribute(string ErrorMessage)
   5:     {
   6:         this.ErrorMessage = ErrorMessage;
   7:     }
   8:  
   9:     public string ErrorMessage { get; set; }
  10:  
  11:     internal virtual string IsValid(PropertyInfo Property,object Object)
  12:     {
  13:         return ErrorMessage;
  14:     }
  15: } 
  16:  
  17: public class Between : BaseAttribute
  18: {
  19:     public Between(object MinValue,object MaxValue, string ErrorMessage)
  20:         : base(ErrorMessage)
  21:     {
  22:         this.MinValue = MinValue;
  23:         this.MaxValue = MaxValue;
  24:     }
  25:  
  26:     public object MinValue { get; set; }
  27:     public object MaxValue { get; set; }
  28:  
  29:     internal override string IsValid(PropertyInfo Property, object Object)
  30:     {
  31:         object Value = Property.GetValue(Object, null);
  32:         if (Value is DateTime && (DateTime)Value <= DateTime.Parse(this.MaxValue.ToString()) && (DateTime)Value >= DateTime.Parse(this.MinValue.ToString()))
  33:             return "";
  34:         else if (Value is DateTime)
  35:             return ErrorMessage;
  36:         else if (double.Parse(Value.ToString()) <= double.Parse(this.MaxValue.ToString()) && double.Parse(Value.ToString()) >= double.Parse(this.MinValue.ToString()))
  37:             return "";
  38:         return ErrorMessage;
  39:     }
  40: }

That's it, a constructor, some fields to hold our information, and one function. We do however have to find the attributes and call the function to even check the property, but with a bit of reflection that's pretty simple:

   1: public static class ValidationManager
   2: {
   3:     public static bool Validate(object Object)
   4:     {
   5:         StringBuilder Builder = new StringBuilder();
   6:         if (Object != null)
   7:         {
   8:             Type ObjectType = Object.GetType();
   9:             PropertyInfo[] Properties = ObjectType.GetProperties();
  10:             foreach (PropertyInfo Property in Properties)
  11:             {
  12:                 object[] Attributes = Property.GetCustomAttributes(typeof(BaseAttribute), true);
  13:                 foreach (object Attribute in Attributes)
  14:                 {
  15:                     Builder.Append(((BaseAttribute)Attribute).IsValid(Property, Object));
  16:                 }
  17:             }
  18:         }
  19:         if(string.IsNullOrEmpty(Builder.ToString()))
  20:             return true;
  21:         throw new NotValid(Builder.ToString());
  22:     }
  23: }

That's it really. We just call the Validate function, passing in our object, and in turn  the function gets all of the properties, finds the attributes, and calls the IsValid function appropriately. And because all of our attributes inherit from BaseAttribute, all we need to do is create a new one and the function will automatically pick it up. So if we want one based off of Regex for strings, not a problem:

   1: public class Regex:BaseAttribute
   2: {
   3:     public Regex(string RegexString, string ErrorMessage)
   4:         :base(ErrorMessage)
   5:     {
   6:         this.RegexString = RegexString;
   7:     }
   8:  
   9:     public string RegexString { get; set; }
  10:  
  11:     internal override string IsValid(PropertyInfo Property, object Object)
  12:     {
  13:         object Value = Property.GetValue(Object, null);
  14:         if (Value is String)
  15:         {
  16:             System.Text.RegularExpressions.Regex TempRegex = new System.Text.RegularExpressions.Regex(RegexString);
  17:             if (TempRegex.IsMatch((string)Value))
  18:                 return "";
  19:         }
  20:         return ErrorMessage;
  21:     }
  22: }

Hell if we want to have the ability to cascade and check classes, we can:

   1: public class Cascade:BaseAttribute
   2: {
   3:     public Cascade()
   4:         : base("")
   5:     {
   6:     }
   7:  
   8:     internal override string IsValid(PropertyInfo Property, object Object)
   9:     {
  10:         object Value = Property.GetValue(Object, null);
  11:         if (Property.PropertyType.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
  12:         {
  13:             Type ListType = Value.GetType();
  14:             PropertyInfo IndexProperty = ListType.GetProperty("Item");
  15:             PropertyInfo CountProperty = ListType.GetProperty("Count");
  16:             int Count = (int)CountProperty.GetValue(Value, null);
  17:             for (int x = 0; x < Count; ++x)
  18:             {
  19:                 object IndexedObject = IndexProperty.GetValue(Value, new object[] { x });
  20:                 if (IndexedObject != null)
  21:                 {
  22:                     try
  23:                     {
  24:                         ValidationManager.Validate(IndexedObject);
  25:                     }
  26:                     catch (NotValid e) { return Property.Name + "(" + x + ") : " + e.Message; }
  27:                 }
  28:             }
  29:         }
  30:         else
  31:         {
  32:             if (Value != null)
  33:             {
  34:                 try
  35:                 {
  36:                     ValidationManager.Validate(Value);
  37:                 }
  38:                 catch (NotValid e) { return Property.Name + " : " + e.Message; }
  39:             }
  40:         }
  41:         return "";
  42:     }
  43: }

Heck in the one above, we can even check if this is a list and go through each item in the list... And when we're done creating the attribute, we just tack it on our properties and we're done. So try it out, leave feedback, and happy coding.

相關文章