I used my little WebFormContrib library again today. Some days I love revisiting old code because you realize how ignorant of some practices you were in the past. Hopefully none of you download it and say…geez this guy is Mr. Ignoramus. If you do, keep it to yourself. Kidding, please comment and inform the ignorant (me).
Anyhow, it’s been about 6 months since I’ve had to use WebForms, but today I had to and it wasn’t bad. I was able to tie my view into my pages and controls and used AutoMapper to map back to the domain from it. To me, WebFormContrib makes WebForms kinda fun again…cause it makes it seem new. I really do think it’s a great stepping stone to using MVC just because you kinda get used to the syntax. I also think it’s a decent library because I didn’t have to go relearn how it worked, I just referenced the library and then started working on my little WebForm app. I set it up just like I do my MVC apps. I also had to add a couple things and it was easily extendable, which I’m sure you all know is a good thing.
Anyhow, if you have no idea what I’m talking about, please read my previous posts on WebFormContrib.
- The Original – WebFormContrib – Web Forms more like ASP.NET MVC
- WebFormContrib – Sample Part 1
- WebFormContrib – Sample Part 2
- WebFormContrib – Sample Part 3
Also, how could I post without a code sample? In “The Original” post, I mentioned the first thing I wanted to refactor was the validation section. Well, I did. Here’s the new and improved ModelIsValid() method:
internal bool ModelIsValid(TModel view)
{
ErrorMessages = new List<string>();
foreach (var property in typeof(TModel).GetProperties())
{
var value = property.GetValue(view, null);
var attributes = property.GetCustomAttributes(typeof(IValidationAttribute), false);
foreach (IValidationAttribute valatt in attributes)
if (!valatt.IsValid(value))
ErrorMessages.Add(valatt.Message);
}
return ErrorMessages.Count == 0;
}
Previously, it looked like this:
internal bool ModelIsValid(TModel view)
{
ErrorMessages = new List<string>();
foreach (var property in typeof(TModel).GetProperties())
{
var attributes = property.GetCustomAttributes(typeof(RequiredAttribute), false);
if (attributes.Length > 0)
{
var value = property.GetValue(view, null);
if (value.ToSafeString() == string.Empty)
ErrorMessages.Add(((RequiredAttribute)attributes[0]).Message);
}
}
if (ErrorMessages.Count == 0)
return true;
return false;
}
Obviously…I was a moron. I still don’t think it’s perfect, but it is a serious improvement. It’s funny how you don’t see how to refactor something until you need to extend it. As soon as I created the length validator and added the code here I thought…wow this is dumb and then OH! do it this way. Anyhow, I thought I’d share the slight improvement.
You can download the source and samples here…or just download the DLL here.
Thanks for reading!