Business Object Validation Using Attributes in C#
Business Object Validation Using Attributes in C#
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.
相關文章
- C#中Attributes的用法C#
- 9 Rules for Using Color in Business Intelligence DashboardsIntel
- SAP 中的 BOPF(Business Object Processing Framework)ObjectFramework
- Using MongoDB in C#MongoDBC#
- 使用ABAP程式碼給SAP CRM Business object建立附件AttachmentObject
- C#中using的使用C#
- C# json to dynamic objectC#JSONObject
- [Angular 2] Using a Reducer to Change an Object's Property Inside an ArrayAngularObjectIDE
- Database Triggers and event attributes--Event AttributesDatabase
- 溫故之C# using注意事項C#
- Flush an Object Out The Library Cache [SGA] Using The DBMS_SHARED_POOLObject
- jQuery attributes(上)jQuery
- LINQ首部曲: LINQ To Object Part 2 - Using VB.NETObject
- Using Oracle 12cR1 RAC with Oracle E-Business Suite Release 12_1490850.1OracleUI
- Database Triggers and event attributes--Event Attributes【Blog 搬家】Database
- Oracle ASM Attributes DirectoryOracleASM
- Declaring Attributes of FunctionsFunction
- HTML 23 - Form AttributesHTMLORM
- HTML 25 - Input AttributesHTML
- Laravel model validationLaravel
- Java Bean ValidationJavaBean
- WITH VALIDATION 與WITHOUT VALIDATION對分割槽交換的影響
- Syntax Error: ValidationError: Invalid options object. Stylus Loader has been initialized using anErrorObjectZed
- 【黃忠成】LINQ首部曲: LINQ To Object Part 2 - Using VB.NETObject
- Unity Attributes 自帶特性Unity
- Oracle ASM Disk Group AttributesOracleASM
- Playing with __attributes__ (三)
- Playing with __attributes__ (二)
- C#中關於 object,dynamic 一點使用心得C#Object
- 【黃忠成】LINQ首部曲: LINQ To Object Part 2 - Using VB.NET(2)Object
- 【黃忠成】LINQ首部曲: LINQ To Object Part 2 - Using VB.NET(3)Object
- 《Object Detection Using ClusteringAlgorithm Adaptive Searching Regions in Aerial Images》論文10問ObjectGoAPT
- How to convert a numeric value or currency to English words using C#C#
- 爬蟲 - CNN Business爬蟲CNN
- object sender,EventArgs e的一些講解(c#,0)ObjectC#
- dubbo~javax.validation和jakarta.validation的介紹與排雷Java
- LINQ 首部曲 : LINQ To Object Part 1 - Using VB.NET 2008Object
- Spring Validation 的使用Spring