1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;
using Tango.Core.Commands;
using Tango.CSV;
using Tango.DispenserAnalyzer.UI.Models;
using Tango.SharedUI;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Tango.DispenserAnalyzer.UI.Analysis;
using System.Windows;
using System.Windows.Threading;
using OxyPlot;
using OxyPlot.Wpf;
using OxyPlot.Annotations;
using System.Windows.Media;
using System.Diagnostics;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Media.Imaging;
using PdfSharp;
using OxyPlot.Reporting;
using Tango.Documents;
using Tango.DispenserAnalyzer.UI.View;
using Tango.Core.Helpers;
using Tango.DispenserAnalyzer.UI.ExcelModel;
using Tango.DispenserAnalyzer.UI.Analyzers;
using static Tango.DispenserAnalyzer.UI.Analyzers.FlowAnalyser;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Globalization;
namespace Tango.DispenserAnalyzer.UI.ViewModels
{
public class MainWindowVM: ViewModel
{
private const string FILE_EXTENSION = ".pdf";
private string _settingsFilepath = "";
#region Properties
public Plot PlotControl { get; set; }
/// <summary>
/// Gets or sets the results panel. Using to save all results in xps file
/// </summary>
public System.Windows.Controls.ItemsControl ResultsPanel { get; set; }
private string _openFilePath;
public string OpenFilePath
{
get { return _openFilePath; }
set
{
if(value != null && _openFilePath != value)
{
_openFilePath = value;
OnSelectedFileChanged();
RaisePropertyChangedAuto();
GenerateCommand.RaiseCanExecuteChanged();
}
}
}
private string _filename;
public string FileName
{
get { return _filename; }
set { _filename = value;
RaisePropertyChangedAuto();
RaisePropertyChanged("ButtonName"); }
}
public string ButtonName {
get { return "Generate result for " + FileName; }
}
private string _testName = "";
public string TestName
{
get { return _testName.ToUpper() + " TEST"; }
set { _testName = value; RaisePropertyChangedAuto(); }
}
private IList<DataPoint> _points;
/// <summary>
/// Binding to ItemsSource of line chart.
/// </summary>
public IList<DataPoint> Points
{
get { return _points; }
set
{
_points = value;
RaisePropertyChangedAuto();
}
}
private int _step;
public int XStep
{
get { return _step; }
set { _step = value; RaisePropertyChangedAuto(); }
}
private double _from;
/// <summary>
/// From use to binding to bottom axis min value
/// </summary>
public double From
{
get { return _from; }
set
{
_from = value; RaisePropertyChangedAuto();
}
}
private double _to;
/// <summary>
/// To use to binding to bottom axis max value
/// </summary>
public double To
{
get { return _to; }
set
{
_to = value; RaisePropertyChangedAuto();
}
}
private string _titleAxisBottom;
public string TitleAxisBottom
{
get { return _titleAxisBottom; }
set { _titleAxisBottom = value; RaisePropertyChangedAuto(); }
}
private string _titleAxisLeft;
public string TitleAxisLeft
{
get { return _titleAxisLeft; }
set { _titleAxisLeft = value; RaisePropertyChangedAuto(); }
}
private bool _isRunning;
/// <summary>
/// Gets or sets a value indicating whether this instance is running.
/// </summary>
public bool IsRunning
{
get { return _isRunning; }
set { _isRunning = value; RaisePropertyChangedAuto(); }
}
private ObservableCollection<IAnalyzerResult> _analyzerResults;
public ObservableCollection<IAnalyzerResult> AnalyzerResults
{
get { return _analyzerResults; }
set { _analyzerResults = value; RaisePropertyChangedAuto(); }
}
public Func<double, string> YFormatter { get; set; }
private Visibility _isCompareVisible;
public Visibility IsCompareVisible
{
get { return _isCompareVisible; }
set { _isCompareVisible = value;
RaisePropertyChangedAuto();
}
}
private bool _addToComare;
public bool AddToComare
{
get { return _addToComare; }
set { _addToComare = value;
OnAddToCompareResults(value);
RaisePropertyChangedAuto();
}
}
private string _compareResText1;
public string CompareResText1
{
get {
if (String.IsNullOrEmpty(_compareResText1))
return "Empty";
return _compareResText1;
}
set {
_compareResText1 = value;
RaisePropertyChangedAuto();
}
}
private string _compareResText2;
public string CompareResText2
{
get {
if (String.IsNullOrEmpty(_compareResText2))
return "Empty";
return _compareResText2; }
set { _compareResText2 = value;
RaisePropertyChangedAuto();
}
}
private bool _isAddedRes1;
public bool IsAddedRes1
{
get { return _isAddedRes1; }
set { _isAddedRes1 = value;
RaisePropertyChangedAuto();
}
}
private bool _isAddedRes2;
public bool IsAddedRes2
{
get { return _isAddedRes2; }
set { _isAddedRes2 = value;
RaisePropertyChangedAuto();
}
}
private ObservableCollection<CompareResultModel> _resultsToCompare;
public ObservableCollection<CompareResultModel> ResultsToCompare
{
get { return _resultsToCompare; }
set { _resultsToCompare = value; }
}
#endregion
#region Commands
public RelayCommand OpenCSVFileCommand { get; set; }
public RelayCommand GenerateCommand { get; set; }
public RelayCommand OpenSettingWndCommand { get; set; }
public RelayCommand CompareCommand { get; set; }
public RelayCommand SaveExelCommand { get; set; }
#endregion
public MainWindowVM()
{
ResultsToCompare = new ObservableCollection<CompareResultModel>();
OpenCSVFileCommand = new RelayCommand(OpenCSVFile);
GenerateCommand = new RelayCommand(Generate, CanGenerate);
OpenSettingWndCommand = new RelayCommand(OpenSettingWnd);
CompareCommand = new RelayCommand(Compareresults, CanCompareresults);
SaveExelCommand = new RelayCommand(SaveExel, CanSaveExel);
YFormatter = value => value.ToString();
_from = 0;
_to = 1;
XStep = 1;
AnalyzerResults = new ObservableCollection<IAnalyzerResult>();
_isRunning = false;
TitleAxisBottom = "";
TitleAxisLeft = "";
this.Points = new List<DataPoint>();
IsCompareVisible = Visibility.Collapsed;
IsAddedRes1 = IsAddedRes2 = false;
InitUserSettings();
}
#region Settings
public void InitUserSettings()
{
string folderPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DispenserAnalyzer");
Directory.CreateDirectory(folderPath);
_settingsFilepath = System.IO.Path.Combine(folderPath, "Settings.json");
try
{
Settings.DeserializeSettings(_settingsFilepath);
}
catch (IOException ex)
{
MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
public void OpenSettingWnd()
{
SettingsWnd settings = new SettingsWnd();
settings.Owner = System.Windows.Application.Current.MainWindow;
if(true == settings.ShowDialog())
{
Dictionary<AnalyzerSettingsEnum, object> changes = settings.GetChanges();
foreach (KeyValuePair<AnalyzerSettingsEnum, object> entry in changes)
{
Settings.SetValueByName(entry.Key, entry.Value);
}
try
{
Settings.SerializeSettings(_settingsFilepath);
}
catch (IOException ex)
{
MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
private void ClearResults()
{
IsCompareVisible = Visibility.Collapsed;
_addToComare = false;
RaisePropertyChanged("AddToComare");
Points.Clear();
AnalyzerResults.Clear();
TestName = "";
foreach (var ax in PlotControl.Axes)
{
ax.Maximum = ax.Minimum = Double.NaN;
PlotControl.ResetAllAxes();
}
PlotControl.Annotations.Clear();
PlotControl.InvalidatePlot(true);
}
#endregion
#region Read File
private void OpenCSVFile()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "CSV Files|*.csv";
if (dlg.ShowDialog().Value)
{
try
{
OpenFilePath = dlg.FileName;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while trying to import the CSV file. " + ex.Message,
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
}
}
protected virtual bool IsFileLocked(string filePath)
{
FileStream stream = null;
try
{
stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException ex)
{
MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
private void OnSelectedFileChanged()
{
ClearResults();
if(File.Exists(OpenFilePath))
{
FileHelper.OpenFilePath = OpenFilePath;
FileName = Path.GetFileName(OpenFilePath);
}
SaveExelCommand.RaiseCanExecuteChanged();
}
#endregion
#region Generate
public bool CanGenerate()
{
var value = (OpenFilePath != null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath));
return (OpenFilePath!= null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath));
}
/// <summary>
/// Generates all results.
/// </summary>
public async void Generate()
{
if (false == File.Exists(OpenFilePath) || IsFileLocked(OpenFilePath))
return;
ClearResults();
var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
if (analyzer == null)
return;
IsRunning = true;
AnalyzerAttribute[] attr = analyzer.GetType().GetCustomAttributes(typeof(AnalyzerAttribute), true);
if (attr != null && attr.Count() > 0)
{
TestName = attr[0].Name;
}
List<OxyPlot.Wpf.LineAnnotation> annotations = new List<OxyPlot.Wpf.LineAnnotation>();
var samples = analyzer.Reader.ReadScvFile(OpenFilePath, annotations);
bool showChartAfterProcess = analyzer.ShowChartAfterProcess;
if (false == showChartAfterProcess)
{
analyzer.GetPoints(samples, Points);
if (Points.Count == 0)
{
IsRunning = false;
return;
}
}
//visible only for process type
IsCompareVisible = analyzer.AvailableCompareResults ? Visibility.Visible : Visibility.Collapsed;
annotations.ForEach(x => PlotControl.Annotations.Add(x));
To = 0;
From = 0;
List<IAnalyzerResult> res = await analyzer.Process(samples, false);
AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res);
if (showChartAfterProcess)
{
analyzer.GetPoints(samples, Points);
if (Points.Count == 0)
{
IsRunning = false;
return;
}
}
_to = Points.Max(x => x.Y);
_from = TestName.Contains("sealtest") ? Points.FirstOrDefault(x => x.X == 0).Y : Points.Min(x => x.Y);
List<string> titles = analyzer.Reader.GetTitles(OpenFilePath);
TitleAxisBottom = titles[0];
TitleAxisLeft = titles[1];
// data.Clear();
_to += 100;
RaisePropertyChanged("To");
if (_from != 0)
_from -= 100;
RaisePropertyChanged("From");
XStep = (int)(Points.Count / 5);
IsRunning = false;
PlotControl.InvalidatePlot(true);
if(analyzer.Reader.PrintResultsToPDFFile())
{
await PrintToXpsFile();
}
InvalidateRelayCommands();
}
/// <summary>
/// Generates all results from command line and close application.
/// </summary>
public async Task GenerateInBackground(string openFilePath)
{
OpenFilePath = openFilePath;
if (false == File.Exists(OpenFilePath) || IsFileLocked(OpenFilePath))
return;
var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
if (analyzer == null)
return;
AnalyzerAttribute[] attr = analyzer.GetType().GetCustomAttributes(typeof(AnalyzerAttribute), true);
if (attr != null && attr.Count() > 0)
{
TestName = attr[0].Name;
}
List<OxyPlot.Wpf.LineAnnotation> annotations = new List<OxyPlot.Wpf.LineAnnotation>();
var samples = analyzer.Reader.ReadScvFile(OpenFilePath, annotations);
analyzer.GetPoints(samples, Points);
if (Points.Count == 0)
{
return;
}
List<IAnalyzerResult> res = await analyzer.Process(samples, true);
AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res);
await ExportResultsToTextFile();
}
#endregion
#region SaveInXps file
private async Task PrintToXpsFile()
{
await Task.Delay(200);
try
{
var resultFile = FileHelper.GetResultFilePath();
if (resultFile.IsNotNullOrEmpty())
{
SaveResultsAsXps(resultFile);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
public void SaveResultsAsXps( string fileName)
{
var dir = Path.GetDirectoryName(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
string fileNameWithoutExtension = Path.Combine(dir, name);
ContentControl cc = ResultsPanel.Parent as ContentControl;
ResultsPanel.UpdateLayout();
List<Plot> all_plots = ResultsPanel.FindVisualChildren<OxyPlot.Wpf.Plot>().ToList();
List<Plot> plots = new List<Plot>();
List<System.Windows.Controls.Image> plotimages = new List<System.Windows.Controls.Image>();
int index = 0;
foreach (var item in all_plots)
{
var seriesdata = item.Series[0].ItemsSource;
item.RaiseEvent(new System.Windows.RoutedEventArgs(OxyPlot.Wpf.PlotView.LoadedEvent));
item.InvalidatePlot(true);
if (item.IsMeasureValid && item.ActualHeight > 0)
{
plots.Add(item);
string pngPlotFileName = String.Format($"{fileNameWithoutExtension}_Plottest{index}.png");
File.Delete(pngPlotFileName);
System.Windows.Controls.Image plotImage = new System.Windows.Controls.Image();
//print plot to png file - removed 2/07/2020
//using (var stream = File.Open(pngPlotFileName, FileMode.Create, FileAccess.ReadWrite))
{
PngExporter exporter = new PngExporter() { Width = (int)item.ActualWidth, Height = (int)item.ActualHeight, Background = OxyColors.White, Resolution = 96 };
//exporter.Export(item.ActualModel, stream);
BitmapSource bitmap = exporter.ExportToBitmap(item.ActualModel);
plotImage.Source = bitmap;
plotImage.UpdateLayout();
var parent = item.Parent;
if (parent is Panel)
{
var plpanel = (Panel)parent;
plpanel.Children.Remove(item);
plpanel.Children.Add(plotImage);
plpanel.UpdateLayout();
}
else if (parent is Decorator)
{
((Decorator)parent).Child = plotImage;
((Border)parent).UpdateLayout();
}
}
plotimages.Add(plotImage);
index++;
}
ResultsPanel.UpdateLayout();
}
if (cc != null)
{
cc.Content = null;
CreateDoc(fileName, plots, plotimages);
cc.Content = ResultsPanel;
}
}
private void CreateDoc( string fileName, List<Plot> plots, List<System.Windows.Controls.Image> plotimages)
{
Dispatcher.CurrentDispatcher.Invoke( DispatcherPriority.Loaded, new Action(() =>
{
var dir = Path.GetDirectoryName(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
string fileNameWithoutExtension = Path.Combine(dir, name);
Size reportSize = GetReportSize(ResultsPanel);
FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
fixedPage.Width = reportSize.Width;
fixedPage.Height = reportSize.Height;
fixedPage.Children.Add(ResultsPanel);
fixedPage.UpdateLayout();
pageContent.BeginInit();
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
pageContent.EndInit();
fixedDoc.Pages.Add(pageContent);
InjectData(fixedDoc, AnalyzerResults);
ResultsPanel.Measure(reportSize);
ResultsPanel.Arrange(new Rect(new Point(0, 0), ResultsPanel.DesiredSize));
ResultsPanel.UpdateLayout();
String sourceXpsFile = String.Format($"{fileNameWithoutExtension}_test.xps");
File.Delete(sourceXpsFile);
using (XpsDocument xpsd = new XpsDocument(sourceXpsFile, FileAccess.Write))
{
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(fixedDoc);
}
fixedPage.Children.Remove(ResultsPanel);
PdfSharp.Xps.XpsConverter.Convert(sourceXpsFile, fileName, 0);
File.Delete(sourceXpsFile);
}));
}
/// <summary>
/// Injects the data to printed document. Without this the binding data to elements doesn't work.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="dataSource">The data source.</param>
protected void InjectData(FixedDocument document, object dataSource)
{
document.DataContext = new { AnalyzerResults = dataSource };
// we need to give the binding infrastructure a push as we
// are operating outside of the intended use of WPF
var dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.Invoke(DispatcherPriority.SystemIdle, new DispatcherOperationCallback(delegate { return null; }), null);
}
private static Size GetReportSize(ItemsControl reportContainer)
{
double reportWidth = reportContainer.ActualWidth + 10;
double reportHeight = reportContainer.ActualHeight + 10;// (reportWidth / printDialog.PrintableAreaWidth) * printDialog.PrintableAreaHeight;
return new Size(reportWidth, reportHeight);
}
public static void Print(IPlotModel model, string fileName, double width, double height)
{
using (var stream = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite))
{
var exporter = new XpsExporter { Width = width, Height = height};
//PngExporter.Export(this.Plot.ActualModel, fileName, 600, 400, OxyColors.White)
exporter.Export(model, stream);
}
}
#endregion
#region ExportToExel
public async Task ExportResultsToTextFile()
{
var resultFile = FileHelper.GetResultFilePath();
var dir = Path.GetDirectoryName(resultFile);
var name = Path.GetFileNameWithoutExtension(resultFile);
string fileNameWithoutExtension = Path.Combine(dir, name);
String sourceFile = String.Format($"{fileNameWithoutExtension}s.txt");
File.Delete(sourceFile);
await Task.Factory.StartNew(() =>
{
try
{
List<IAnalyzerResult> results = AnalyzerResults.ToList();
using (StreamWriter outputFile = new StreamWriter(sourceFile))
{
outputFile.WriteLine(String.Format($" {TestName.ToUpper()} RESULTS: "));
outputFile.WriteLine("");
outputFile.WriteLine("");
foreach (var res in results)
{
if (res.GetType().IsSubclassOf(typeof(AnalyzerResultBase)))
{
List<AnalyzerResultProperty> properties = (res as AnalyzerResultBase).Properties;
foreach (var prop in properties)
{
outputFile.WriteLine(String.Format($" {prop.Name} : {prop.Value}"));
}
string resV = String.Format($" RESULT = {res.Result.ToString()}");
outputFile.WriteLine(resV);
outputFile.WriteLine("");
}
}
outputFile.Flush();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
});
}
public async void ExportFlowResultsToExcel()
{
string filePath = (string)Settings.GetValueByName(AnalyzerSettingsEnum.DirectoryPath);
if (!Directory.Exists(filePath))
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
filePath = dialog.FileName;
if (filePath.Count(x => x == '%') == 2)
{
var variable = Regex.Match(filePath, "(?<=%)(.*?)(?=%)").Value;
filePath = filePath.Replace($"%{variable}%", Environment.ExpandEnvironmentVariables($"%{variable}%"));
}
Settings.SetValueByName(AnalyzerSettingsEnum.DirectoryPath, filePath);
Settings.SetDefaultPath(filePath);
}
else
{
MessageBox.Show("An error occurred while trying to open directory for saving result. ",
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
}
await Task.Run(() =>
{
ExcelWriter writer = null;
ExcelReader reader = null;
try
{
IsFree = false;
Stream stream = null;
bool dispose = false;
if (false == filePath.EndsWith(@"\"))
{
filePath += @"\";
}
String file = filePath + $"DispensersData.xlsx";
if (File.Exists(file))
{
//stream = File.OpenRead(file);
stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
dispose = true;
}
else
{
var b = Assembly.GetExecutingAssembly().GetManifestResourceNames();
stream = EmbeddedResourceHelper.GetEmbeddedResourceStream("Tango.DispenserAnalyzer.UI.Templates.DispensersData.xlsx");
}
if (stream == null)
return;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
File.WriteAllBytes(file, data);
if (dispose)
{
stream.Dispose();
}
reader = new ExcelReader(file);
List<ExcelDataModel> old_threadCharacteristicsExelModels = reader.GetDataByIndex<ExcelDataModel>("Data", 2);
reader.Dispose();
reader = null;
int maxNumber = old_threadCharacteristicsExelModels.Count > 0 ? old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Max(x => x.No___of_test) : 0;
maxNumber++;
var time_test = AnalysisService.GetDateTimeString(FileName);
var dispenser = AnalysisService.GetDispenserNumber(FileName);
int iterations = 0;
if (old_threadCharacteristicsExelModels.Count > 0)
{
var one_existed = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser && x.DATE == time_test);
if (one_existed > 0)
{
InvokeUI(() =>
{
var warningresult = MessageBox.Show($"The result is already saved for the dispenser {dispenser} at time {time_test}. Do you want to save it anyway?",
"Warning",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if(warningresult == MessageBoxResult.Cancel)
return;
});
}
iterations = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser );
}
iterations++;
//write results
List<ExcelDataModel> threadCharacteristicsExelModels = new List<ExcelDataModel>();
ExcelDataModel model = new ExcelDataModel();
model.No___of_test = maxNumber;//Could be defiend and saved
model.DISPENSER = dispenser;
model.iteration = iterations;
model.Location = FileName.IndexOf("CH8") > 0 ? "Dagesh" : "Twine";
model.DATE = time_test;
List<IAnalyzerResult> results = AnalyzerResults.ToList();
bool firstFlowAverageResult = true;
bool firstPrimingResult = true;
bool firstErrorResult = true;
bool pass = true;
foreach (var res in results)
{
if (res is PrimingAnalyzerResult)
{
if (firstPrimingResult)
{
model.PBU___sec__First_cycle = (res as PrimingAnalyzerResult).OnlyTime;
firstPrimingResult = false;
}
else
{
model.PBU___sec__Second_cycle = (res as PrimingAnalyzerResult).OnlyTime;
}
}
else if (res is FlowAverageAnalyzerResult)
{
if (firstFlowAverageResult)
{
model.Average_Value = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##");
firstFlowAverageResult = false;
if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed)
pass = false;
}
else
{
model.AverageValue2 = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##");
if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed)
pass = false;
}
}
else if (res is FlowAnalyzerResult)
{
if (firstErrorResult)
{
model.Max_Error = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##");
model.Error__mBr = (res as FlowAnalyzerResult).MaxLocalError.ToString();
model.Trend = (res as FlowAnalyzerResult).Trend;
firstErrorResult = false;
}
else
{
model.MaxError2 = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##");
model.Error2 = (res as FlowAnalyzerResult).MaxLocalError.ToString();
model.Trend2 = (res as FlowAnalyzerResult).Trend;
}
}
}
model.Test_result = pass ? "Pass" : "Fail";
model.Eng_Recommendations = "-";
model.Last_Action = "-";
threadCharacteristicsExelModels.Add(model);
writer = new ExcelWriter(file);
writer.WriteData(threadCharacteristicsExelModels, "Data");
writer.Dispose();
writer = null;
}
catch (Exception ex)
{
InvokeUI(() =>
{
MessageBox.Show("An error occurred while trying to save results in file DispensersData.xlsx. Error" + ex.Message,
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Warning);
});
}
finally
{
IsFree = true;
if (reader != null)
reader.Dispose();
if (writer != null)
writer.Dispose();
}
});
}
#endregion
#region CompareResults
private void Compareresults(object obj)
{
//List<string> names, List<AnalyzerResultBase> results
CompareResultsDlg resultsdlg = new CompareResultsDlg( ResultsToCompare);
resultsdlg.Owner = System.Windows.Application.Current.MainWindow;
resultsdlg.ShowDialog();
AddToComare = false;
ResultsToCompare.ToList().ForEach(x => x.RemoveCompareResultEvent -= OnCompareResultsChanged);
ResultsToCompare.Clear();
CompareCommand.RaiseCanExecuteChanged();
}
private bool CanCompareresults(object arg)
{
return ResultsToCompare.Count > 1;
}
private void OnAddToCompareResults(bool add)
{
if(add)
{
if (ResultsToCompare.Count == 3)
{
ResultsToCompare.RemoveAt(0);
}
ResultsToCompare.Add( new CompareResultModel(new EventHandler(OnCompareResultsChanged)) { Result= AnalyzerResults[0] as AnalyzerResultBase, IsAddedResult = true, ResultName = Path.GetFileNameWithoutExtension(FileName)});
}
if(add == false )
{
if (ResultsToCompare.Count > 0)
{
ResultsToCompare[ResultsToCompare.Count - 1].RemoveCompareResultEvent -= OnCompareResultsChanged;
ResultsToCompare.RemoveAt(ResultsToCompare.Count - 1);
}
}
CompareCommand.RaiseCanExecuteChanged();
}
public void OnCompareResultsChanged(object sender, EventArgs e)
{
CompareResultModel result = sender as CompareResultModel;
if(result != null && result.IsAddedResult == false)
{
result.RemoveCompareResultEvent -= OnCompareResultsChanged;
ResultsToCompare.Remove(result);
CompareCommand.RaiseCanExecuteChanged();
}
}
public bool CanSaveExel(object arg)
{
var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
if (analyzer == null)
return false;
return AnalyzerResults.Count > 0 && analyzer is FlowAnalyser;
}
private void SaveExel()
{
if(!IsFree)
return;
// await ExportRMLToExcel().ConfigureAwait(false);
ExportFlowResultsToExcel();
}
#endregion
}
}
|