Web developer from Sydney Australia. Currently using asp.net, mvc where possible.

Tuesday, May 11, 2010

Quickly Trim all your model's string properties

While developing a internal application for http://www.jobping.com using ASP.NET MVC 2 I had the old problem of trimming all string properties on the model before saving to the database.

My first reaction was to start adding trim() everywhere but this causes problems when properties are null. Checking for null pushed me over the edge and I quickly came up with some code to do what I needed via reflection.

The code is below, it will quickly trim any string properties on your model object (no promises of course)



With this code, you can simply trim all string properties, lets say you have a blog model object called myBlog, just go myBlog.NullSafeTrimStrings(), job done.

Be warned this is quite an expansive little operation. DO NOT go putting it in a for each loop

kick it on DotNetKicks.com

7 comments:

Boersnoes said...

You might want to select only the properties where the type is string. That way your starting set is already lots smaller.

Unknown said...

public static string SafeTrim(this string item) {
if(!string.IsNullOrEmpty(item))
return item.Trim();

return null;
}

public static void SafeTrimStrings(this T item) {
var properties = TypeDescriptor.GetProperties(item).OfType().Where(p => p.PropertyType == typeof(string));

foreach(var prop in properties) {
if(prop.IsReadOnly) continue;

string currentValue = prop.GetValue(item).ToString();

prop.SetValue(item, currentValue.SafeTrim());
}
}

Mark Kemper said...

@Boersnoes, how would you do that?

I can't see any built in way of selecting just string properties.

If your suggesting a linq query or similar, then we would be iterating over all the properties twice. Once to select the strings, then once more to do the trim.

At the moment is just goes through all properties one time.

Mark Kemper said...

@kim Thanks for posting some actual code :)

Be careful with the change to the first method. If you pass in String.Empty you are returning null!

For the second method, like I said above, doing a linq query will require going through each property an extra time.

I think cutting out the GetIndexedParamters might be a good thing, although I haven't actually tested it.

Thanks for you comment.

my real estate blog said...

Thanks for the codes' I will try that this weekend.


Philippines properties for sale

Unknown said...

chalet a louer
I would like to appreciate your work and would like to tell to my friends.

Unknown said...

great information you write it very clean. I am very lucky to get this tips from you.

Mechanical Seals