tbf/TestBenchFramework/BenchControl/ResultsWriters/Basic/Writer.cs
2015-02-02 18:10:52 +01:00

368 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using log4net;
using TBF.BenchControl;
using TBF.Resources;
namespace TBF.BenchControl.ResultsWriters.Basic
{
public class Writer : ComponentBase, IOperation, GenericDevices.IResultsWriter
{
private static readonly ILog log = LogManager.GetLogger(typeof(Writer));
public override string ToString() { return string.Format("ResultsWriters.Basic({0})", Cfg.ToString(1)); }
readonly WriterCfg writerCfg;
/// <summary>
/// Result items to print
/// </summary>
IList<TBF.Forms.ResultItemSpec> resultItems;
bool combined;
/// <summary>
/// Results to print
/// </summary>
Entities.Procedure procedure;
IList<Entities.TestResult> unsortedResults;
DateTime dateTime;
StreamWriter writer;
public Writer(WriterCfg cfg)
: base(cfg)
{
writerCfg = cfg;
log.Debug(this.ToString());
}
/// <summary>
/// Returns a file name derived from a DateTime structure.
/// Creates directories on this path as a side effect.
/// </summary>
/// <param name="time">Date and time</param>
/// <returns>File name</returns>
string GetFilename(DateTime time)
{
Directory.CreateDirectory(writerCfg.DestinationPath);
string directory = string.Format("{0}{1}\\", writerCfg.DestinationPath, time.Year.ToString());
Directory.CreateDirectory(directory);
string monthStr /* = now.Month.ToString("D2")*/;
switch (time.Month)
{
default:
case 1: monthStr = "January"; break;
case 2: monthStr = "February"; break;
case 3: monthStr = "March"; break;
case 4: monthStr = "April"; break;
case 5: monthStr = "May"; break;
case 6: monthStr = "June"; break;
case 7: monthStr = "July"; break;
case 8: monthStr = "August"; break;
case 9: monthStr = "September"; break;
case 10: monthStr = "October"; break;
case 11: monthStr = "November"; break;
case 12: monthStr = "December"; break;
}
directory = string.Format("{0}{1}\\", directory, monthStr);
Directory.CreateDirectory(directory);
if (writerCfg.DayFolders)
{
directory = string.Format("{0}{1}\\", directory, time.Day.ToString("D2"));
Directory.CreateDirectory(directory);
}
return string.Format("{0}{1}{2}{3}-{4}{5}.txt", directory, (time.Year % 100).ToString("D2"),
time.Month.ToString("D2"), time.Day.ToString("D2"), time.Hour.ToString("D2"), time.Minute.ToString("D2"));
}
/// <summary>
/// Writes the test cycle results into a file, Events: Event.ResultsWritten
/// </summary>
/// <param name="procedure">Procedure to print the results of</param>
/// <param name="unsortedResults">Results to write into the file</param>
/// <returns>Reference to the operation</returns>
public IOperation WriteResultsOp(Entities.Procedure procedure, IList<Entities.TestResult> unsortedResults)
{
if ((procedure == null) || (unsortedResults == null) || (unsortedResults.Count < 1))
{
return null;
}
this.procedure = procedure;
this.unsortedResults = unsortedResults;
combined = (procedure.MetersKind == Entities.MetersKind.Combined);
if (combined)
{
resultItems = Forms.ResultItemSpec.FromStrArray(Program.LocalSettings.RsltItems_Disk_CombinedWM);
}
else
{
resultItems = Forms.ResultItemSpec.FromStrArray(Program.LocalSettings.RsltItems_Disk_SingleWM);
}
try
{
dateTime = DateTime.Now;
writer = new StreamWriter(System.IO.File.Create(GetFilename(dateTime)));
}
catch
{
writer = null;
}
return this;
}
/// <summary>Start this operation</summary>
public void Start()
{
if (writer == null) return;
///----------
/// Header
///----------
writer.WriteLine(unsortedResults[0].ProtocolTitle);
writer.WriteLine(string.Empty);
string[] leftColumn = new string[]
{
"Cycle number: ",
"Date and time: ",
"Procedure:",
Strings.User_,
"Ambient temperature: ",
"Ambient pressure: ",
"Ambient humidity: ",
};
string[] rightColumn = new string[]
{
unsortedResults[0].BatchNr.ToString(),
//dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(),
string.Format("{0}.{1}.{2} {3}:{4}", dateTime.Year.ToString("D4"),
dateTime.Month.ToString("D2"),
dateTime.Day.ToString("D2"),
dateTime.Hour.ToString("D2"),
dateTime.Minute.ToString("D2")),
procedure.Name,
Entities.User.CurrentUser.Name,
unsortedResults[0].AmbientTempAve.ToString("F1") + " °C",
unsortedResults[0].AmbientPressAve.ToString("F0") + " mbar",
unsortedResults[0].AmbientHumiAve.ToString("F0") + " %",
};
/// Determine max. left column width in characters
int maxLen = 0;
foreach (var s in leftColumn) if (s.Length > maxLen) maxLen = s.Length;
/// Write aligned columns
for (int i = 0; i < Math.Min(leftColumn.Length, rightColumn.Length); i++)
{
writer.Write(leftColumn[i]);
writer.Write(new string(' ', maxLen - leftColumn[i].Length + 3));
writer.WriteLine(rightColumn[i]);
}
writer.WriteLine(string.Empty);
///--------
/// Body
///--------
int nrWMs = (combined ? Program.WMsCount / 2 : Program.WMsCount);
if (combined)
{
for (int wmNr = 1; wmNr <= Program.WMsCount / 2; wmNr++) WriteCombinedWM(wmNr); /// wmNr is 1-based
}
else
{
for (int wmNr = 1; wmNr <= Program.WMsCount; wmNr++) WriteSingleWM(wmNr); /// wmNr is 1-based
}
}
/// <summary>
/// Write one water meter results
/// </summary>
/// <param name="wmNr1">Water meter number (1-based)</param>
void WriteSingleWM(int wmNr1)
{
IList<Entities.TestResult> results = Utils.GetSortedTestResults(procedure, unsortedResults, wmNr1);
/// Determine column widths
int[] columnWidths = new int[resultItems.Count];
int totalWidth = 0;
for (int i = 0; i < resultItems.Count; i++)
{
columnWidths[i] = resultItems[i].ClmnHeaderText.Length;
foreach (var tr in results)
{
if (tr != null)
{
int len = resultItems[i].Print(tr.Meters[wmNr1 - 1]).Length;
if (len > columnWidths[i]) columnWidths[i] = len;
}
}
totalWidth += columnWidths[i];
}
totalWidth += 3 * (resultItems.Count - 1);
/// Write water meter number and s/n
writer.Write(string.Format("Water meter {0}", wmNr1));
if (!string.IsNullOrEmpty(unsortedResults[0].Meters[wmNr1 - 1].SerialNr))
{
writer.Write(string.Format(" s/n: {0}", unsortedResults[0].Meters[wmNr1 - 1].SerialNr));
}
writer.WriteLine(string.Empty);
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line above the header
/// Write column headers
for (int i = 0; i < resultItems.Count; i++)
{
writer.Write(resultItems[i].ClmnHeaderText);
if (i < resultItems.Count - 1)
writer.Write(new string(' ', columnWidths[i] - resultItems[i].ClmnHeaderText.Length + 3));
else
writer.WriteLine(string.Empty);
}
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line between the header and the body
/// Write table data
foreach (var tr in results)
{
if (tr != null)
{
for (int i = 0; i < resultItems.Count; i++)
{
string text = resultItems[i].Print(tr.Meters[wmNr1 - 1]);
/// Get rid of the color information
string[] texts = text.Split(new char[] { '|' });
if (texts.Length == 2) { text = texts[0]; }
writer.Write(text);
if (i < resultItems.Count - 1)
writer.Write(new string(' ', columnWidths[i] - text.Length + 3));
else
writer.WriteLine(string.Empty);
}
}
}
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line below the body
writer.WriteLine(string.Empty);
}
/// <summary>
/// Write one combined water meter results
/// </summary>
/// <param name="wmNr1">Combined water meter number (1-based)</param>
void WriteCombinedWM(int wmNr1)
{
IList<Entities.TestResult> results = Utils.GetSortedTestResults(procedure, unsortedResults, wmNr1);
/// Determin column widths
int[] columnWidths = new int[resultItems.Count];
int totalWidth = 0;
for (int i = 0; i < resultItems.Count; i++)
{
columnWidths[i] = resultItems[i].ClmnHeaderText.Length;
foreach (var tr in results)
{
if (tr != null)
{
int len = resultItems[i].PrintCombined(tr.Meters[2 * wmNr1 - 2], tr.Meters[2 * wmNr1 - 1], tr.CombinedMeters[wmNr1 - 1]).Length;
if (len > columnWidths[i]) columnWidths[i] = len;
}
}
totalWidth += columnWidths[i];
}
totalWidth += 3 * (resultItems.Count - 1);
/// Write water meter number and two s/n-s
writer.Write(string.Format("Water meter {0}", wmNr1));
if (!string.IsNullOrEmpty(unsortedResults[0].Meters[2 * wmNr1 - 2].SerialNr))
{
writer.Write(string.Format(", Main s/n: {0}", unsortedResults[0].Meters[2 * wmNr1 - 2].SerialNr));
}
if (!string.IsNullOrEmpty(unsortedResults[0].Meters[2 * wmNr1 - 1].SerialNr))
{
writer.Write(string.Format(", Aux. s/n:{0}", unsortedResults[0].Meters[2 * wmNr1 - 1].SerialNr));
}
writer.WriteLine(string.Empty);
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line above the header
for (int i = 0; i < resultItems.Count; i++)
{
writer.Write(resultItems[i].ClmnHeaderText);
if (i < resultItems.Count - 1)
writer.Write(new string(' ', columnWidths[i] - resultItems[i].ClmnHeaderText.Length + 3));
else
writer.WriteLine(string.Empty);
}
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line between the header and the body
foreach (var tr in results)
{
if (tr != null)
{
for (int i = 0; i < resultItems.Count; i++)
{
string text = resultItems[i].PrintCombined(tr.Meters[2 * wmNr1 - 2], tr.Meters[2 * wmNr1 - 1], tr.CombinedMeters[wmNr1 - 1]);
/// Get rid of the color information
string[] texts = text.Split(new char[] { '|' });
if (texts.Length == 2) { text = texts[0]; }
writer.Write(text);
if (i < resultItems.Count - 1)
writer.Write(new string(' ', columnWidths[i] - text.Length + 3));
else
writer.WriteLine(string.Empty);
}
}
}
writer.WriteLine(new String('-', totalWidth)); /// Horizontal line below the body
writer.WriteLine(string.Empty);
}
/// <summary>Run this operation</summary>
/// <returns>Event.ResultsWritten</returns>
public Event Run()
{
return Event.ResultsWritten;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
if (writer != null) writer.Close();
writer = null;
}
}
}