Sunday, 14 June 2015

Create a Logger using the Trace Listener in C#



When writing software for the commercial world it is crucial your application can log errors, be it to the database, or to a text file, or even to theWindows Event Log if necessary. The .NET Framework contains a mechanism called a Trace Listener. This Listener is an object which directs the trace output to an appropriate target, such as an error log for example.

In this article I am going to show you how to use the Trace Listener to record your application’s errors to an error log.
To begin this example create a console application and add an App.config file to your project. We are going to use the App.config file to tell our application that it should create a trace listener on start-up. Amend the XML code of your App.configfile to look like the below example.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="application.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>
As you can see, we are adding a listener of typeSystem.Diagnostics.TextWriterTraceListener which is set to write to a log file called application.log. Also note that in the <trace> node we are setting theautoflush attribute to true. When set to true this attribute tells the listener to flush the buffer after every write operation. For this example it is great but for real world applications you probably would want to set this to false to limit disk read and write operations.
Now in your static Main method you can write to the log using the Trace class as shown below.
static void Main(string[] args)
{
    Trace.WriteLine("Application started.", "MyApp");

    Trace.WriteLine("working...", "MyApp");

    Trace.WriteLine("Application finished.", "MyApp");
}
If we open the application.log file created automatically by the listener right after we run the above code we will find the following in the file:
MyApp: Application started.
MyApp: working...
MyApp: Application finished.
As you can see it’s quite easy to write to the log file. We didn’t even have to open a FileStream to write to the file because it was all done for us automatically by the listener.
This logger we just created is quite crude since we are not recording the date and time of the error, nor are we recording the source. So let’s extend the concept a little by creating a small logger class as shown below.
using System;
using System.Diagnostics;

public static class Logger
{
    public static void Error(string message, string module)
    {
        WriteEntry(message, "error", module);
    }

    public static void Error(Exception ex, string module)
    {
        WriteEntry(ex.Message, "error", module);
    }

    public static void Warning(string message, string module)
    {
        WriteEntry(message, "warning", module);
    }

    public static void Info(string message, string module)
    {
        WriteEntry(message, "info", module);
    }

    private static void WriteEntry(string message, string type, string module)
    {
        Trace.WriteLine(
                string.Format("{0},{1},{2},{3}",
                              DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                              type,
                              module,
                              message));
    }
}
The above Logger class has four public static methods – WarningInfo, and an overloaded Error method. Each of these methods calls the private WriteEntrymethod which actually writes to the log through the Trace class. As you can see here we are writing the date and time, the entry type (“error”“warning”, or“info”), the module where the error occurred, and the actual error message.
Now to use this class we can do the following:
static void Main(string[] args)
{
    try
    {
        Logger.Info("Application started.", "MyApp");
        Logger.Info("working...", "MyApp");
        Logger.Warning("Application about to exit!", "MyApp");
        Logger.Info("Application finished.", "MyApp");

        throw new Exception();
    }
    catch (Exception ex)
    {
        Logger.Error(ex, "MyApp");
    }
}
The above code would produce the following log:
2009-09-16 23:02:04,info,MyApp,Application started.
2009-09-16 23:02:04,info,MyApp,working...
2009-09-16 23:02:04,warning,MyApp,Application about to exit!
2009-09-16 23:02:04,info,MyApp,Application finished.
2009-09-16 23:02:04,error,MyApp,Exception of type 'System.Exception' was thrown.
And there you have it – you now know how to use the Trace Listener in C# and how to create a simple logger class. Obviously the Logger class we created can be enhanced a lot more. For example you could add code to wrap the log file after it grows to 5MB. You could also add code to log the thread which the error occurred on. There is a large number of amendments you could do to make this class better.
I hope you enjoyed this article. Feel free to leave any comments below or if you want you can contact me through my contact page. Also, if you haven’t already subscribed to my rss feed, please do so – Grab RSS Feed.

Wednesday, 3 June 2015

How to Set Text Alignment in Excel with C#


After exporting data to an Excel file, we need to pay attention to formatting because a well formatted file is more appealed for readers and the data will be shown more clearly. Excel formats include font style, number style and alignment. In this post, I will talk something about how to align data in cells with C#.
There are three mainly used types in alignment, horizontal, vertical and orientation. Generally speaking, if we don’t set alignment for cells, the data in cell will be aligned right in horizontal and bottom in vertical automatically. In my example, I will set all styles of the three alignments.
Note: A component, Spire.XLS for .NET is used in this example for realizing this function more easily and quickly. So, I have added its DLL file as reference in my project.
Steps:
  1. Create a new workbook and one worksheet.
  2. Fill cue words “Text Align” in B1 and format the cell.
  3. Set vertical alignment for text from B3 to D3.
  4. Set default alignment for text in B5 and set format for the cell.
  5. Set horizontal alignment for text from B7 to D7.
  6. Set orientation alignment for text from B9 to C9.
  7. In order to show the setting effects more clearly, I set format for horizontal, vertical and orientation alignment respectively.
  8. Save and launch file.
