Article Options
Premium Sponsor
Premium Sponsor

Structured Exception Handling in .NET (ApplicationException)
by Arnaldo Sandoval | Published  11/04/2006 | .NET Framework .NET Intermediate Windows Development | Rating:
Page 6

Private SaveToFile() method:
This is the method writing the exception details to a flat file that developers provide when calling the Save() method or to the default file coded in the class.

     Private Sub SaveToFile(ByVal TargetFile As String)

        If TargetFile.Length = 0 Then
            TargetFile = "C:\Temp\ApplicationErrors.log"
        Else
            If
TargetFile.IndexOf(":\") < 0 Then
                TargetFile = "C:\Temp\" & TargetFile
            End If
        End If

        Dim
OutputFile As New System.IO.StreamWriter(TargetFile, True)
        Dim sOutput As String

        sOutput = Me.ErrorDate & "/"
        sOutput &= Me.ErrorTime & "/"
        sOutput &= Me.MachineName & "/"
        sOutput &= Me.OSVersion & "/"
        sOutput &= Me.UserName & "/"
        sOutput &= Me.Source & "/"
        sOutput &= Me.ApplicationVersion & "/"
        sOutput &= Me.ApplicationCulture & "/"
        sOutput &= Me.Method & "/"
        sOutput &= Me.MethodAction & "/"
        sOutput &= Me.Message & "/"
        sOutput &= Me.StackTrace.Trim

        OutputFile.WriteLine(sOutput)
        OutputFile.Close()

TargetFile: This parameter contains the name and location of the file where the exception details will be written.

The first thing the method does is making sure a file name is provided, if the parameter is empty, it assigns the default target flat file: C:\Temp\ApplicationErrors.log, otherwise, it checks the given file name for a drive name sign within the name, searching for ":\" does the trick, if no evidence of a drive name is found, the code insert the folder "C:\Temp\".

WARNING: This approach has its weakness, and you may want to improve it.

  1. The log file could be at each user workstation's C:\Temp folder.
  2. Users' workstations C: drive could be hidden.
  3. The drive validation seems poorly implemented, what about a network drive name?

The method keep going by opening the TargetFile, building a long string with all the exception details, separating them with pipes, appending the long string to the file and finally closing the TargetFile.

Private SaveToAccess() Method:
This method write our application's exception details to an Access Database, the access database is accessed thru a connection string, so as long as it is reachable we have nothing to worry about.

     Private Sub SaveToAccess(ByVal ConnectionStringKey As String)

        Dim SQL_Connection As New OleDbConnection
        Dim SQL_Command As New OleDbCommand
        Dim sSQL_Command As String = ""
        '
        ' Retrieve the connection string, from config file, pass it to the command object
        
'
        If ConnectionStringKey.Length = 0 Then
            ConnectionStringKey = DEFAULT_CONNECTION_STRING
        End If

        SQL_Connection.ConnectionString = AppSettings.Get(ConnectionStringKey)
        SQL_Command.Connection = SQL_Connection
        '
        ' Build the INSERT command
        '
        sSQL_Command = "INSERT INTO ErrorLog ( " & _
                       " [ErrorDate] " & _
                       " , [ErrorTime] " & _
                       " , [Machine] " & _
                       " , [OSVersion] " & _
                       " , [User] " & _
                       " , [Application] " & _
                       " , [Version] " & _
                       " , [Method] " & _
                       " , [Action] " & _
                       " , [Message] " & _
                       " , [ErrorStack] " & _
                       ") " & _
                       "VALUES ( " & _
                       " @ErrorDate " & _
                       " , @ErrorTime " & _
                       " , @Machine " & _
                       " , @OSVersion " & _
                       " , @User " & _
                       " , @Application " & _
                       " , @Version " & _
                       " , @Method " & _
                       " , @Action " & _
                       " , @Message " & _
                       " , @ErrorStack " & _
                       ")"
        '
        ' We don't have to worry about apostrophes in the fields we are saving to the database
        ' because we are passing their values as parameters, and its add method takes care of them.
        '
        With SQL_Command
            .Parameters.Add("@ErrorDate", Me.ErrorDate)
            .Parameters.Add("@ErrorTime", Me.ErrorTime)
            .Parameters.Add("@Machine", Me.MachineName)
            .Parameters.Add("@OSVersion", Me.OSVersion)
            .Parameters.Add("@User", Me.UserName)
            .Parameters.Add("@Application", Me.Source)
            .Parameters.Add("@Version", Me.ApplicationVersion)
            .Parameters.Add("@Method", Me.Method)
            .Parameters.Add("@Action", Me.MethodAction)
            .Parameters.Add("@Message", Me.Message)
            .Parameters.Add("@ErrorStack", Me.StackTrace.Trim)

            .CommandText = sSQL_Command
        End With
        '
        ' We are now ready to go
        '
        Try
            '
            SQL_Connection.Open()
            SQL_Command.ExecuteNonQuery()
        Catch ex As OleDbException
            '
            ' We got an error!!! saving the exception to file instead.
            '
            SaveToFile("")
            '
        End Try
        '
        ' Cleaning up
        '
        SQL_Command.Dispose()
        SQL_Connection.Close()
        SQL_Connection.Dispose()
        '
    
End Sub

ConnectionStringKey: This parameter pass the connection string "key" as defined at the application's config file, for the database we are using. The sample application attached (Test_ErrorHandlingException) defined it as shown:

<appSettings>
   <!-- User application and configured property settings go here.-->
   <!-- Example: <add key=
"settingName" value="settingValue"/> -->
   <add key="DBConnStringErrorHandlingException" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\TargetErrorLog.mdb" />
</appSettings>

Because, it is a connection string, you should replace it with the appropriated entry for your database location; the connection string key name is: DBConnStringErrorHandlingException, and the class uses it as a default when an empty connection string key is passed.

The connection string uses the access database TargetErrorLog.mdb located at the C:\temp folder, the database name could be anything, and there are no restrictions, the same goes with the folder C:\temp.

As we are retrieving the connection string from the application's config file, we should include the namespace: Imports System.Configuration.ConfigurationSettings at the top of the class file, as previously explained.

WARNING: Keep in mind the SaveToAccess method lacks an strong validation for a missing connection string, you should make sure the application's config file has its entry before playing around with this class.

Sponsored Links