Article Options
Recently Viewed
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.

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 11/16/2006)
Rating
The article was in-depth and provided an excellent amount of information.

Chas
 
Comment #2  (Posted by an unknown user on 11/21/2006)
Rating
It was very well designed and useful to understand how I can add this to my systems. However, after moving the TargetErrorLog.mdb to c:\temp and fixing the reference to ErrorHandlingException.dll, the program will only run correctly within VB.net and not as a stand alone exe. I did build the solution and the program. The error I get when running it outside of VB.Net is: File or assembly name ErrorHandlingException, or one of its dependencies, was not found. Maybe this shows my inexperience with VB.Net?
 
Comment #3  (Posted by an unknown user on 11/21/2006)
Rating
It was very well designed and useful to understand how I can add this to my systems. However, after moving the TargetErrorLog.mdb to c:\temp and fixing the reference to ErrorHandlingException.dll, the program will only run correctly within VB.net and not as a stand alone exe. I did build the solution and the program. The error I get when running it outside of VB.Net is: File or assembly name ErrorHandlingException, or one of its dependencies, was not found. Maybe this shows my inexperience with VB.Net?
 
Comment #4  (Posted by Morten Grøtan on 10/29/2007)
Rating
The GetApplicationAttributes method can be greatly simplified by using the AssemblyName object instead of the AssemblyQualifiedName, using this (C#) code:

// C# "short-circuit" mechanism makes sure that the if-check exits at the first false expression
if ((targetSite != null) && (targetSite.ReflectedType != null) && (targetSite.ReflectedType.Assembly != null))
{
// This is the same info as in AssemblyQualifiedName, only represented as an object
AssemblyName assemblyName = targetSite.ReflectedType.Assembly.GetName();

Version version = assemblyName.Version;
if (version != null)
{
_objectVersion = version.ToString();
foundVersion = true;
}

CultureInfo culture = assemblyName.CultureInfo;
if ((culture != null) && (culture.ToString().Length > 0))
{
_objectCulture = culture.ToString();
foundCulture = true;
}
}

 
Comment #5  (Posted by Sumit on 10/17/2008)
Rating
Very useful info.
Thanx
 
Comment #6  (Posted by Buy oem software on 09/29/2011)
Rating
EqdRl5 Hello! How do you feel about young composers?!...
 
Comment #7  (Posted by oem software on 02/10/2012)
Rating
Kz9bIj Thanks, useful material I added your blog to my bookmarks!....
 
Comment #8  (Posted by Buy oem Software on 02/10/2012)
Rating
geS4cf Comrade kill yourself..
 
Comment #9  (Posted by cheap oem software on 02/10/2012)
Rating
PJkgyF Author, keep doing in the same way..!!
 
Comment #10  (Posted by cheap oem software on 02/10/2012)
Rating
K9X2zO I would add something else, of course, but in fact almost everything is mentioned!....
 
Comment #11  (Posted by oem software on 02/10/2012)
Rating
KGsoUs Sent the first post, but it wasn`t published. I am writing the second. It's me, the African tourist..
 
Sponsored Links