using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Eugen.ESystem.IO
{
///
/// Handles a log file
///
[Description("Handles a log file")]
public class LogWriter : Component
{
#region Version und Copyright
// Version und Copyright
static string dllName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //Den Programmnamen auslesen
static string dllVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
static object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
static string copyright = GenerateCopyright();
//Assembly Datum und Zeit
static DateTime value = AssemblyDateTime();
static string date = value.ToShortDateString();
static string time = value.ToLongTimeString();
private static DateTime AssemblyDateTime()
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision));
//Tage seit dem 1. Januar 2000 und Sekunden seit Mitternacht, (multiplizier mit 2 ergibt das Original)
return buildDateTime;
}
private static string CurrentYear()
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
private static string StartYear()
{
string startYear = "";
if (((AssemblyCopyrightAttribute)attributes[0]).Copyright.Contains("Copyright © "))
{
startYear = ((AssemblyCopyrightAttribute)attributes[0]).Copyright.Replace("Copyright © ", "");
while (startYear.StartsWith(" "))
{
startYear = startYear.Remove(0, 1);
}
if (startYear.Contains("-"))
{
startYear = startYear.Remove(startYear.IndexOf("-"));
}
else
{
startYear = startYear.Remove(startYear.IndexOf(" "));
}
return startYear;
}
else
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
}
private static string GenerateCopyright()
{
string startYear = StartYear();
string currentYear = CurrentYear();
if (startYear == currentYear)
{
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
else
{
string temp = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
string start = temp.Remove(temp.IndexOf(startYear) - 1);
string end = (temp.Remove(0, temp.IndexOf(" by")));
return String.Concat(start, " ", startYear, "-", currentYear, end);
}
}
#endregion
#region DLL-Info
///
/// Contains the name of the dll file.
///
public static string DllName { private set; get; }
///
/// Contains the version of the dll file.
///
public static string DllVersion { private set; get; }
///
/// Contains the copyright notice.
///
public static string Copyright { private set; get; }
///
/// Contains the name-, version- and copyright-information of the dll file.
///
public static string[] DllInfo { private set; get; }
private static void SetDllInfo()
{
//Name, Version und Copyright setzen
DllName = dllName;
DllVersion = dllVersion;
Copyright = copyright;
string[] dllInfo = new string[3];
dllInfo[0] = dllName;
dllInfo[1] = dllVersion;
dllInfo[2] = copyright;
DllInfo = dllInfo;
}
protected string ProgramName { private set; get; }
protected string ProgramVersion { private set; get; }
protected string ProgramCopyright { private set; get; }
#endregion
#region delegates
///
/// Provides a method, wich handles events from written messages
///
/// Sender object
/// Event arguments
[Description("Provides a method, wich handles events from written messages")]
public delegate void LogWriterEventHandler(object sender, LogWriterEventArgs e);
#endregion
#region fields
///
/// Stores the log save path
///
private string path = String.Empty;
///
/// Stores the logfile name
///
private string filename = String.Empty;
///
/// Stores the log header
///
private string logheader = String.Empty;
///
/// Stores the file name format
///
private string fileFormat = "log_{0:d}.log";
///
/// Stores the message format
///
private string messageFormat = "{0:T}.{1} - {2}";
#endregion
#region events
///
/// Fired, when a message was written
///
[Description("Fired, when a message was written")]
public event LogWriterEventHandler MessageWritten;
///
/// Fired, when a new log file was created. Fired, when a message was written
///
[Description("Fired, when a new log file was created. Fired, when a message was written")]
public event EventHandler FileCreated;
#endregion
#region properties
///
/// Specifyes the log save path
///
[Description("Specifyes the log save path")]
public string Path
{
get
{
return this.path;
}
set
{
this.path = value;
}
}
///
/// Specifyes the file name format
///
[Description("Specifyes the file name format")]
[DefaultValue("log_{0:d}.log")]
public string FileFormat
{
get
{
return this.fileFormat;
}
set
{
this.fileFormat = value;
}
}
///
/// Specifyes the message format
///
[Description("Specifyes the message format")]
[DefaultValue("{0:t}: {1}")]
public string MessageFormat
{
get
{
return this.messageFormat;
}
set
{
this.messageFormat = value;
}
}
#endregion
#region constructor
///
/// Constructor (for DLL-Information)
///
static LogWriter()
{
SetDllInfo();
}
///
/// Constructor
///
public LogWriter()
{
}
///
/// Constructor (Filename = 'log_dd.mm.yyyy.log)
///
/// Specifyes the log save path
public LogWriter(string path)
{
this.path = path;
}
///
/// Constructor (Filename = self defined)
///
/// Specifyes the log save path
/// Specifyes the log file name
public LogWriter(string path, string filename)
{
this.path = path;
this.filename = filename;
if (this.filename.EndsWith(".log"))
{
this.filename.Replace(".log", "");
}
}
///
/// Constructor (Filename = self defined, with fileheader)
///
///
///
///
public LogWriter(string path, string filename, string logheader)
{
this.path = path;
this.filename = filename;
if (this.filename.EndsWith(".log"))
{
this.filename.Replace(".log", "");
}
this.logheader = logheader;
}
#endregion
#region public members
///
/// Writes a message
///
/// Specifyes the message to be written
/// Wheather the writing progress was successful
public bool WriteMessage(string message)
{
// if directory not exists, cancel
if (!Directory.Exists(this.path))
throw new DirectoryNotFoundException(AppResources.msg001);
// holds the actual date and time
DateTime time = DateTime.Now;
int ms = time.Millisecond;
// creates the file name
string fileName;
if (String.IsNullOrEmpty(this.filename))
{
if (String.IsNullOrEmpty(this.path))
{
fileName = System.IO.Path.DirectorySeparatorChar.ToString();
}
else
{
fileName = this.path;
if (fileName[fileName.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
fileName += System.IO.Path.DirectorySeparatorChar;
}
}
try
{
fileName += String.Format(this.fileFormat, time);
}
catch (FormatException)
{
throw new FormatException(AppResources.msg002);
}
catch
{
return false;
}
}
else
{
if (this.path[this.path.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.filename)))
{
fileName = String.Concat(path, System.IO.Path.DirectorySeparatorChar, this.filename, ".log");
}
else
{
fileName = String.Concat(path, System.IO.Path.DirectorySeparatorChar, this.filename);
}
}
else
{
if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.filename)))
{
fileName = String.Concat(this.path, this.filename, ".log");
}
else
{
fileName = String.Concat(this.path, this.filename);
}
}
}
// build message line
string line;
try
{
// creates the line
line = String.Format(this.messageFormat, new object[] { time, ms, message });
}
catch (FormatException)
{
throw new FormatException(AppResources.msg002);
}
catch
{
return false;
}
try
{
StreamWriter writer;
// if a log header is to be written
if (!String.IsNullOrEmpty(logheader) && IsFileEmpty(fileName))
{
// write log header
// open file
if (!File.Exists(fileName))
{
writer = new StreamWriter(fileName);
OnFileCreated(EventArgs.Empty);
}
else
writer = new StreamWriter(fileName);
// write message line
writer.WriteLine(this.logheader);
// close file
writer.Close();
}
// open file
if (!File.Exists(fileName))
{
writer = new StreamWriter(fileName);
OnFileCreated(EventArgs.Empty);
}
else
writer = new StreamWriter(fileName, true);
// write message line
writer.WriteLine(line);
// close file
writer.Close();
OnMessageWritten(new LogWriterEventArgs(time, ms, message));
return true;
}
catch
{
return false;
}
}
private bool IsFileEmpty(string filename)
{
if (File.Exists(filename))
{
System.IO.StreamReader file = new System.IO.StreamReader(filename);
if (String.IsNullOrEmpty(file.ReadLine()))
{
file.Close();
return true; // file is empty
}
else
{
file.Close();
return false; // file is not empty
}
}
else
{
return true; // file doesn't exist - is empty
}
}
#endregion
#region protected members
///
/// Fires the MessageWritten event
///
///
protected void OnMessageWritten(LogWriterEventArgs e)
{
if (MessageWritten != null)
MessageWritten(this, e);
}
///
/// Fires the FileCreated event
///
///
protected void OnFileCreated(EventArgs e)
{
if (FileCreated != null)
FileCreated(this, e);
}
#endregion
}
#region LogWriterEventArgs class
///
/// LogWriterEventArgs stores information about the sent log message
///
public class LogWriterEventArgs : EventArgs
{
#region fields
///
/// Stores the message post time
///
private DateTime time;
///
/// Stores the milliseconds of the post time of the message
///
private int millisecond;
///
/// Stores the message
///
private string message;
#endregion
#region properties
///
/// Specifyes the message post time
///
[Description("Specifyes the message post time")]
public DateTime Time
{
get
{
return this.time;
}
}
///
/// Specifyes the message
///
[Description("Specifyes the message")]
public string Message
{
get
{
return this.message;
}
}
#endregion
#region constructor
///
/// Constructor
///
/// Specifyes the message post time
/// Specifyes the message
public LogWriterEventArgs(DateTime time, int millisecond, string message)
: base()
{
this.time = time;
this.millisecond = millisecond;
this.message = message;
}
#endregion
}
#endregion
}