mustcodemore.com

9.26.2007

SQLSafe Method for C#

We created this utility method a while back to help us provide another layer of security for SQL Injection attacks. Basically its a tiny little method that takes up to three parameters. It is used to trim a string to a specified length (generally the length of your database field) and throw an error if you want it too.

Parm 1. The string to evaluate and trim if necessary
Parm 2. The max length of the string
Parm 3. Thow an exception or not.

Heres the two methods (one with an override)

        /// <summary>
/// Returns a string with single quotes escaped to protect against SQL injection attacks
///
/// This method will throw an exception if the supplied string's length is greater than maxlen
/// </summary>
/// <param name="s"></param>
/// <param name="maxlen"></param>
/// <returns></returns>
public static string SqlSafe(string s,int maxlen)
{
return SqlSafe(s,maxlen,false);
}
/// <summary>
/// Returns a string with single quotes escaped to protect against SQL injection attacks
///
/// </summary>
/// <param name="s"></param>
/// <param name="maxlen"></param>
/// <param name="ThrowExceptionOnTruncate"></param>
/// <returns></returns>
public static string SqlSafe(string s,int maxlen,bool ThrowExceptionOnTruncate)
{
if(s==null)
{
return "";
}
if(ThrowExceptionOnTruncate && s.Length>maxlen)
{
throw new Exception("StringTools.SqlSafe string exceeds maximum length");
}
//replace apostrophies AFTER truncation
//(the doubles don't count for field length)
return Truncate(s,maxlen).Replace("'","''");
}


So this method is called from anywhere (usually i put it right in a parameter going to a SQL DataSource or some Object Data source right before insert or update).
Just call it like this

SBX.StringTools.SqlSafe(HttpContext.Current.Request.UserAgent.ToString(), 255);


In this example i have the SqlSafe method in a static class called SBX.StringTools. If you are going to use this put it in whatever framework class libraries you utilize in your web or forms apps. That way you can re-use it quickly and easily.

mcm.

0 Comments:

Post a Comment

<< Home