Question: when you're accepting input from a user, one should always:

  1. Ensure the data are valid before writing to the database
  2. Ensure the data are valid while writing to the database
  3. Ask the user to please not perform an injection attack since your system isn't designed to handle it
  4. Do it the clever way!

I'll leave that to you to determine the correct answer. One of Joshua S.'s colleagues, "Dave," chose D.

Dave was working on a new application that like most information systems was just a frontend for CRUD operations in the database. The database had been designed with all kinds of validation logic and custom datatypes to prevent, for example, a phone number of "THISISNOTAPHONENUMBER" from being entered.

With all that validation in the backend, who needs frontend validation?

Protected Sub StudentPhoneNumberRecordDataSource_HandleErrors(ByVal sender As 
Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs, 
ByVal CommandDescription As String)
    Dim sqlException As SqlException = TryCast(e.Exception, SqlException)
    If sqlException IsNot Nothing Then
        Dim txtPhone As Object = e.Command.Parameters("@txtPhone").Value
        Dim sb As New StringBuilder
        Dim haveSqlErrorNumber As Boolean = (sqlException.Errors.Count >= 1)
        Dim firstSqlErrorNumber As Integer = Nothing
        If haveSqlErrorNumber Then firstSqlErrorNumber = sqlException.Errors(0).Number

        If haveSqlErrorNumber AndAlso firstSqlErrorNumber = 2627 Then
        sb.Append(CommandDescription)
        sb.Append(" failed. You cannot have two phone numbers with the same type """)
        sb.Append(e.Command.Parameters("@IDPhoneType").Value)
        sb.Append(""" Sorry.")
        ElseIf haveSqlErrorNumber AndAlso firstSqlErrorNumber = 8152 Then
        sb.Append(CommandDescription)
        sb.Append(" failed.  The entered phone number is probably too long.")
        ElseIf haveSqlErrorNumber AndAlso firstSqlErrorNumber = 515 Then
        sb.Append("You must enter a phone number for ")
        sb.Append(CommandDescription)
        sb.Append(".")
        Else
        sb.Append("Unknown SQL Exception ")
        sb.Append(sqlException.ErrorCode)
        sb.Append(": ")
        sb.Append(sqlException.Message)
        End If
        InsertionErrorPanel.Visible = True
        InsertionErrorLabel.Text = sb.ToString
        e.ExceptionHandled = True
    End If
    End Sub

For those of you that hate VB (which is apparently the entire WTF community), this is error handling code that runs in the event of an error on a database write. So it actually attempts to write the data to the database, and halts if the database rejects your input.

Very clever, Dave.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!