/// /// Copyright (c) 2013-2015 Sensus Metering Systems /// using System; using System.Collections.Generic; using System.IO; using log4net; using Config.Entities; 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; /// /// Result items to print /// IList resultItems; bool combined; /// /// Results to print /// Procedure procedure; IList unsortedResults; DateTime dateTime; StreamWriter writer; string separatorStr; public Writer() { } public Writer(WriterCfg cfg) : base(cfg) { writerCfg = cfg; switch (cfg.Separator) { default: case Separator.None: separatorStr = string.Empty; break; case Separator.Space: separatorStr = " "; break; case Separator.Tabulator: separatorStr = "\t"; break; case Separator.Comma: separatorStr = ","; break; case Separator.Semicolon: separatorStr = ";"; break; } log.Debug(this.ToString()); } /// /// Eliminate spaces conditionally, depesing on bool WriterCfg.EliminateSpaces /// /// Input string /// Output string string ElSpaces(string item) { if (writerCfg.EliminateSpaces) return item.Replace(" ", string.Empty); else return item; } /// /// Returns a file name derived from a DateTime structure. /// Creates directories on this path as a side effect. /// /// Date and time /// File name string GetFilename(DateTime time) { string directory = writerCfg.DestinationPath; /// Ends with "\\"; Directory.CreateDirectory(directory); if (writerCfg.YearFolders) { directory = string.Format("{0}{1}\\", directory, time.Year.ToString()); Directory.CreateDirectory(directory); } if (writerCfg.MonthFolders) { 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")); } /// /// Writes the test cycle results into a file, Events: Event.ResultsWritten /// /// Procedure to print the results of /// Results to write into the file /// Reference to the operation public IOperation WriteResultsOp(Procedure procedure, IList waterMeters, IList unsortedResults) { if ((procedure == null) || (unsortedResults == null) || (unsortedResults.Count < 1)) { return null; } this.procedure = procedure; this.unsortedResults = unsortedResults; combined = (procedure.MetersKind == MetersKind.Combined); if (combined) { resultItems = Config.ResultItemSpec.FromStrArray(Program.LocalSettings.RsltItems_Disk_CombinedWM); } else { resultItems = Config.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; } /// Start this operation public void Start() { if (writer == null) return; ///---------- /// Header ///---------- writer.WriteLine(unsortedResults[0].ProtocolTitle); writer.WriteLine(string.Empty); string[] leftColumn = new string[] { "Batch 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, 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 ///-------- if (combined) { for (int wmNr = 0; wmNr < Config.Data.CompoundWMsCount; wmNr++) WriteCombinedWM(wmNr + 1); /// wmNr is 0-based } else { for (int wmNr = 0; wmNr < Config.Data.WMsCount; wmNr++) /// wmNr is 0-based { if (!unsortedResults[0].Meters[wmNr].Disabled) WriteSingleWM(wmNr, wmNr + 1); } } } /// /// Write one water meter results /// /// Water meter number (0-based) void WriteSingleWM(int wmNr, int printedWMNr) { IList results = Utils.GetSortedTestResults(procedure, unsortedResults, Utils.PartNr(wmNr + 1, combined)); /// Determine column widths int[] columnWidths = new int[resultItems.Count]; int totalWidth = 0; for (int i = 0; i < resultItems.Count; i++) { columnWidths[i] = ElSpaces(resultItems[i].ClmnHeaderText).Length; foreach (var tr in results) { if (tr != null) { string text = resultItems[i].Print(tr.Meters[wmNr]); /// Get rid of the color information string[] texts = text.Split(new char[] { '|' }); if (texts.Length == 2) { text = texts[0]; } int len = ElSpaces(text).Length; if (len > columnWidths[i]) columnWidths[i] = len; } } totalWidth += columnWidths[i]; } totalWidth += 3 * (resultItems.Count - 1); if (totalWidth < 0) totalWidth = 0; /// Write water meter number and s/n writer.Write(string.Format("Water meter {0}", printedWMNr)); if (!string.IsNullOrEmpty(unsortedResults[0].Meters[wmNr].SerialNr)) { writer.Write(string.Format(" s/n: {0}", unsortedResults[0].Meters[wmNr].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(ElSpaces(resultItems[i].ClmnHeaderText)); if (i < resultItems.Count - 1) { if (!writerCfg.EliminateSpaces) { writer.Write(new string(' ', columnWidths[i] - resultItems[i].ClmnHeaderText.Length + 3)); } writer.Write(separatorStr); } 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[wmNr]); /// Get rid of the color information string[] texts = text.Split(new char[] { '|' }); if (texts.Length == 2) { text = texts[0]; } writer.Write(ElSpaces(text)); if (i < resultItems.Count - 1) { if (!writerCfg.EliminateSpaces) { writer.Write(new string(' ', columnWidths[i] - text.Length + 3)); } writer.Write(separatorStr); } else { writer.WriteLine(string.Empty); } } } } writer.WriteLine(new String('-', totalWidth)); /// Horizontal line below the body writer.WriteLine(string.Empty); } /// /// Write one combined water meter results /// /// Combined water meter number (1-based) void WriteCombinedWM(int wmNr1) { IList results = Utils.GetSortedTestResults(procedure, unsortedResults, Utils.PartNr(wmNr1, combined)); /// Determin column widths int[] columnWidths = new int[resultItems.Count]; int totalWidth = 0; for (int i = 0; i < resultItems.Count; i++) { columnWidths[i] = ElSpaces(resultItems[i].ClmnHeaderText).Length; foreach (var tr in results) { if (tr != null) { string text = resultItems[i].PrintCombined(tr.Meters[2 * wmNr1 - 2], tr.Meters[2 * wmNr1 - 1], tr.CombinedMeters[wmNr1 - 1]); int len = ElSpaces(text).Length; if (len > columnWidths[i]) columnWidths[i] = len; } } totalWidth += columnWidths[i]; } totalWidth += 3 * (resultItems.Count - 1); if (totalWidth < 0) totalWidth = 0; /// 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(ElSpaces(resultItems[i].ClmnHeaderText)); if (i < resultItems.Count - 1) { if (!writerCfg.EliminateSpaces) { writer.Write(new string(' ', columnWidths[i] - resultItems[i].ClmnHeaderText.Length + 3)); } writer.Write(separatorStr); } 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(ElSpaces(text)); if (i < resultItems.Count - 1) { if (!writerCfg.EliminateSpaces) { writer.Write(new string(' ', columnWidths[i] - text.Length + 3)); } writer.Write(separatorStr); } else { writer.WriteLine(string.Empty); } } } } writer.WriteLine(new String('-', totalWidth)); /// Horizontal line below the body writer.WriteLine(string.Empty); } /// Run this operation /// Event.ResultsWritten public Event Run() { return Event.ResultsWritten; } /// Stop this operation public void Stop() { if (writer != null) writer.Close(); writer = null; } } }