Willkommen bei dotnet-snippets.de! Snippet hinzufügen Login Registrieren
Snippets in der Datenbank: 1563 | Anzahl registrierter User: 1896 | Besucher online: 66
Hauptmenü
Home
Top Ten
Zufälliger Snippet
FAQs
.NET Community
dotnet-forum.de
dotnet-kicks.de
Social

RSS Feeds
Rss Alle Snippets
Rss C#
Rss VB.NET
Rss C++
Rss ASP.NET
Partner
Member of Microsoft Community Leader/Insider Program (CLIP)

Extended ExceptionHandling Klasse


Autor: Sebastian
Sprache: VB.NET
Bewertung: 9
(1 Bewertung)
Anzahl der Aufrufe: 4938
  
Kick it on dotnet-kicks.de  

Beschreibung:

Zum Behandeln von Exceptions.

Die Klasse kann Logdateien (auf Wunsch mit Rotation) und in die Windows-Ereignisanzeige schreiben. Wahlweise werden Popupfenster gezeigt oder die Klasse kann komplett deaktiviert werden. Interne Fehler (z.B. bei Zuweisung eines falschen Logdatei-Namens) lösen ein OnError Event aus.

Kommentare und Kritiken sind willkommen.

Beispielanwendung:
        Dim err As New ExtendedExceptionHandling("C:\Testlogfile.log", ExtendedExceptionHandling.RotationType.Daily, True, True)
err.HandleException(New Exception("blahblah"), "Informationen")

err.RaisePopupOnException = False
err.HandleException(New AccessViolationException("zugriffsverletzung"))

err.LogToFile = False
err.HandleException(New Exception("Diese exc darf nicht in der Datei stehen"))

err.WriteToWindowsEventLog = False
err.HandleException(New Exception("Diese ex wird völlig ignoriert"))

err.RaisePopupOnException = True
err.HandleException(New Exception("Diese ex wird nur als fenster angezeigt"))

err.LogToFile = True
err.HandleException(New Exception("wieder in datei"))
err.RaisePopupOnException = False
err.LogfileRotation = ExtendedExceptionHandling.RotationType.Daily
err.HandleException(New Exception("Daily Rotation"))

err.LogfileRotation = ExtendedExceptionHandling.RotationType.Weekly
err.HandleException(New Exception("Weekly Rotation"))

err.Disabled = True
err.HandleException(New Exception("Hilfe!"))


