diff options
Diffstat (limited to 'Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs')
| -rw-r--r-- | Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs | 578 |
1 files changed, 0 insertions, 578 deletions
diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs deleted file mode 100644 index 48d426d23..000000000 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs +++ /dev/null @@ -1,578 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Win32; -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 System.Threading; -using Tango.DispenserAnalyzer.UI.View; -using Tango.Core.Helpers; -using Tango.Documents; - -namespace Tango.DispenserAnalyzer.UI.ViewModels -{ - public class MainWindowVM: ViewModel - { - private const string FILE_EXTENSION = ".pdf"; - - 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; } - - public RelayCommand OpenCSVFileCommand { get; set; } - public RelayCommand GenerateCommand { get; set; } - public RelayCommand OpenSettingWndCommand { get; set; } - - public MainWindowVM() - { - OpenCSVFileCommand = new RelayCommand(OpenCSVFile); - GenerateCommand = new RelayCommand(Generate, CanGenerate); - OpenSettingWndCommand = new RelayCommand(OpenSettingWnd); - - YFormatter = value => value.ToString(); - _from = 0; - _to = 1; - XStep = 1; - AnalyzerResults = new ObservableCollection<IAnalyzerResult>(); - _isRunning = false; - TitleAxisBottom = ""; - TitleAxisLeft = ""; - this.Points = new List<DataPoint>(); - } - - #region Settings - - public void OpenSettingWnd() - { - SettingsWnd settings = new SettingsWnd(); - settings.Owner = System.Windows.Application.Current.MainWindow; - if(true == settings.ShowDialog()) - { - Dictionary<AnalyzerSettingsEnum, double> changes = settings.GetChanges(); - foreach (KeyValuePair<AnalyzerSettingsEnum, double> entry in changes) - { - Settings.SetValueByName(entry.Key, entry.Value); - } - } - } - - #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() - { - ResetSettings(); - if(File.Exists(OpenFilePath)) - { - FileHelper.OpenFilePath = OpenFilePath; - FileName = Path.GetFileName(OpenFilePath); - } - } - #endregion - - #region Generate - - public bool CanGenerate() - { - 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; - ResetSettings(); - - 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); - analyzer.GetPoints(samples, Points); - if (Points.Count == 0) - { - IsRunning = false; - return; - } - annotations.ForEach(x => PlotControl.Annotations.Add(x)); - To = 0; - From = 0; - - List<IAnalyzerResult> res = await analyzer.Process(samples, false); - AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res); - - _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(); - } - } - - /// <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 - - private void ResetSettings() - { - 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); - } - - #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); - } - }); - - } - #endregion - - } -} |
