I had a task to create an export process that would prepare some data to be sent over to an external vendor. The only catch was that I expected a lot of fields in my database to contain data that was longer than the external vendor to accept. I needed to do some simple length validatinos for every field that I was exporting.
From my limited experience using DataAnnotations in my .Net MVC projects, I knew this was the best wy to accomplish this. But how to use DataAnnotations in a non-web application? So the first challenge was to figure out how to run the validations since they’re run automatically in the context of a web request:
Not so bad. But what do you do with this List business?
The next challenge was to try to fix-up the data that failed the length validations. The example below fixes some common verbosity in addresses that was safe to do to try to get them within the 35 character limit.
Then, using reflection, I was able to update the object being exported in a generic way:
privatevoidFixup(List<ValidationResult>results){foreach(ValidationResultresultinresults){\\thenameofthekeythatfailedstringkey=result.MemberNames.First();vartype=this.GetType();varprop=type.GetProperty(key);if(Regex.IsMatch(key,"Address")){// the value that failed validationvarval=prop.GetValue(this,null).ToString();// do our best to shorten this field for ourselvesval=val.Replace("Street","St");val=val.Replace("Avenue","Ave");val=val.Replace("Floor","Fl");val=val.Replace("Suite","Ste");val=val.Replace("Drive","Dr");val=val.Replace("Boulevard","Blvd");val=val.Replace("Apartment","Apt");// set the property on the objectprop.SetValue(this,val,null);}}results.Clear();if(!this.TryValidate(outresults)){// log that we failed to fixup a record --- manual intervention required}}