Search Results for

    Show / Hide Table of Contents

    Handling non-fatal errors (C# / netframework)

    Note

    This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\10.API\X0.Handling Errors and also at https:​//​github.​com/​tmssoftware/​TMS-​FlexCel.​NET-​demos/​tree/​master/​csharp/​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.cs

    using System.Reflection;
    using 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 - 2025 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("7.24.0.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.cs

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using FlexCel.Core;
    using FlexCel.XlsAdapter;
    using System.IO;
    using System.Diagnostics;
    using System.Reflection;
    using System.Text;
    
    using FlexCel.Render;
    
    namespace HandlingErrors
    {
        /// <summary>
        /// How to handle non fatal errors with FlexCel.
        /// </summary>
        public partial class mainForm: System.Windows.Forms.Form
        {
    
            private FlexCelErrorEventHandler FlexCelTrace_OnErrorHandler;
            public mainForm()
            {
                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(FlexCelTrace_OnError); //We will save the value of the delegate here so we can unhook the event on dispose.
                FlexCelTrace.OnError += FlexCelTrace_OnErrorHandler;
            }
    
            private ArrayList ErrorList;
            private static object ErrorListLock = new object(); //Used to lock ErrorList and ensure no more than one thread writes to it.
    
            private string PathToExe
            {
                get
                {
                    return Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ".."), "..") + Path.DirectorySeparatorChar;
                }
            }
    
    
            private void button1_Click(object sender, System.EventArgs e)
            {
                ErrorList.Clear();
                errorBox.Text = "";
    
                try
                {
                    DoThings();
                }
                catch (MyAbortException ex)
                {
                    MessageBox.Show(ex.Message);
                }
    
                if (ErrorList.Count == 0) errorBox.Text = "No errors!";
                else
                {
                    errorBox.Text = String.Format("There were {0} error messages" + Environment.NewLine, ErrorList.Count);
                    foreach (string s in ErrorList)
                    {
                        errorBox.AppendText(s + Environment.NewLine);
                    }
                }
            }
    
    
            private void DoThings()
            {
                ExcelFile xls = new XlsFile(true);
                xls.NewFile(1, TExcelFileFormat.v2019);
    
                for (int r = 1; r < 2000; r++)
                {
                    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)
                }
    
                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.
    
                TFlxFormat fmt = 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() != DialogResult.OK) return;
    
                using (FlexCelPdfExport pdf = new FlexCelPdfExport(xls, true))
                {
                    pdf.Export(Path.ChangeExtension(saveFileDialog1.FileName, ".pdf"));
                }
    
                xls.Save(saveFileDialog1.FileName + ".xls");
            }
    
            /// <summary>
            /// This is the generic event handler for non fatal errors. We hooked it in the mainForm constructor.
            /// </summary>
            /// <param name="e"></param>
            private void FlexCelTrace_OnError(TFlexCelErrorInfo e)
            {
    
                if (cbIgnoreFontErrors.Checked)
                {
                    switch (e.Error)
                    {
                        //Ignore this errors:
                        case FlexCelError.PdfFontNotFound:
                        case FlexCelError.PdfGlyphNotInFont:
                        case FlexCelError.PdfFauxBoldOrItalics:
                            return;
                    }
                }
    
    
                //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)
                {
                    throw new MyAbortException(e.Message);
                }
    
                //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).
                lock (ErrorListLock)
                {
                    ErrorList.Add(System.Threading.Thread.CurrentThread.Name + ": - " + e.Message);
                }
            }
        }
    
        /// <summary>
        /// A custom exception designed to notify us when a non fatal error must be aborted.
        /// </summary>
        public class MyAbortException: Exception
        {
            public MyAbortException(string aMessage) : base(aMessage) { }
        }
    }
    

    Form1.Designer.cs

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using FlexCel.Core;
    using FlexCel.XlsAdapter;
    using System.IO;
    using System.Diagnostics;
    using System.Reflection;
    using System.Text;
    using FlexCel.Render;
    namespace HandlingErrors
    {
        public partial class mainForm: System.Windows.Forms.Form
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
    
                //Onhook the event handler. Since this is a form, we need to onhook the event when it is disposed or it would live forever.
                FlexCelTrace.OnError -= FlexCelTrace_OnErrorHandler;
    
                base.Dispose(disposing);
            }
    
            #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 void InitializeComponent()
            {
                this.button1 = new System.Windows.Forms.Button();
                this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
                this.label1 = new System.Windows.Forms.Label();
                this.cbStopOnErrors = new System.Windows.Forms.CheckBox();
                this.errorBox = new System.Windows.Forms.TextBox();
                this.cbIgnoreFontErrors = new System.Windows.Forms.CheckBox();
                this.SuspendLayout();
                // 
                // button1
                // 
                this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
                this.button1.Location = new System.Drawing.Point(244, 313);
                this.button1.Name = "button1";
                this.button1.TabIndex = 0;
                this.button1.Text = "GO!";
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // saveFileDialog1
                // 
                this.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All files|*.*";
                this.saveFileDialog1.RestoreDirectory = true;
                this.saveFileDialog1.Title = "Save file as: (FILE WILL BE SAVED AS PDF TOO)";
                // 
                // label1
                // 
                this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
                this.label1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192)));
                this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                this.label1.Location = new System.Drawing.Point(16, 16);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(536, 32);
                this.label1.TabIndex = 1;
                this.label1.Text = "This demo shows how to handle non fatal errors in FlexCel by using the FlexCelTra" +
                    "ce static class.";
                // 
                // cbStopOnErrors
                // 
                this.cbStopOnErrors.Location = new System.Drawing.Point(16, 64);
                this.cbStopOnErrors.Name = "cbStopOnErrors";
                this.cbStopOnErrors.Size = new System.Drawing.Size(400, 24);
                this.cbStopOnErrors.TabIndex = 2;
                this.cbStopOnErrors.Text = "Stop on non fatal errors";
                // 
                // errorBox
                // 
                this.errorBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
                this.errorBox.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
                this.errorBox.Location = new System.Drawing.Point(16, 128);
                this.errorBox.Multiline = true;
                this.errorBox.Name = "errorBox";
                this.errorBox.ReadOnly = true;
                this.errorBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
                this.errorBox.Size = new System.Drawing.Size(536, 160);
                this.errorBox.TabIndex = 3;
                this.errorBox.Text = "";
                this.errorBox.WordWrap = false;
                // 
                // cbIgnoreFontErrors
                // 
                this.cbIgnoreFontErrors.Location = new System.Drawing.Point(16, 88);
                this.cbIgnoreFontErrors.Name = "cbIgnoreFontErrors";
                this.cbIgnoreFontErrors.Size = new System.Drawing.Size(208, 24);
                this.cbIgnoreFontErrors.TabIndex = 4;
                this.cbIgnoreFontErrors.Text = "Ignore font errors";
                // 
                // mainForm
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(560, 350);
                this.Controls.Add(this.cbIgnoreFontErrors);
                this.Controls.Add(this.errorBox);
                this.Controls.Add(this.cbStopOnErrors);
                this.Controls.Add(this.label1);
                this.Controls.Add(this.button1);
                this.Name = "mainForm";
                this.Text = "Handling non fatal errors.";
                this.ResumeLayout(false);
    
            }
            #endregion
    
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.SaveFileDialog saveFileDialog1;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.TextBox errorBox;
            private System.Windows.Forms.CheckBox cbStopOnErrors;
            private System.Windows.Forms.CheckBox cbIgnoreFontErrors;
    
        }
    }
    

    Program.cs

    using System;
    using System.Windows.Forms;
    
    namespace HandlingErrors
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new mainForm());
            }
        }
    }
    
    In This Article
    Back to top FlexCel Studio for the .NET Framework v7.24.0.0
    © 2002 - 2025 tmssoftware.com