Coding:
using System;
using System.Drawing;
using Spire.Xls;
namespace Alignment
{
    class Align
    {
        static void Main(string[] args)
        {
            //Create Workbook and Initialize Worksheet
            Workbook workbook = new Workbook();
            workbook.CreateEmptySheets(1);
            Worksheet sheet = workbook.Worksheets[0];
            //Add Cue Word in B1
            sheet.Range[“B1″].Text = “Text Align”;
            sheet.Range[“B1″].Style.Font.FontName = “Calibri”;
            sheet.Range[“B1″].Style.Font.Color = Color.Red;
            sheet.Range[“B1″].Style.Font.Size = 14;
            sheet.Range[“B1″].Style.Font.IsBold = true;
            //Set Horizontal Alignment
            sheet.Range[“B3″].Text = “Top”;
            sheet.Range[“B3″].Style.VerticalAlignment =VerticalAlignType.Top;
            sheet.Range[“C3″].Text = “Center”;
            sheet.Range[“C3″].Style.VerticalAlignment =VerticalAlignType.Center;
            sheet.Range[“D3″].Text = “Bottom”;
            sheet.Range[“D3″].Style.VerticalAlignment =VerticalAlignType.Bottom;
            //Set Default Alignment
            sheet.Range[“B5″].Text = “General”;
            sheet.Range[“B5″].Style.Font.FontName = “Calibri”;
            sheet.Range[“B5″].Style.Font.Size = 12;
            sheet.Range[“B5″].Style.Color = Color.LightSkyBlue;
            sheet.Range[“B5″].Style.HorizontalAlignment =HorizontalAlignType.General;
            //Set Vertical Alignment
            sheet.Range[“B7″].Text = “Left”;
            sheet.Range[“B7″].Style.HorizontalAlignment =HorizontalAlignType.Left;
            sheet.Range[“C7″].Text = “Center”;
            sheet.Range[“C7″].Style.HorizontalAlignment =HorizontalAlignType.Center;
            sheet.Range[“D7″].Text = “Right”;
            sheet.Range[“D7″].Style.HorizontalAlignment =HorizontalAlignType.Right;
            //Set Orientation Alignment
            sheet.Range[“B9″].Text = “Rotation 90 degree”;
            sheet.Range[“B9″].Style.Rotation = 90;
            sheet.Range[“C9″].Text = “Rotation 45 degree”;
            sheet.Range[“C9″].Style.Rotation = 45;
            //Set Vertical Alignment Format
            sheet.Range[“B3:D3″].Style.Font.FontName = “Calibri”;
            sheet.Range[“B3:D3″].Style.Font.Size = 12;
            sheet.Range[“B3:D3″].Style.Color  = Color.LightYellow;
            sheet.Range[“B3:D3″].Borders.LineStyle = LineStyleType.Thin;
            sheet.Range[“B3:D3″].Borders.Color = Color.DarkBlue;
           sheet.Range[“B3:D3″].Borders[BordersLineType.DiagonalDown].LineStyle =LineStyleType.None;
            sheet.Range[“B3:D3″].Borders[BordersLineType.DiagonalUp].LineStyle = LineStyleType.None;
            //Set Horizontal Alignment Format
            sheet.Range[“B7:D7″].Style.Font.FontName = “Calibri”;
            sheet.Range[“B7:D7″].Style.Font.Size = 12;
            sheet.Range[“B7:D7″].Style.Color = Color.LightYellow;
            sheet.Range[“B7:D7″].Borders.LineStyle = LineStyleType.Thin;
            sheet.Range[“B7:D7″].Borders.Color = Color.DarkBlue;
           sheet.Range[“B7:D7″].Borders[BordersLineType.DiagonalDown].LineStyle =LineStyleType.None;
            sheet.Range[“B7:D7″].Borders[BordersLineType.DiagonalUp].LineStyle = LineStyleType.None;
            //Set Orientation Alignment Format
            sheet.Range[“B9:C9″].Style.Font.FontName = “Calibri”;
            sheet.Range[“B9:C9″].Style.Font.Size = 13;
            sheet.Range[“B9:C9″].Style.Font.IsBold = true;
            sheet.Range[“B9:C9″].Style.Font.Color = Color.LimeGreen;
            //Set Column Width and Row Height
            sheet.AllocatedRange.AutoFitColumns();
            sheet.Range[“B3:D3″].RowHeight = 20;
            sheet.Range[“B7:D7″].RowHeight = 20;
            //Save and Launch File
            workbook.SaveToFile(Alignment.xlsxExcelVersion.Version2010);
            System.Diagnostics.Process.Start(workbook.FileName);
        }
    }
}
After running, we can get the following result:

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...