Reflection and regex

At work we encountered a problem with certain characters in strings, these had to be filtered out before inserting or selecting things from the database so the application would be a little less vulnerable to Sql-Injection. But this was easier said then done, and we wanted one method for all the objects. Because we did not want to place regex.replace all over the place, as you know I like to automate tedious little tasks that are repetitive. So I took a stab at it, and came upon reflection.

This is what I came up with (I think it quite elegant if I might say so myself)  a method that takes whatever object you put in there, it iterates through the properties to find a string and replace the blacklisted chars with whatever we wanted in this case nothing.

If you read this and have any suggestions please, let me know same goes for questions.

public void RunThroughObj(object thing)
        {
            //Run through its values
            foreach (PropertyInfo propertyInfo in thing.GetType().GetProperties())
            {
                //If type of object property equeals string replace blacklist chars
                if (propertyInfo.GetValue(thing).GetType().ToString() == "System.String"){
                    Regex rgx = new Regex("([\"<'>/&])+");
                    propertyInfo.SetValue(thing, rgx.Replace(propertyInfo.GetValue(thing).ToString(), ""));
                }
            }
        }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s