Handling non-fatal errors (VB.Net / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\10.API\X0.Handling Errors and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/vb/VS2022/netframework/Modules/10.API/X0.Handling Errors
Overview
On this demo we are going to see how to deal with errors that are not fatal and will normally be ignored, but that can degrade the generated files.
You can hook your own listener to the FlexCelTrace static class to gain control on what should be done when a non-fatal error happens.
Concepts
How to hook a listener to the static FlexCelTrace class. In a normal application you would just hook the listener at the beginning of the application. On this case, since our demo can be used standalone or from the MainDemo browser, we need to make sure we unhook the event when the form is disposed.
How to stop the file generation when a non-fatal error happens.
How we should take care of threading issues, since FlexCelTrace is a static class that could be called from more than one place.
How to ignore different types of errors.
Files
AssemblyInfo.vb
Imports System.Reflection
Imports System.Runtime.CompilerServices
'
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
'
<Assembly: AssemblyTitle("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("(c) 2002 - 2014 TMS Software")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
'
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Revision and Build Numbers
' by using the '*' as shown below:
<Assembly: AssemblyVersion("6.2.1.0")>
'
' In order to sign your assembly you must specify a key to use. Refer to the
' Microsoft .NET Framework documentation for more information on assembly signing.
'
' Use the attributes below to control which key is used for signing.
'
' Notes:
' (*) If no key is specified, the assembly is not signed.
' (*) KeyName refers to a key that has been installed in the Crypto Service
' Provider (CSP) on your machine. KeyFile refers to a file which contains
' a key.
' (*) If the KeyFile and the KeyName values are both specified, the
' following processing occurs:
' (1) If the KeyName can be found in the CSP, that key is used.
' (2) If the KeyName does not exist and the KeyFile does exist, the key
' in the KeyFile is installed into the CSP and used.
' (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
' When specifying the KeyFile, the location of the KeyFile should be
' relative to the project output directory which is
' %Project Directory%\obj\<configuration>. For example, if your KeyFile is
' located in the project directory, you would specify the AssemblyKeyFile
' attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
' (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
' documentation for more information on this.
'
<Assembly: AssemblyDelaySign(False)>
<Assembly: AssemblyKeyFile("")>
<Assembly: AssemblyKeyName("")>
Form1.Designer.vb
Imports System.Collections
Imports System.ComponentModel
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports System.IO
Imports System.Reflection
Imports System.Text
Imports FlexCel.Render
Namespace HandlingErrors
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
''' <summary>
''' Required designer variable.
''' </summary>
Private components As System.ComponentModel.Container = Nothing
''' <summary>
''' Clean up any resources being used.
''' </summary>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If components IsNot Nothing Then
components.Dispose()
End If
End If
'Onhook the event handler. Since this is a form, we need to onhook the event when it is disposed or it would live forever.
RemoveHandler FlexCelTrace.OnError, FlexCelTrace_OnErrorHandler
MyBase.Dispose(disposing)
End Sub
#Region "Windows Form Designer generated code"
''' <summary>
''' Required method for Designer support - do not modify
''' the contents of this method with the code editor.
''' </summary>
Private Sub InitializeComponent()
Me.button1 = New System.Windows.Forms.Button()
Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
Me.label1 = New System.Windows.Forms.Label()
Me.cbStopOnErrors = New System.Windows.Forms.CheckBox()
Me.errorBox = New System.Windows.Forms.TextBox()
Me.cbIgnoreFontErrors = New System.Windows.Forms.CheckBox()
Me.SuspendLayout()
'
' button1
'
Me.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom
Me.button1.Location = New System.Drawing.Point(244, 313)
Me.button1.Name = "button1"
Me.button1.TabIndex = 0
Me.button1.Text = "GO!"
' Me.button1.Click += New System.EventHandler(Me.button1_Click)
'
' saveFileDialog1
'
Me.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All files|*.*"
Me.saveFileDialog1.RestoreDirectory = True
Me.saveFileDialog1.Title = "Save file as: (FILE WILL BE SAVED AS PDF TOO)"
'
' label1
'
Me.label1.Anchor = (CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.label1.BackColor = System.Drawing.Color.FromArgb((CByte(255)), (CByte(255)), (CByte(192)))
Me.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.label1.Location = New System.Drawing.Point(16, 16)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(536, 32)
Me.label1.TabIndex = 1
Me.label1.Text = "This demo shows how to handle non fatal errors in FlexCel by using the FlexCelTra" & "ce static class."
'
' cbStopOnErrors
'
Me.cbStopOnErrors.Location = New System.Drawing.Point(16, 64)
Me.cbStopOnErrors.Name = "cbStopOnErrors"
Me.cbStopOnErrors.Size = New System.Drawing.Size(400, 24)
Me.cbStopOnErrors.TabIndex = 2
Me.cbStopOnErrors.Text = "Stop on non fatal errors"
'
' errorBox
'
Me.errorBox.Anchor = (CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.errorBox.Font = New System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte(0)))
Me.errorBox.Location = New System.Drawing.Point(16, 128)
Me.errorBox.Multiline = True
Me.errorBox.Name = "errorBox"
Me.errorBox.ReadOnly = True
Me.errorBox.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.errorBox.Size = New System.Drawing.Size(536, 160)
Me.errorBox.TabIndex = 3
Me.errorBox.Text = ""
Me.errorBox.WordWrap = False
'
' cbIgnoreFontErrors
'
Me.cbIgnoreFontErrors.Location = New System.Drawing.Point(16, 88)
Me.cbIgnoreFontErrors.Name = "cbIgnoreFontErrors"
Me.cbIgnoreFontErrors.Size = New System.Drawing.Size(208, 24)
Me.cbIgnoreFontErrors.TabIndex = 4
Me.cbIgnoreFontErrors.Text = "Ignore font errors"
'
' mainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(560, 350)
Me.Controls.Add(Me.cbIgnoreFontErrors)
Me.Controls.Add(Me.errorBox)
Me.Controls.Add(Me.cbStopOnErrors)
Me.Controls.Add(Me.label1)
Me.Controls.Add(Me.button1)
Me.Name = "mainForm"
Me.Text = "Handling non fatal errors."
Me.ResumeLayout(False)
End Sub
#End Region
Private WithEvents button1 As System.Windows.Forms.Button
Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
Private label1 As System.Windows.Forms.Label
Private errorBox As System.Windows.Forms.TextBox
Private cbStopOnErrors As System.Windows.Forms.CheckBox
Private cbIgnoreFontErrors As System.Windows.Forms.CheckBox
End Class
End Namespace
Form1.vb
Imports System.Collections
Imports System.ComponentModel
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports System.IO
Imports System.Reflection
Imports System.Text
Imports FlexCel.Render
Namespace HandlingErrors
''' <summary>
''' How to handle non fatal errors with FlexCel.
''' </summary>
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Private FlexCelTrace_OnErrorHandler As FlexCelErrorEventHandler
Public Sub New()
InitializeComponent()
'Create a list to hold error messages. Keeping all error messages in memory is normally not a good thing to do,
'but for this demo it is ok.
ErrorList = New ArrayList()
'Hook our error handler to FlexCel error handler.
FlexCelTrace_OnErrorHandler = New FlexCelErrorEventHandler(AddressOf FlexCelTrace_OnError) 'We will save the value of the delegate here so we can unhook the event on dispose.
AddHandler FlexCelTrace.OnError, FlexCelTrace_OnErrorHandler
End Sub
Private ErrorList As ArrayList
Private Shared ErrorListLock As New Object() 'Used to lock ErrorList and ensure no more than one thread writes to it.
Private ReadOnly Property PathToExe() As String
Get
Return Path.Combine(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), ".."), "..") & Path.DirectorySeparatorChar
End Get
End Property
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
ErrorList.Clear()
errorBox.Text = ""
Try
DoThings()
Catch ex As MyAbortException
MessageBox.Show(ex.Message)
End Try
If ErrorList.Count = 0 Then
errorBox.Text = "No errors!"
Else
errorBox.Text = String.Format("There were {0} error messages" & Environment.NewLine, ErrorList.Count)
For Each s As String In ErrorList
errorBox.AppendText(s & Environment.NewLine)
Next s
End If
End Sub
Private Sub DoThings()
Dim xls As ExcelFile = New XlsFile(True)
xls.NewFile(1, TExcelFileFormat.v2019)
For r As Integer = 1 To 1999
xls.InsertHPageBreak(r) 'This won't throw an exception here, since FlexCel allows to have more than 1025 page breaks, but at the moment of saving. (since an xls file can't have more than that)
Next r
xls.SetCellValue(1, 1, "We have a page break on each row, so this will print/export as one row per page")
xls.SetCellValue(2, 1, "??? ? ? ? ???? ????") 'Since we leave the font at arial, this won't show when exporting to pdf.
Dim fmt As TFlxFormat = xls.GetDefaultFormat
fmt.Font.Name = "Arial Unicode MS"
xls.SetCellValue(3, 1, "??? ? ? ? ???? ????", xls.AddFormat(fmt)) 'this will display fine in the pdf.
fmt.Font.Name = "ThisFontDoesntExists"
xls.SetCellValue(4, 1, "This font doesn't exists", xls.AddFormat(fmt))
'Tahoma doesn't have italic variant. See http://help.lockergnome.com/office/Tahoma-italic-ftopict705661.html
'You shouldn't normally use Tahoma italics in a document. If we embedded the fonts in this pdf, the fake italics wouldn't work.
fmt.Font.Name = "Tahoma"
fmt.Font.Style = TFlxFontStyles.Italic
xls.SetCellValue(5, 1, "This is fake italics", xls.AddFormat(fmt))
If saveFileDialog1.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
Return
End If
Using pdf As New FlexCelPdfExport(xls, True)
pdf.Export(Path.ChangeExtension(saveFileDialog1.FileName, ".pdf"))
End Using
xls.Save(saveFileDialog1.FileName & ".xls")
End Sub
''' <summary>
''' This is the generic event handler for non fatal errors. We hooked it in the mainForm constructor.
''' </summary>
''' <param name="e"></param>
Private Sub FlexCelTrace_OnError(ByVal e As TFlexCelErrorInfo)
If cbIgnoreFontErrors.Checked Then
Select Case e.Error
'Ignore this errors:
Case FlexCelError.PdfFontNotFound, FlexCelError.PdfGlyphNotInFont, FlexCelError.PdfFauxBoldOrItalics
Return
End Select
End If
'Normally tracing non fatal errors is a good idea.
'Depending on the listener of your trace object, you can redirect this to a log, the event viewer or wherever else.
Trace.WriteLine(e.Message)
'If we selected "Stop On Errors" we will abort file generation by throwing an exception that will be
'catched in the main block.
If cbStopOnErrors.Checked Then
Throw New MyAbortException(e.Message)
End If
'In this case this is a single thread app so locking is not really necessary,
'but it is a good practice to always lock access to global objects in this error handler.
'This event handler might me called from more than one thread, and you don't want to mess
'the object collecting the messages (in this case ErrorList).
SyncLock ErrorListLock
ErrorList.Add(System.Threading.Thread.CurrentThread.Name & ": - " & e.Message)
End SyncLock
End Sub
End Class
''' <summary>
''' A custom exception designed to notify us when a non fatal error must be aborted.
''' </summary>
Public Class MyAbortException
Inherits Exception
Public Sub New(ByVal aMessage As String)
MyBase.New(aMessage)
End Sub
End Class
End Namespace
Program.vb
Namespace HandlingErrors
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application.
''' </summary>
<STAThread> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New mainForm())
End Sub
End Class
End Namespace