Abgelegt unter: Fehlerbehandlung, Errorhandling, Fehler, Error, Exceptionhandling, Exception.



Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
Namespace Base.ExceptionHandling

    ''' <summary>
    ''' Behandelt Ausnahmefehler, das Event OnError wird ausgelöst wenn bei der Fehlerbehandlung etwas schief läuft
    ''' </summary>
    ''' <remarks>Fehlerbehandlungsklasse Revision 0</remarks>
    Public Class ExtendedExceptionHandling
        Public Enum RotationType
            None = 0
            Daily = 1
            Weekly = 2
            Monthly = 3
            Yearly = 4
        End Enum

        Private _ex As Exception
        Private _Logfile As String = ""
        Private _LogToFile As Boolean
        Private _RaisePopup As Boolean
        Private _Disabled As Boolean = False
        Private _LogfileRotation As RotationType
        Private _InternalLogfilename As String = ""

        Private _WriteToWindowsEventLog As Boolean = False
        Private _EventlogAppName As String = "ApplicationName"
        Private _EventlogLogName As String = "ApplicationGroupName"

        Public Event OnError(ByVal Message As String)

        ''' <summary>
        ''' Name der Anwendung der in der Windows-Ereignisanzeige angezeigt wird
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property EventlogApplicationName() As String
            Get
                Return _EventlogAppName
            End Get
            Set(ByVal value As String)
                _EventlogAppName = value
            End Set
        End Property

        ''' <summary>
        ''' Name der Ereignisanzeigen-Gruppe (z.B. "Anwendung", "Sicherheit" usw)
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property EventlogLogfileGroupName() As String
            Get
                Return _EventlogLogName
            End Get
            Set(ByVal value As String)
                _EventlogLogName = value
            End Set
        End Property

        ''' <summary>
        ''' Aktiviert/Deaktiviert das Schreiben in die Windows-Ereignisanzeige
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>Mit EventlogApplicationName und EventlogLogfileGroupName kann das Ziel angegeben werden</remarks>
        Public Property WriteToWindowsEventLog() As Boolean
            Get
                Return _WriteToWindowsEventLog
            End Get
            Set(ByVal value As Boolean)
                _WriteToWindowsEventLog = value
            End Set
        End Property

        ''' <summary>
        ''' Absoluter Pfad zur Logdatei
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property LogfilePath() As String
            Get
                Return _Logfile
            End Get
            Set(ByVal value As String)
                _Logfile = value
                SetNewLogfileName()
            End Set
        End Property

        ''' <summary>
        ''' Schaltet das Logging in eine Datei
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property LogToFile() As Boolean
            Get
                Return _LogToFile
            End Get
            Set(ByVal value As Boolean)
                If _Logfile <> "" Or value = False Then
                    _LogToFile = value
                Else
                    RaiseEvent OnError("Die Logdatei muss angegeben sein bevor der das Logging in eine Datei angeschaltet wird.")
                End If
            End Set
        End Property

        ''' <summary>
        ''' Schaltet ob IMMER ein Fehlerfenster angezeigt werden soll
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property RaisePopupOnException() As Boolean
            Get
                Return RaisePopupOnException
            End Get
            Set(ByVal value As Boolean)
                _RaisePopup = value
            End Set
        End Property

        ''' <summary>
        ''' Schaltet die Fehlerbehandlung über diese Klasse an/aus
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Disabled() As Boolean
            Get
                Return _Disabled
            End Get
            Set(ByVal value As Boolean)
                _Disabled = value
            End Set
        End Property

        ''' <summary>
        ''' Schaltet die Fehlerbehandlung über diese Klasse an/aus
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Enabled() As Boolean
            Get
                Return Not (_Disabled)
            End Get
            Set(ByVal value As Boolean)
                _Disabled = Not (value)
            End Set
        End Property

        ''' <summary>
        ''' Gibt an in welchem Intervall eine neue Logdatei erzeugt wird
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property LogfileRotation() As RotationType
            Get
                Return _LogfileRotation
            End Get
            Set(ByVal value As RotationType)
                _LogfileRotation = value
                SetNewLogfileName()
            End Set
        End Property

        ''' <summary>
        ''' Setzt den neuen Namen für tägliche/wöchentliche/monatliche Logfiles
        ''' </summary>
        ''' <remarks></remarks>
        Private Sub SetNewLogfileName()
            _InternalLogfilename = _Logfile
            Dim FileNameParts() As String = _Logfile.Split(".")
            If FileNameParts.Length < 2 Then
                RaiseEvent OnError("Der Logfile-Dateiname muss mit Erweiterung (z.B. 'log.txt') angegeben werden, wenn tägliche Logfiles erzeugt werden sollen.")
                Exit Sub
            End If

            Dim FileNameExtension As String = FileNameParts(FileNameParts.Length - 1)
            Dim LogRot As String = ""
            Select Case _LogfileRotation
                Case RotationType.Daily : LogRot = " " & DateAndTime.Now.Year & "-" & DateAndTime.Now.Month & "-" & DateAndTime.Now.Day
                Case RotationType.Weekly : LogRot = " " & DateAndTime.Now.Year & "-W" & DatePart(DateInterval.WeekOfYear, Date.Now)
                Case RotationType.Monthly : LogRot = " " & DateAndTime.Now.Year & "-M" & DateAndTime.Now.Month
                Case RotationType.Yearly : LogRot = " " & DateAndTime.Now.Year
            End Select

            _InternalLogfilename = Left(_Logfile, Len(_Logfile) - Len(FileNameExtension) - 1) & _
                        LogRot & "." & FileNameExtension

        End Sub

        ''' <summary>
        ''' Konstruktor
        ''' </summary>
        ''' <remarks>Defaults: DebugMode = false, LogToFile = false, LogfileRotation = none, RaisePopup = true</remarks>
        Public Sub New()
            _Logfile = ""
            _LogfileRotation = RotationType.None
            _LogToFile = False
            _RaisePopup = True
        End Sub

        ''' <summary>
        ''' Konstruktor
        ''' </summary>
        ''' <param name="LogfilePath"></param>
        ''' <param name="LogfileRotation"></param>
        ''' <param name="RaisePopup"></param>
        ''' <remarks></remarks>
        Public Sub New(ByVal LogfilePath As String, Optional ByVal LogfileRotation As RotationType = RotationType.Weekly, Optional ByVal RaisePopup As Boolean = True, Optional ByVal WriteToWindowsEventLog As Boolean = False)
            _Logfile = LogfilePath
            _LogToFile = True
            _LogfileRotation = LogfileRotation
            _RaisePopup = RaisePopup
            _WriteToWindowsEventLog = WriteToWindowsEventLog
            SetNewLogfileName()
        End Sub

        ''' <summary>
        ''' Behandelt einen Ausnahmefehler
        ''' </summary>
        ''' <param name="ex"></param>
        ''' <remarks>Globale Einstellung für Dateilogging und Popupfenster werden berücksichtigt</remarks>
        Public Sub HandleException(ByVal ex As Exception)
            HandleException(ex, "", _RaisePopup)
        End Sub

        ''' <summary>
        ''' Behandelt einen Ausnahmefehler
        ''' </summary>
        ''' <param name="ex"></param>
        ''' <param name="Remarks">Bemerkungen</param>
        ''' <remarks>Globale Einstellung für Dateilogging und Popupfenster werden berücksichtigt</remarks>
        Public Sub HandleException(ByVal ex As Exception, ByVal Remarks As String)
            HandleException(ex, Remarks, _RaisePopup)
        End Sub

        ''' <summary>
        ''' Behandelt einen Ausnahmefehler
        ''' </summary>
        ''' <param name="ex"></param>
        ''' <param name="RaisePopup">Popupfenster anzeigen?</param>
        ''' <remarks>Globale Einstellung für Dateilogging wird berücksichtigt</remarks>
        Public Sub HandleException(ByVal ex As Exception, ByVal RaisePopup As Boolean)
            HandleException(ex, "", RaisePopup)
        End Sub

        ''' <summary>
        ''' Behandelt einen Ausnahmefehler
        ''' </summary>
        ''' <param name="ex"></param>
        ''' <param name="Remarks">Bemerkungen</param>
        ''' <param name="RaisePopup">Popup Fenster anzeigen?</param>
        ''' <remarks>Globale Einstellung für Dateilogging wird berücksichtigt</remarks>
        Public Sub HandleException(ByVal ex As Exception, ByVal Remarks As String, ByVal RaisePopup As Boolean)

            'Fehlerbehandlung abgeschaltet?
            If _Disabled = True Then
                RaiseEvent OnError(ex.Message)
                Throw ex
                Exit Sub
            End If

            Dim InnerEx As Exception = Nothing

            Dim LogMessage As String = ""
            Dim WinMessage As String = ""

            Dim Message As String = ex.Message
            Dim ModuleName As String
            If Not ex.TargetSite Is Nothing Then
                ModuleName = ex.TargetSite.ToString
            Else
                ModuleName = "*unbekannt*"
            End If

            Dim Trace As String = ex.StackTrace

            LogMessage = vbCrLf & DateAndTime.Now & " -----------------------------------------------------" & vbCrLf
            LogMessage += "[EXCEPTION in Modul: " & ModuleName & "] "
            If Remarks <> "" Then LogMessage += "[" & Remarks & "]"
            LogMessage += vbCrLf & "[MESSAGE] " & ex.Message & vbCrLf
            LogMessage += "[STACKTRACE] " & Trace

            WinMessage = "Fehler in Modul " & ModuleName & ":" & vbCr
            WinMessage += ex.Message

            Try
                InnerEx = ex.InnerException

                'Inner Exception hinzufügen wenn möglich
                If Not InnerEx Is Nothing Then
                    LogMessage += vbCrLf & "[INNER EXCEPTION in Modul " & InnerEx.TargetSite.ToString & "] " & vbCrLf
                    LogMessage += "[INNER STACKTRACE] " & InnerEx.StackTrace

                    WinMessage += vbCr & "Innere Ausnahme in Modul " & InnerEx.TargetSite.ToString & ":" & vbCr
                    WinMessage += InnerEx.Message
                End If

                'In Datei loggen
                If _LogToFile = True Then
                    FileOpen(93, _InternalLogfilename, OpenMode.Append, OpenAccess.ReadWrite)
                    Print(93, LogMessage)
                    FileClose(93)
                End If

                'Popup Fenster anzeigen
                If RaisePopup = True Then MsgBox(WinMessage, MsgBoxStyle.Critical, "Programmfehler")

                'Windows Eventlog
                If _WriteToWindowsEventLog = True Then WriteToEventLog(LogMessage, EventLogEntryType.Error)

            Catch exp As Exception
                RaiseEvent OnError("Fehler beim Behandeln eines Ausnahmefehlers: " & exp.Message & " - " & exp.StackTrace.ToString)
            End Try
        End Sub

        ''' <summary>
        ''' Schreibt ins Windows-Log
        ''' </summary>
        ''' <param name="Entry">Nachricht</param>
        ''' <param name="EventType">Typ</param>
        ''' <remarks></remarks>
        Private Sub WriteToEventLog(ByVal Entry As String, ByVal EventType As EventLogEntryType)
            Dim objEventLog As New EventLog
            Try
                'Applikation registrieren, wenn unbekannt
                If Not EventLog.SourceExists(_EventlogAppName) Then
                    EventLog.CreateEventSource(_EventlogAppName, _EventlogLogName)
                End If
                objEventLog.Source = _EventlogAppName
                'Schreibt in das Eventlog
                objEventLog.WriteEntry(Entry, EventType)
            Catch Ex As Exception
                RaiseEvent OnError("Konnte kein Windows-Ereignis schreiben: " & Ex.Message)
            End Try
        End Sub

    End Class
End Namespace
Sie haben Fragen zu diesem Snippet oder brauchen Hilfe bei der .NET Entwicklung?
Freundliche und kompetente Entwickler helfen Ihnen gern weiter im Forum für .NET Entwicklung.



Kommentare:
(Zum Schreiben von Kommentaren bitte anmelden.)



schlecht sehr gut
1 2 3 4 5 6 7 8 9 10
Nur angemeldete User können Snippets bewerten.