diff options
Diffstat (limited to 'Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels')
5 files changed, 2599 insertions, 0 deletions
diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/AddItemDialogVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/AddItemDialogVM.cs new file mode 100644 index 000000000..0187f3bee --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/AddItemDialogVM.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Core.Commands; +using Tango.SharedUI; + +namespace Tango.MachineStudio.ThreadExtensions.ViewModels +{ + public class AddItemDialogVM : DialogViewVM + { + private string _name; + + public string Name + { + get { return _name; } + set { _name = value; + RaisePropertyChangedAuto(); + SaveCommand.RaiseCanExecuteChanged(); + } + } + + + /// <summary> + /// Gets or sets the login command. + /// </summary> + public RelayCommand SaveCommand { get; set; } + + /// <summary> + /// Gets or sets the cancel command. + /// </summary> + public RelayCommand CancelCommand { get; set; } + + /// <summary> + /// Initializes a new instance of the <see cref="MachineLoginViewVM"/> class. + /// </summary> + public AddItemDialogVM() + { + SaveCommand = new RelayCommand(Accept, () => false == String.IsNullOrEmpty(Name)); + CancelCommand = new RelayCommand(Cancel); + } + + } +} diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/ColorParametersVewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/ColorParametersVewVM.cs new file mode 100644 index 000000000..a89a2e33c --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/ColorParametersVewVM.cs @@ -0,0 +1,817 @@ +using OxyPlot; +using OxyPlot.Wpf; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.BL; +using Tango.BL.ActionLogs; +using Tango.BL.Builders; +using Tango.BL.DTO; +using Tango.BL.Entities; +using Tango.Core; +using Tango.MachineStudio.Common.Notifications; +using Tango.SharedUI; +using Tango.AutoComplete.Editors; +using Tango.MachineStudio.ThreadExtensions.Models; +using Tango.Core.Commands; +using Microsoft.Win32; +using System.Diagnostics; +using Tango.Settings; +using Tango.MachineStudio.Common; +using Tango.Logging; +using Tango.BL.Enumerations; +using System.Data.Entity; + +namespace Tango.MachineStudio.ThreadExtensions.ViewModels +{ + public class ColorParametersVewVM : ViewModel + { + private INotificationProvider _notification; + private IActionLogManager _actionLogManager; + + private ObservablesContext _active_context; + + public event EventHandler SaveColorParameters; + + #region Properties + + private ColorProcessParameter _selectedColorProcessparameter; + /// <summary> + /// Gets or sets the selected RML. + /// </summary> + public ColorProcessParameter SelectedColorProcessParameter + { + get { return _selectedColorProcessparameter; } + set + { + _selectedColorProcessparameter = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessData> _magentaProcessData; + public ObservableCollection<ColorProcessData> MagentaProcessData + { + get + { + return _magentaProcessData; + } + set + { + _magentaProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessData> _cyanProcessData; + public ObservableCollection<ColorProcessData> CyanProcessData + { + get + { + return _cyanProcessData; + } + set + { + _cyanProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessData> _yellowProcessData; + public ObservableCollection<ColorProcessData> YellowProcessData + { + get + { + return _yellowProcessData; + } + set + { + _yellowProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessData> _blackProcessData; + public ObservableCollection<ColorProcessData> BlackProcessData + { + get + { + return _blackProcessData; + } + set + { + _blackProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessFactor> _factor100ProcessData; + public ObservableCollection<ColorProcessFactor> Factor100ProcessData + { + get + { + return _factor100ProcessData; + } + set + { + _factor100ProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessFactor> _factor200ProcessData; + public ObservableCollection<ColorProcessFactor> Factor200ProcessData + { + get + { + return _factor200ProcessData; + } + set + { + _factor200ProcessData = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessFactor> _minInkUptake; + public ObservableCollection<ColorProcessFactor> MinInkUptake + { + get + { + return _minInkUptake; + } + set + { + _minInkUptake = value; + RaisePropertyChangedAuto(); + } + } + + private ObservableCollection<ColorProcessFactor> _maxInkUptake; + public ObservableCollection<ColorProcessFactor> MaxInkUptake + { + get + { + return _maxInkUptake; + } + set + { + _maxInkUptake = value; + RaisePropertyChangedAuto(); + } + } + + + private PlotProperties _cyanPlot; + + public PlotProperties CyanPlot + { + get { return _cyanPlot; } + set + { + _cyanPlot = value; + RaisePropertyChangedAuto(); + } + } + + private PlotProperties _magentaPlot; + + public PlotProperties MagentaPlot + { + get { return _magentaPlot; } + set { _magentaPlot = value; } + } + + private PlotProperties _yellowPlot; + + public PlotProperties YellowPlot + { + get { return _yellowPlot; } + set { _yellowPlot = value; } + } + + private PlotProperties _blackPlot; + + public PlotProperties BlackPlot + { + get { return _blackPlot; } + set { _blackPlot = value; } + } + + private string _RMLExtentionGUID; + + public string RMLExtemtionGUID + { + get { return _RMLExtentionGUID; } + set + { + _RMLExtentionGUID = value; + OnRMLExtensionGUIDChanged(); + } + } + + private string _RMLGUID; + + public string RMLGUID + { + get { return _RMLGUID; } + set + { + _RMLGUID = value; + OnRMLExtensionGUIDChanged(); + } + } + + protected string _selectedMachineGuid; + /// <summary> + /// Gets or sets the selected machine. + /// </summary> + public String SelectedMachineGUID + { + get { return _selectedMachineGuid; } + set + { + if (value != null && _selectedMachineGuid != value) + { + _selectedMachineGuid = value; + SelectedMachineChanged(); + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); + } + } + } + + private bool _isViewLoaded; + /// <summary> + /// Gets or sets a value indicating whether this instance is view loaded. Used to update charts. + /// </summary> + /// <value> + /// <c>true</c> if this instance is view loaded; otherwise, <c>false</c>. + /// </value> + public bool IsViewLoaded + { + get { return _isViewLoaded; } + set + { + if (_isViewLoaded != value) + { + _isViewLoaded = value; + } + } + } + + /// <summary> + /// Saved guid of the removed color process data before save. + /// </summary> + private List<string> RemovedColorProcessDataBeforeSave { get; set;} + + #endregion + #region commands + + public RelayCommand SaveCommand { get; set; } + + public RelayCommand SaveFactorsCommand { get; set; } + + public RelayCommand ImportCyanDataCommand { get; set; } + public RelayCommand ImportMagentaDataCommand { get; set; } + public RelayCommand ImportYellowDataCommand { get; set; } + public RelayCommand ImportBlackDataCommand { get; set; } + + private void ImportMagentaData(object obj) + { + List<ColorDataExcelModel> items; + if (LoadColorDataFromExcel(out items) && items != null) + { + MagentaProcessData.Clear(); + RemoveColorDataByColor((int)FactorColors.MAGENTA, SelectedColorProcessParameter.Guid); + items.ForEach(x => MagentaProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid })); + MagentaPlot.CreateGraph(MagentaProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.MAGENTA); + } + } + + private void ImportYellowData(object obj) + { + List<ColorDataExcelModel> items; + if (LoadColorDataFromExcel(out items) && items != null) + { + YellowProcessData.Clear(); + RemoveColorDataByColor((int)FactorColors.YELLOW, SelectedColorProcessParameter.Guid); + items.ForEach(x => YellowProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid })); + YellowPlot.CreateGraph(YellowProcessData.ToList(), false); + UpdateFactorsOnChangeProcessData(FactorColors.YELLOW); + } + } + + private void ImportCyanData(object obj) + { + List<ColorDataExcelModel> items; + if (LoadColorDataFromExcel(out items) && items != null) + { + CyanProcessData.Clear(); + RemoveColorDataByColor((int)FactorColors.CYAN, SelectedColorProcessParameter.Guid); + items.ForEach(x => CyanProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid })); + CyanPlot.CreateGraph(CyanProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.CYAN); + } + } + + + private void ImportBlackData(object obj) + { + List<ColorDataExcelModel> items; + if (LoadColorDataFromExcel(out items) && items != null) + { + BlackProcessData.Clear(); + RemoveColorDataByColor((int)FactorColors.BLACK, SelectedColorProcessParameter.Guid); + items.ForEach(x => BlackProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid })); + BlackPlot.CreateGraph(BlackProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.BLACK); + } + } + + private async void SaveFactors(object obj) + { + using (var context = ObservablesContext.CreateDefault()) + { + try { + var rml = await new RmlBuilder(context) + .Set(RMLGUID) + .WithLiquidFactors() + .BuildAsync(); + var LiquidTypesRml = rml.LiquidTypesRmls; + foreach (var factor in Factor100ProcessData) + { + var liquidFactor = LiquidTypesRml.ToList().First(x => x.LiquidType.Name.ToLower() == factor.FactorColor.ToDescription().ToLower()); + if(liquidFactor != null) + { + liquidFactor.MaxNlPerCm = factor.InkNlCm; + } + } + await context.SaveChangesAsync(); + } + catch(Exception ex) + { + LogManager.Log(ex, "Could not update color factor."); + _notification.ShowError($"An error occurred while trying to save color factors.\n{ex.Message}"); + } + } + + } + + + private bool LoadColorDataFromExcel(out List<ColorDataExcelModel> items) + { + OpenFileDialog dlg = new OpenFileDialog(); + items = null; + try + { + dlg.Title = $"Import excel file with data"; + dlg.Filter = "Excel Files|*.xlsx"; + if (dlg.ShowDialog().Value) + { + string error = ""; + ColorDataExcelModel.GetDataFromFile(dlg.FileName, out items, ref error); + if (false == String.IsNullOrEmpty(error) || items == null || items.Count == 0) + { + _notification.ShowError("An error occurred while trying to import data form the selected excel file. Please check the file format if valid and is available to read."); + return false; + } + return true; + } + } + catch (Exception ex) + { + LogManager.Log(ex, "Error importing excel file " + dlg.FileName); + _notification.ShowError("An error occurred while trying to import the selected excel file. Please check the file format if valid and is available to read."); + } + return false; + } + + #endregion + + public ColorParametersVewVM(INotificationProvider notification, IActionLogManager actionLogManager) + { + _notification = notification; + _actionLogManager = actionLogManager; + _isViewLoaded = false; + RemovedColorProcessDataBeforeSave = new List<string>(); + + + CyanProcessData = new ObservableCollection<ColorProcessData>(); + CyanProcessData.CollectionChanged += OnCyanCollectionChanged; + + MagentaProcessData = new ObservableCollection<ColorProcessData>(); + MagentaProcessData.CollectionChanged += OnMagentaCollectionChanged; + + YellowProcessData = new ObservableCollection<ColorProcessData>(); + YellowProcessData.CollectionChanged += OnYellowCollectionChanged; + + BlackProcessData = new ObservableCollection<ColorProcessData>(); + BlackProcessData.CollectionChanged += OnBlackCollectionChanged; + + CyanPlot = new PlotProperties(FactorColors.CYAN); + YellowPlot = new PlotProperties(FactorColors.YELLOW); + MagentaPlot = new PlotProperties(FactorColors.MAGENTA); + BlackPlot = new PlotProperties(FactorColors.BLACK); + + SaveCommand = new RelayCommand(Save, () => IsFree); + ImportCyanDataCommand = new RelayCommand(ImportCyanData); + ImportMagentaDataCommand = new RelayCommand(ImportMagentaData); + ImportYellowDataCommand = new RelayCommand(ImportYellowData); + ImportBlackDataCommand = new RelayCommand(ImportBlackData); + + SaveFactorsCommand = new RelayCommand(SaveFactors, () => IsFree); + } + + + #region Loading + + public async void LoadColorParameters() + { + if (SelectedMachineGUID == null) + { + _notification.ShowWarning(LogManager.Log($"Please, select machine.", LogCategory.Warning)); + IsFree = false; + return; + } + IsFree = false; + if (_active_context != null) + { + _active_context.Dispose(); + } + + _active_context = ObservablesContext.CreateDefault(); + + await Task.Factory.StartNew(() => + { + using (_notification.PushTaskItem("Loading Color Process Parameters ...")) + { + + var currentcolorProcessParameter = _active_context.ColorProcessParameters.Where(x => x.RmlsExtensionsGuid == RMLExtemtionGUID && x.MachineGuid == SelectedMachineGUID).FirstOrDefault(); + if (currentcolorProcessParameter != null) + { + SelectedColorProcessParameter = new ColorProcessParametersBuilder(_active_context).Set(currentcolorProcessParameter.Guid).WithColorProcessData().WithColorProcessFactor().Build(); + } + + if (SelectedColorProcessParameter == null) + { + SelectedColorProcessParameter = new ColorProcessParameter() { RmlsExtensionsGuid = RMLExtemtionGUID, MachineGuid = SelectedMachineGUID }; + SelectedColorProcessParameter.WhitePointL = 0.0; + SelectedColorProcessParameter.WhitePointA = 0.0; + SelectedColorProcessParameter.WhitePointB = 0.0; + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.CYAN, FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.MAGENTA, FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.YELLOW, FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.BLACK, FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.CYAN, FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.MAGENTA, FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.YELLOW, FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.BLACK, FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.CYAN, FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.MAGENTA, FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.YELLOW, FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.BLACK, FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.CYAN, FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.MAGENTA, FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.YELLOW, FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + SelectedColorProcessParameter.ColorProcessFactors.Add(new ColorProcessFactor() { FactorColor = FactorColors.BLACK, FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + _active_context.ColorProcessParameters.Add(SelectedColorProcessParameter); + _active_context.SaveChangesAsync(); + } + + } + }); + + LoadParameters(); + IsFree = true; + } + + private void LoadParameters() + { + Factor100ProcessData = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 100).ToObservableCollection(); + + Factor200ProcessData = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 200).ToObservableCollection(); + + MinInkUptake = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 1).ToObservableCollection(); + + MaxInkUptake = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 1111).ToObservableCollection(); + + RemovedColorProcessDataBeforeSave.Clear(); + + var cyanDataList = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == FactorColors.CYAN).ToList().OrderBy(x => x.InkNlCm).ToList(); + CyanProcessData.Clear(); + cyanDataList.ForEach(y => CyanProcessData.Add(y)); + + var magentaDatalist = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == FactorColors.MAGENTA).ToList().OrderBy(x => x.InkNlCm).ToList(); ; + MagentaProcessData.Clear(); + magentaDatalist.ForEach(y => MagentaProcessData.Add(y)); + + var yellowDatalist = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == FactorColors.YELLOW).ToList().OrderBy(x => x.InkNlCm).ToList(); ; + YellowProcessData.Clear(); + yellowDatalist.ForEach(y => YellowProcessData.Add(y)); + + var blackDatalist = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == FactorColors.BLACK).ToList().OrderBy(x => x.InkNlCm).ToList(); ; + BlackProcessData.Clear(); + blackDatalist.ForEach(y => BlackProcessData.Add(y)); + + UpdatePlots(); + SelectedColorProcessParameter.ColorProcessFactors.ToList().ForEach(x => UpdateFactorsOnChangeProcessData(x.FactorColor)); + } + + private void OnRMLExtensionGUIDChanged() + { + SelectedColorProcessParameter = null; + } + + private void SelectedMachineChanged() + { + SelectedColorProcessParameter = null; + LoadColorParameters(); + } + #endregion + + #region Update Plot + + public void UpdatePlots() + { + if (IsViewLoaded) + { + CyanPlot.CreateGraph(CyanProcessData.ToList(), true); + MagentaPlot.CreateGraph(MagentaProcessData.ToList(), true); + YellowPlot.CreateGraph(YellowProcessData.ToList(), false); + BlackPlot.CreateGraph(BlackProcessData.ToList(), true); + } + } + + private void OnCyanCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + OnColorCollectionChange(e, FactorColors.CYAN, CyanMeasurementModelPropertyChanged); + } + + private void CyanMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (IsFree) + { + CyanPlot.CreateGraph(CyanProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.CYAN); + } + } + + private void OnMagentaCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + OnColorCollectionChange(e, FactorColors.MAGENTA, MagentaMeasurementModelPropertyChanged); + } + + private void MagentaMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (IsFree) + { + MagentaPlot.CreateGraph(MagentaProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.MAGENTA); + } + } + + private void OnYellowCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + OnColorCollectionChange(e, FactorColors.YELLOW, YellowMeasurementModelPropertyChanged); + } + + private void YellowMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (IsFree) + { + YellowPlot.CreateGraph(YellowProcessData.ToList(), false); + UpdateFactorsOnChangeProcessData(FactorColors.YELLOW); + } + } + + private void OnBlackCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + OnColorCollectionChange(e, FactorColors.BLACK, BlackMeasurementModelPropertyChanged); + } + + private void BlackMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (IsFree) + { + BlackPlot.CreateGraph(BlackProcessData.ToList(), true); + UpdateFactorsOnChangeProcessData(FactorColors.BLACK); + } + } + + private void OnColorCollectionChange(NotifyCollectionChangedEventArgs e, FactorColors color, PropertyChangedEventHandler eventHandler) + { + if (e.Action == NotifyCollectionChangedAction.Reset) + { + var processData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == color).ToObservableCollection(); + + foreach (ColorProcessData item in processData) + { + item.PropertyChanged -= eventHandler; + SelectedColorProcessParameter.ColorProcessData.Remove(item); + } + //UpdateFactorsOnChangeProcessData(color); + } + else if (e.Action == NotifyCollectionChangedAction.Remove) + { + foreach (ColorProcessData item in e.OldItems) + { + SelectedColorProcessParameter.ColorProcessData.Remove(item); + item.PropertyChanged -= eventHandler; + RemovedColorProcessDataBeforeSave.Add(item.Guid); + } + UpdateFactorsOnChangeProcessData(color); + } + else if (e.Action == NotifyCollectionChangedAction.Add) + { + foreach (ColorProcessData item in e.NewItems) + { + item.FactorColor = color; + item.ColorProcessParametersGuid = SelectedColorProcessParameter.Guid; + SelectedColorProcessParameter.ColorProcessData.Add(item); + item.PropertyChanged += eventHandler; + } + } + } + #endregion + + #region update factors + + /// <summary> + /// Updates the ColorProcessFactor from ColorProcessData item. + /// </summary> + /// <param name="factor">The factor.</param> + /// <param name="item">The item.</param> + private void UpdateFactor(ColorProcessFactor factor, DataPoint point) + { + if (factor == null) + return; + if (point.X == 0) + { + factor.InkNlCm = 0; + factor.L = factor.A = factor.B = 0.0; + return; + } + factor.InkNlCm = (int)point.X; + + } + + /// <summary> + /// Calculate and Update the factors on change process data. + /// </summary> + /// <param name="color">The color.</param> + private void UpdateFactorsOnChangeProcessData(FactorColors color) + { + bool isLtype = color == FactorColors.YELLOW ? false : true; + var processData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == color).ToList(); + double target100 = FactorTarget.GetFactor100(color); + double target200 = FactorTarget.GetFactor200(color); + //ColorProcessData closest100 = null; + //ColorProcessData closest200 = null; + + //var minDifference100 = double.MaxValue; + //var minDifference200 = double.MaxValue; + + if (processData.Count == 0) + return; + + //foreach (var item in processData) + //{ + // var colorvalue = isLtype ? item.L : item.B; + // var difference100 = Math.Abs(colorvalue - target100); + // if (minDifference100 > difference100) + // { + // minDifference100 = (int)difference100; + // closest100 = item; + // } + // var difference200 = Math.Abs(colorvalue - target200); + // if (minDifference200 > difference200) + // { + // minDifference200 = (int)difference200; + // closest200 = item; + // } + //} + var point100 = GetTargetPoint(processData, target100, isLtype); + UpdateFactor(Factor100ProcessData.FirstOrDefault(x => x.FactorColor == color), point100); + var point200 = GetTargetPoint(processData, target200, isLtype); + UpdateFactor(Factor200ProcessData.FirstOrDefault(x => x.FactorColor == color), point200); + } + + private DataPoint GetTargetPoint(List<ColorProcessData> listValues, double factor, bool isLtype) + { + if (listValues.Count < 2 || factor <= 0) + return new DataPoint(0, 0); + + var test = listValues.GroupBy(x => x.InkNlCm, x => isLtype ? x.L : x.B, (Ink, Value) => new { InkValuep = Ink, ColorValue = Value.Average() }).ToList(); + var distinctItems = listValues.GroupBy(x => x.InkNlCm, x => isLtype ? x.L : x.B, (Ink, Value) => new { InkValuep = Ink, ColorValue = Value }).Select(y => new ColorProcessData { InkNlCm = y.InkValuep, L = y.ColorValue.Average() }).ToList(); + + double calculatedX = 0.0; + ColorProcessData prevItem = distinctItems[0]; + for (int index = 1; index < distinctItems.Count; index++) + { + var item = distinctItems[index]; + if (prevItem.L > item.L && (factor > prevItem.L || (factor <= prevItem.L && factor >= item.L)) + || (prevItem.L <= item.L && (factor > prevItem.L || (factor >= prevItem.L && factor <= item.L))) + || ((index + 1) == distinctItems.Count && calculatedX == 0.0)) + { + calculatedX = CalculateXValue(factor, new DataPoint(prevItem.InkNlCm, prevItem.L), new DataPoint(item.InkNlCm, item.L)); + break; + + } + prevItem = item; + } + + return new DataPoint(calculatedX, factor); ; + } + + private double CalculateXValue(double factor, DataPoint leftPoint, DataPoint rightPoint) + { + double deltaX = rightPoint.X - leftPoint.X; + double deltaY = rightPoint.Y - leftPoint.Y; + + // prevents division by zero exceptions. + if (deltaX == 0) + return 0.0; + + double slope = deltaY / deltaX; + + // double c = leftPoint.Y - slope * leftPoint.X; + // double cX = (factor - c) / slope; + + return (leftPoint.X + (factor - leftPoint.Y) / slope); + + } + #endregion + + #region save + + private async void RemoveColorDataByColor(int color, string colorProcessParamGuid) + { + if(_active_context == null) + { + return; + } + var existingColorProcessData = await _active_context.ColorProcessData.Where(y => y.Color == color && y.ColorProcessParametersGuid == colorProcessParamGuid).ToListAsync(); + foreach( var data in existingColorProcessData) + { + _active_context.ColorProcessData.Remove(data); + } + } + public async void Save() + { + if (String.IsNullOrEmpty(SelectedMachineGUID)) + { + _notification.ShowWarning(LogManager.Log($"Could not save Color Process Parameters. Please, select machine before save.", LogCategory.Warning)); + return; + } + + try + { + IsFree = false; + + SelectedColorProcessParameter.LastUpdated = DateTime.UtcNow; + + foreach (var item in RemovedColorProcessDataBeforeSave) + { + var existingColorProcessData = await _active_context.ColorProcessData.FirstOrDefaultAsync(y => y.Guid == item); + if (existingColorProcessData != null) + { + _active_context.ColorProcessData.Remove(existingColorProcessData); + } + } + foreach(var colordata in SelectedColorProcessParameter.ColorProcessData) + { + colordata.LastUpdated = DateTime.UtcNow; + } + foreach (var factordata in SelectedColorProcessParameter.ColorProcessFactors) + { + factordata.LastUpdated = DateTime.UtcNow; + } + + await _active_context.SaveChangesAsync(); + + LoadColorParameters(); + } + catch (Exception ex) + { + LogManager.Log(ex, "Could not update color parameters."); + _notification.ShowError($"An error occurred while trying to save color parameters.\n{ex.Message}"); + } + finally + { + IsFree = true; + EventHandler handler = SaveColorParameters; + handler?.Invoke(this, new EventArgs()); + } + } + + #endregion + } +} + diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/MainViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/MainViewVM.cs new file mode 100644 index 000000000..10ec55958 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/MainViewVM.cs @@ -0,0 +1,1130 @@ +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Data; +using Tango.BL; +using Tango.BL.Builders; +using Tango.BL.Calibration; +using Tango.BL.Entities; +using Tango.Core.Commands; +using Tango.MachineStudio.Common; +using Tango.MachineStudio.Common.Notifications; + + +using System.Data.Entity; +using Tango.Core.ExtensionMethods; +using Tango.MachineStudio.Common.Authentication; +using Tango.BL.ActionLogs; +using Tango.BL.DTO; +using Tango.BL.Enumerations; +using Tango.MachineStudio.ThreadExtensions.Contracts; +using Tango.MachineStudio.ThreadExtensions.Views; +using Tango.MachineStudio.ThreadExtensions.Models; +using Tango.Settings; +using System.Reflection; + +namespace Tango.MachineStudio.ThreadExtensions.ViewModels +{ + public class MainViewVM : StudioViewModel<IMainView> + { + private INotificationProvider _notification; + private IAuthenticationProvider _authentication; + private IActionLogManager _actionLogManager; + + private ObservablesContext _rmlExtentions_context; + private ObservablesContext _active_context; + + private List<User> _allUsers; + + #region properties + //private ObservableCollection<RmlsExtension> _rmlsExtension; + //public ObservableCollection<RmlsExtension> RmlsExtensions + //{ + // get { return _rmlsExtension; } + // set { _rmlsExtension = value; + // RaisePropertyChangedAuto(); } + //} + + private List<RmlExtensionModel> _rmlExtensions; + public List<RmlExtensionModel> RmlExtensions + { + get { return _rmlExtensions; } + set { _rmlExtensions = value; + RaisePropertyChangedAuto(); } + } + + private RmlsExtension _ActiveRMLExtension; + public RmlsExtension ActiveRMLExtension + { + get { return _ActiveRMLExtension; } + set { _ActiveRMLExtension = value; + RaisePropertyChangedAuto(); } + } + + private Rml _activeRML; + public Rml ActiveRML + { + get { return _activeRML; } + set + { + _activeRML = value; + RaisePropertyChangedAuto(); + } + } + + private RmlExtensionModel _selectedRMLExtension; + public RmlExtensionModel SelectedRMLExtension + { + get { return _selectedRMLExtension; } + set { _selectedRMLExtension = value; + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); } + } + + //private ICollectionView _rmlExtCollectionView; + ///// <summary> + ///// Gets or sets the RML collection view. + ///// </summary> + //public ICollectionView RmlExtCollectionView + //{ + // get { return _rmlExtCollectionView; } + // set + // { + // _rmlExtCollectionView = value; + // RaisePropertyChangedAuto(); + // } + //} + + private ObservableCollection<YarnApplication> _applications; + public ObservableCollection<YarnApplication> Applications + { + get { return _applications; } + set { _applications = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnBrand> _brands; + public ObservableCollection<YarnBrand> Brands + { + get { return _brands; } + set { _brands = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnWhiteShade> _yarnWhiteShade; + public ObservableCollection<YarnWhiteShade> YarnWhiteShade + { + get { return _yarnWhiteShade; } + set { _yarnWhiteShade = value; RaisePropertyChangedAuto(); } + } + private ObservableCollection<MediaPurpos> _enduse; + public ObservableCollection<MediaPurpos> EndUse + { + get { return _enduse; } + set { _enduse = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<LinearMassDensityUnit> _units; + public ObservableCollection<LinearMassDensityUnit> Units + { + get { return _units; } + set { _units = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnFamily> _family; + public ObservableCollection<YarnFamily> Family + { + get { return _family; } + set { _family = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<FiberShape> _geometry; + public ObservableCollection<FiberShape> Geometry + { + get { return _geometry; } + set { _geometry = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnGlossLevel> _glosslevel; + public ObservableCollection<YarnGlossLevel> GlossLevel + { + get { return _glosslevel; } + set { _glosslevel = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnGroup> _group; + public ObservableCollection<YarnGroup> Group + { + get { return _group; } + set { _group = value; RaisePropertyChangedAuto(); } + } + + private List<String> _manufacturers; + + public List<String> Manufacturers + { + get { return _manufacturers; } + set { _manufacturers = value; + RaisePropertyChangedAuto(); + } + } + + + private ObservableCollection<MediaMaterial> _materials; + public ObservableCollection<MediaMaterial> Materials + { + get { return _materials; } + set { _materials = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnSubFamily> _subFamilies; + public ObservableCollection<YarnSubFamily> SubFamilies + { + get { return _subFamilies; } + set { _subFamilies = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnTexturing> _texturing; + public ObservableCollection<YarnTexturing> Texturing + { + get { return _texturing; } + set { _texturing = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnType> _yarnTypes; + public ObservableCollection<YarnType> YarnTypes + { + get { return _yarnTypes; } + set { _yarnTypes = value; RaisePropertyChangedAuto(); } + } + + private ObservableCollection<YarnIndustrysector> _industrySector; + public ObservableCollection<YarnIndustrysector> IndustrySector + { + get { return _industrySector; } + set { _industrySector = value; RaisePropertyChangedAuto(); } + } + + private String _Filter; + /// <summary> + /// Gets or sets the search filter. + /// </summary> + public String Filter + { + get { return _Filter; } + set { _Filter = value; RaisePropertyChangedAuto(); OnFilterChanged(); } + } + + private async void OnFilterChanged() + { + await LoadRmlExtentions(); + } + + private ColorParametersVewVM _colorParametersVewVM; + public ColorParametersVewVM ColorParametersVewVM + { + get { return _colorParametersVewVM; } + set { _colorParametersVewVM = value; RaisePropertyChangedAuto(); } + } + + private TestResultsViewVM _testResultsViewVM; + public TestResultsViewVM TestResultsViewVM + { + get { return _testResultsViewVM; } + set { _testResultsViewVM = value; RaisePropertyChangedAuto(); } + } + + protected MachineModel _selectedMachine; + /// <summary> + /// Gets or sets the selected machine. + /// </summary> + public MachineModel SelectedMachine + { + get { return _selectedMachine; } + set + { + if (value != null && _selectedMachine != value) + { + _selectedMachine = value; + SelectedMachineChanged(); + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); + } + } + } + + private ObservableCollection<MachineModel> _machines; + /// <summary> + /// Gets or sets the Machines. + /// </summary> + public ObservableCollection<MachineModel> Machines + { + get + { + return _machines; + } + + set + { + _machines = value; RaisePropertyChanged(nameof(Machines)); + } + + } + + #endregion + + #region commands + + public RelayCommand SaveCommand { get; set; } + + public RelayCommand ManageRmlExtensionCommand { get; set; } + + public RelayCommand BackToThreadExtensionViewsCommand { get; set; } + + private async void BackToThreadExtensionViews(object obj) + { + View.NavigateTo(RMLExtensionNavigationView.RMLExtensionsView); + await LoadRmlExtentions(); + } + + public RelayCommand AddManufacturerItemCommand { get; set;} + public RelayCommand EditManufacturerItemCommand { get; set; } + public RelayCommand DeleteManufacturerItemCommand { get; set; } + + public RelayCommand AddBrandItemCommand { get; set; } + public RelayCommand EditBrandItemCommand { get; set; } + public RelayCommand DeleteBrandItemCommand { get; set; } + + public RelayCommand AddEndUseItemCommand { get; set; } + public RelayCommand EditEndUseItemCommand { get; set; } + public RelayCommand DeleteEndUseItemCommand { get; set; } + + public RelayCommand AddApplicationItemCommand { get; set; } + public RelayCommand EditApplicationItemCommand { get; set; } + public RelayCommand DeleteApplicationItemCommand { get; set; } + + public RelayCommand AddIndustrySectorItemCommand { get; set; } + public RelayCommand EditIndustrySectorItemCommand { get; set; } + public RelayCommand DeleteIndustrySectorItemCommand { get; set; } + + public RelayCommand AddMaterialItemCommand { get; set; } + public RelayCommand EditMaterialItemCommand { get; set; } + public RelayCommand DeleteMaterialItemCommand { get; set; } + + public RelayCommand AddYarnTypeItemCommand { get; set; } + public RelayCommand EditYarnTypeItemCommand { get; set; } + public RelayCommand DeleteYarnTypeItemCommand { get; set; } + + public RelayCommand AddSubFamilyItemCommand { get; set; } + public RelayCommand EditSubFamilyItemCommand { get; set; } + public RelayCommand DeleteSubFamilyItemCommand { get; set; } + + public RelayCommand AddFamilyItemCommand { get; set; } + public RelayCommand EditFamilyItemCommand { get; set; } + public RelayCommand DeleteFamilyItemCommand { get; set; } + + public RelayCommand AddGroupItemCommand { get; set; } + public RelayCommand EditGroupItemCommand { get; set; } + public RelayCommand DeleteGroupItemCommand { get; set; } + + public RelayCommand AddTexturingItemCommand { get; set; } + public RelayCommand EditTexturingItemCommand { get; set; } + public RelayCommand DeleteTexturingItemCommand { get; set; } + + public RelayCommand AddGeometryItemCommand { get; set; } + public RelayCommand EditGeometryItemCommand { get; set; } + public RelayCommand DeleteGeometryItemCommand { get; set; } + + public RelayCommand AddYarnWhiteShadeItemCommand { get; set; } + public RelayCommand EditYarnWhiteShadeItemCommand { get; set; } + public RelayCommand DeleteYarnWhiteShadeItemCommand { get; set; } + + public RelayCommand AddGlossLevelItemCommand { get; set; } + public RelayCommand EditGlossLevelItemCommand { get; set; } + public RelayCommand DeleteGlossLevelItemCommand { get; set; } + + #endregion + + #region Command Functions + + private async void AddManufacturerItem(object obj) + { + AddItemDialogVM vm = ViewModelLocator.AddItemDialogVM; + vm.Name = ""; + + _notification.ShowModalDialog<AddItemDialogVM, Views.AddItemDialog>(vm, (x) => + { + if (Manufacturers.Any(y => y.ToLower() == vm.Name.ToLower())) + { + _notification.ShowError("Manufacturer already exists."); + return; + } + _active_context.YarnManufacturers.Add(new YarnManufacturer() { Name = vm.Name }); + + }, () => { }); + if(vm.DialogResult) + { + await _active_context.SaveChangesAsync(); + Manufacturers = _active_context.YarnManufacturers.Select(z => z.Name).ToList(); + ActiveRML.Manufacturer = Manufacturers.Where(z=> z == vm.Name).FirstOrDefault(); + } + } + + private async void EditManufacturerItem(object obj) + { + AddItemDialogVM vm = ViewModelLocator.AddItemDialogVM; + vm.Name = ActiveRML.Manufacturer; + bool bChanged = false; + + _notification.ShowModalDialog<AddItemDialogVM, Views.AddItemDialog>(vm, (x) => + { + if (ActiveRML.Manufacturer == x.Name) + return; + if (Manufacturers.Any(y => y == x.Name)) + { + _notification.ShowError("Manufacturer already exists."); + return; + } + var editItem = _active_context.YarnManufacturers.Where(z => z.Name == ActiveRML.Manufacturer).FirstOrDefault(); + if (editItem != null) + { + editItem.Name = x.Name; + ActiveRML.Manufacturer = x.Name; + bChanged = true; + } + }, () => { }); + if(bChanged) + { + await _active_context.SaveChangesAsync(); + Manufacturers = _active_context.YarnManufacturers.Select(x => x.Name).ToList(); + } + + } + + private bool AddItemToCollection<T>( ObservableCollection<T> collection, DbSet<T> dbColection, ref string name) where T : class + { + AddItemDialogVM vm = ViewModelLocator.AddItemDialogVM; + vm.Name = ""; + + PropertyInfo pi = typeof(T).GetProperty("Name"); + bool returnValue = false; + _notification.ShowModalDialog<AddItemDialogVM, Views.AddItemDialog>(vm, (x) => + { + if (String.IsNullOrEmpty(x.Name)) + { + returnValue = false; + return; + } + if (collection.Any(y => pi.GetValue(y).ToString().ToLower() == x.Name.ToLower())) + { + returnValue = false; + _notification.ShowError("The name already exists."); + return; + } + returnValue = true; + T newItem = (T)Activator.CreateInstance(typeof(T), new object[] { }); + pi.SetValue(newItem, x.Name); + dbColection.Add(newItem); + }, () => { }); + name = vm.Name; + return returnValue; + } + + private bool EditItemCollection<T>(ObservableCollection<T> collection, DbSet<T> dbColection, ref string name) where T : class + { + AddItemDialogVM vm = ViewModelLocator.AddItemDialogVM; + vm.Name = name; + string currentName = name; + + PropertyInfo pi = typeof(T).GetProperty("Name"); + bool returnValue = false; + _notification.ShowModalDialog<AddItemDialogVM, Views.AddItemDialog>(vm, (x) => + { + if (String.IsNullOrEmpty(x.Name) || currentName == x.Name) + { + returnValue = false; + return; + } + + if (collection.Any(y => pi.GetValue(y).ToString() == x.Name)) + { + returnValue = false; + _notification.ShowError("The name already exists."); + return; + } + returnValue = true; + }, () => { }); + name = vm.Name; + return returnValue; + } + + + private async void AddBrandItem(object obj) + { + string newName = ""; + if( AddItemToCollection( Brands, _active_context.YarnBrands, ref newName)) + { + await _active_context.SaveChangesAsync(); + Brands = _active_context.YarnBrands.ToObservableCollection(); + ActiveRMLExtension.YarnBrand = Brands.FirstOrDefault(b => b.Name == newName); + } + } + + private async void EditBrandItem(object obj) + { + string newName = ActiveRMLExtension.YarnBrand.Name; + if (EditItemCollection(Brands, _active_context.YarnBrands, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnBrand.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddEndUseItem(object ob) + { + string newName = ""; + if (AddItemToCollection(EndUse, _active_context.MediaPurposes, ref newName)) + { + await _active_context.SaveChangesAsync(); + EndUse = _active_context.MediaPurposes.ToObservableCollection(); + ActiveRML.MediaPurpose = EndUse.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditEndUseItem(object ob) + { + string newName = ActiveRML.MediaPurpose.Name; + if (EditItemCollection(EndUse, _active_context.MediaPurposes, ref newName)) + { + ActiveRML.LastUpdated = DateTime.UtcNow; + ActiveRML.MediaPurpose.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddApplicationItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Applications, _active_context.YarnApplications, ref newName)) + { + await _active_context.SaveChangesAsync(); + Applications = _active_context.YarnApplications.ToObservableCollection(); + ActiveRMLExtension.YarnApplication = Applications.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditApplicationItem(object ob) + { + string newName = ActiveRMLExtension.YarnApplication.Name; + if (EditItemCollection(Applications, _active_context.YarnApplications, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnApplication.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddIndustrySectorItem(object ob) + { + string newName = ""; + if (AddItemToCollection(IndustrySector, _active_context.YarnIndustrysectors, ref newName)) + { + await _active_context.SaveChangesAsync(); + IndustrySector = _active_context.YarnIndustrysectors.ToObservableCollection(); + ActiveRMLExtension.YarnIndustrysector = IndustrySector.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditIndustrySectorItem(object ob) + { + string newName = ActiveRMLExtension.YarnIndustrysector.Name; + if (EditItemCollection(IndustrySector, _active_context.YarnIndustrysectors, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnIndustrysector.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddMaterialItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Materials, _active_context.MediaMaterials, ref newName)) + { + await _active_context.SaveChangesAsync(); + Materials = _active_context.MediaMaterials.ToObservableCollection(); + ActiveRML.MediaMaterial = Materials.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditMaterialItem(object ob) + { + string newName = ActiveRML.MediaMaterial.Name; + if (EditItemCollection(Materials, _active_context.MediaMaterials, ref newName)) + { + ActiveRML.LastUpdated = DateTime.UtcNow; + ActiveRML.MediaMaterial.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddYarnTypeItem(object ob) + { + string newName = ""; + if (AddItemToCollection(YarnTypes, _active_context.YarnTypes, ref newName)) + { + await _active_context.SaveChangesAsync(); + YarnTypes = _active_context.YarnTypes.ToObservableCollection(); + ActiveRMLExtension.YarnType = YarnTypes.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditYarnTypeItem(object ob) + { + string newName = ActiveRMLExtension.YarnType.Name; + if (EditItemCollection(YarnTypes, _active_context.YarnTypes, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnType.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddSubFamilyItem(object ob) + { + string newName = ""; + if (AddItemToCollection(SubFamilies, _active_context.YarnSubFamilies, ref newName)) + { + await _active_context.SaveChangesAsync(); + SubFamilies = _active_context.YarnSubFamilies.ToObservableCollection(); + ActiveRMLExtension.YarnSubFamily = SubFamilies.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditSubFamilyItem(object ob) + { + string newName = ActiveRMLExtension.YarnSubFamily.Name; + if (EditItemCollection(SubFamilies, _active_context.YarnSubFamilies, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnSubFamily.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddFamilyItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Family, _active_context.YarnFamilies, ref newName)) + { + await _active_context.SaveChangesAsync(); + Family = _active_context.YarnFamilies.ToObservableCollection(); + ActiveRMLExtension.YarnFamily = Family.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditFamilyItem(object ob) + { + string newName = ActiveRMLExtension.YarnFamily.Name; + if (EditItemCollection(Family, _active_context.YarnFamilies, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnFamily.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddGroupItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Group, _active_context.YarnGroups, ref newName)) + { + await _active_context.SaveChangesAsync(); + Group = _active_context.YarnGroups.ToObservableCollection(); + ActiveRMLExtension.YarnGroup = Group.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditGroupItem(object ob) + { + string newName = ActiveRMLExtension.YarnGroup.Name; + if (EditItemCollection(Group, _active_context.YarnGroups, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnGroup.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddTexturingItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Texturing, _active_context.YarnTexturings, ref newName)) + { + await _active_context.SaveChangesAsync(); + Texturing = _active_context.YarnTexturings.ToObservableCollection(); + ActiveRMLExtension.YarnTexturing = Texturing.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditTexturingItem(object ob) + { + string newName = ActiveRMLExtension.YarnTexturing.Name; + if (EditItemCollection(Texturing, _active_context.YarnTexturings, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnTexturing.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddGeometryItem(object ob) + { + string newName = ""; + if (AddItemToCollection(Geometry, _active_context.FiberShapes, ref newName)) + { + await _active_context.SaveChangesAsync(); + Geometry = _active_context.FiberShapes.ToObservableCollection(); + ActiveRML.FiberShape = Geometry.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditGeometryItem(object ob) + { + string newName = ActiveRML.FiberShape.Name; + if (EditItemCollection(Geometry, _active_context.FiberShapes, ref newName)) + { + ActiveRML.LastUpdated = DateTime.UtcNow; + ActiveRML.FiberShape.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddYarnWhiteShadeItem(object ob) + { + string newName = ""; + if (AddItemToCollection(YarnWhiteShade, _active_context.YarnWhiteShades, ref newName)) + { + await _active_context.SaveChangesAsync(); + YarnWhiteShade = _active_context.YarnWhiteShades.ToObservableCollection(); + ActiveRMLExtension.YarnWhiteShade = YarnWhiteShade.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditYarnWhiteShadeItem(object ob) + { + string newName = ActiveRMLExtension.YarnWhiteShade.Name; + if (EditItemCollection(YarnWhiteShade, _active_context.YarnWhiteShades, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnWhiteShade.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + private async void AddGlossLevelItem(object ob) + { + string newName = ""; + if (AddItemToCollection(GlossLevel, _active_context.YarnGlossLevels, ref newName)) + { + await _active_context.SaveChangesAsync(); + GlossLevel = _active_context.YarnGlossLevels.ToObservableCollection(); + ActiveRMLExtension.YarnGlossLevel = GlossLevel.FirstOrDefault(b => b.Name == newName); + } + } + private async void EditGlossLevelItem(object ob) + { + string newName = ActiveRMLExtension.YarnGlossLevel.Name; + if (EditItemCollection(GlossLevel, _active_context.YarnGlossLevels, ref newName)) + { + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRMLExtension.YarnGlossLevel.Name = newName; + await _active_context.SaveChangesAsync(); + } + } + + #endregion + + + public MainViewVM(INotificationProvider notificationProvider, IAuthenticationProvider authentication, IActionLogManager actionLogManager) + { + _notification = notificationProvider; + _authentication = authentication; + _actionLogManager = actionLogManager; + + BackToThreadExtensionViewsCommand = new RelayCommand(BackToThreadExtensionViews, () => IsFree); + SaveCommand = new RelayCommand(Save, () => IsFree); + ManageRmlExtensionCommand = new RelayCommand(() => LoadActiveRMLExtension(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); + + + AddManufacturerItemCommand = new RelayCommand(AddManufacturerItem); + EditManufacturerItemCommand = new RelayCommand(EditManufacturerItem, () => ActiveRML.Manufacturer != ""); + + AddBrandItemCommand = new RelayCommand(AddBrandItem); + EditBrandItemCommand = new RelayCommand(EditBrandItem, () => ActiveRMLExtension.YarnBrand != null); + + AddEndUseItemCommand = new RelayCommand(AddEndUseItem); + EditEndUseItemCommand = new RelayCommand(EditEndUseItem); + + AddApplicationItemCommand = new RelayCommand(AddApplicationItem); + EditApplicationItemCommand = new RelayCommand(EditApplicationItem); + + AddIndustrySectorItemCommand = new RelayCommand(AddIndustrySectorItem); + EditIndustrySectorItemCommand = new RelayCommand(EditIndustrySectorItem); + + AddMaterialItemCommand = new RelayCommand(AddMaterialItem); + EditMaterialItemCommand = new RelayCommand(EditMaterialItem); + + AddYarnTypeItemCommand = new RelayCommand(AddYarnTypeItem); + EditYarnTypeItemCommand = new RelayCommand(EditYarnTypeItem); + + AddSubFamilyItemCommand = new RelayCommand(AddSubFamilyItem); + EditSubFamilyItemCommand = new RelayCommand(EditSubFamilyItem); + + AddFamilyItemCommand = new RelayCommand(AddFamilyItem); + EditFamilyItemCommand = new RelayCommand(EditFamilyItem); + + AddGroupItemCommand = new RelayCommand(AddGroupItem); + EditGroupItemCommand = new RelayCommand(EditGroupItem); + + AddTexturingItemCommand = new RelayCommand(AddTexturingItem); + EditTexturingItemCommand = new RelayCommand(EditTexturingItem); + + AddGeometryItemCommand = new RelayCommand(AddGeometryItem); + EditGeometryItemCommand = new RelayCommand(EditGeometryItem); + + AddYarnWhiteShadeItemCommand = new RelayCommand(AddYarnWhiteShadeItem); + EditYarnWhiteShadeItemCommand = new RelayCommand(EditYarnWhiteShadeItem); + + AddGlossLevelItemCommand = new RelayCommand(AddGlossLevelItem); + EditGlossLevelItemCommand = new RelayCommand(EditGlossLevelItem); + + } + + + public override void OnApplicationReady() + { + } + + + #region Loading + + private async Task LoadRmlExtentions() + { + var filter = Filter.ToStringOrEmpty().ToLower(); + + try + { + IsFree = false; + + using (_notification.PushTaskItem("Loading RmlExtentions...")) + { + if (_rmlExtentions_context != null) _rmlExtentions_context.Dispose(); + + _rmlExtentions_context = ObservablesContext.CreateDefault(); + + Brands = _rmlExtentions_context.YarnBrands.ToObservableCollection(); + _allUsers = await _rmlExtentions_context.Users.Include(x => x.Contact).ToListAsync(); + var q = (from c in _rmlExtentions_context.Rmls.Where(x => x.Name.ToLower().Contains(filter)) + join p in _rmlExtentions_context.RmlsExtensions on c.Guid equals p.RmlsGuid into ps + from p in ps.DefaultIfEmpty() + select new { RML = c, RMLExtesion = p }).Distinct().ToList().DistinctBy(x => x.RML.Guid) + .Select(x => new RmlExtensionModel() + { + RMLGuid = x.RML.Guid, + Guid = x.RMLExtesion == null? null : x.RMLExtesion.Guid, + Name = x.RML.Name, + Manufacturer = x.RML.Manufacturer, + Brand = x.RMLExtesion == null ? "" : (Brands.Where( y => y.Guid == x.RMLExtesion.YarnBrandGuid).Select( z => z.Name).FirstOrDefault()), + LinearDensity = (int) x.RML.FiberSize, + CreatedBy = x.RMLExtesion == null ? "" : _allUsers.SingleOrDefault(y => y.Guid == x.RMLExtesion.UsersGuid).Contact.FullName, + Created = x.RMLExtesion == null ? DateTime.Now : x.RMLExtesion.Created, + LastUpdated = x.RMLExtesion == null ? DateTime.Now : x.RMLExtesion.LastUpdated, + Status = x.RMLExtesion == null ? RMLExtensionStatus.New : x.RMLExtesion.RMLStatus + }).ToList(); + RmlExtensions = q; + // RmlExtCollectionView = CollectionViewSource.GetDefaultView(RmlExtensions); + // RmlExtCollectionView.SortDescriptions.Add(new SortDescription(nameof(Rml.LastUpdated), ListSortDirection.Ascending)); + + //RmlExtCollectionView.Filter = (rml) => + //{ + // RmlExtensionModel r = rml as RmlExtensionModel; + // return String.IsNullOrWhiteSpace(Filter) + // || r.Name.ToLower().Contains(Filter.ToLower()); + //}; + } + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error loading RMLExtensions.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + private void LoadRmlProperties() + { + Applications = _active_context.YarnApplications.ToObservableCollection(); + Brands = _active_context.YarnBrands.ToObservableCollection(); + YarnWhiteShade = _active_context.YarnWhiteShades.ToObservableCollection(); + EndUse = _active_context.MediaPurposes.ToObservableCollection(); + Family = _active_context.YarnFamilies.ToObservableCollection(); + Geometry = _active_context.FiberShapes.ToObservableCollection(); + GlossLevel = _active_context.YarnGlossLevels.ToObservableCollection(); + Group = _active_context.YarnGroups.ToObservableCollection(); + //Manufacturer = _active_context.YarnManufacturers.ToObservableCollection(); + Manufacturers = _active_context.YarnManufacturers.Select(x => x.Name).ToList(); + Units = _active_context.LinearMassDensityUnits.ToObservableCollection(); + Materials = _active_context.MediaMaterials.ToObservableCollection(); + SubFamilies = _active_context.YarnSubFamilies.ToObservableCollection(); + Texturing = _active_context.YarnTexturings.ToObservableCollection(); + YarnTypes = _active_context.YarnTypes.ToObservableCollection(); + IndustrySector = _active_context.YarnIndustrysectors.ToObservableCollection(); + Machines = ObservablesStaticCollections.Instance.Machines.Select(x => new MachineModel() + { + Guid = x.Guid, + Name = x.Name, + SerialNumber = x.SerialNumber + }).ToObservableCollection(); + + } + + private RmlsExtension GetNewRMLsExtension( string RML_Guid) + { + RmlsExtension rml_extention = new RmlsExtension(); + rml_extention.Created = DateTime.UtcNow; + rml_extention.RmlsGuid = RML_Guid; + rml_extention.UsersGuid = _authentication.CurrentUser.Guid; + //rml_extention.YarnManufacturer = Manufacturer.FirstOrDefault(); + rml_extention.YarnBrand = Brands.FirstOrDefault(); + rml_extention.Country = null; + //rml_extention.YarnEndUse = EndUse.FirstOrDefault(); + rml_extention.YarnApplication = Applications.FirstOrDefault(); + rml_extention.YarnIndustrysector = IndustrySector.FirstOrDefault(); + + //rml_extention.YarnMaterial = Materials.FirstOrDefault(); + rml_extention.YarnType = YarnTypes.FirstOrDefault(); + rml_extention.YarnSubFamily = SubFamilies.FirstOrDefault(); + rml_extention.YarnFamily = Family.FirstOrDefault(); + rml_extention.YarnGroup = Group.FirstOrDefault(); + rml_extention.YarnTexturing = Texturing.FirstOrDefault(); + rml_extention.YarnWhiteShade = YarnWhiteShade.FirstOrDefault(); + rml_extention.YarnGlossLevel = GlossLevel.FirstOrDefault(); + rml_extention.TwistTpm = 0; + rml_extention.YarnTwistDirections = TwistDirections.Unknown; + rml_extention.MinElongation = 0.0; + rml_extention.MaxElongation = 100.0; + rml_extention.MinMaxForceN = 0.0; + rml_extention.MaxMaxForceN = 100.0; + rml_extention.MinElasticity = 0.0; + rml_extention.MaxElasticity = 100.0; + rml_extention.MinTenacity = 0.0; + rml_extention.MaxTenacity = 100.0; + rml_extention.Finishing = "Lubrication"; + rml_extention.RMLStatus = RMLExtensionStatus.New; + + return rml_extention; + } + + private async void LoadActiveRMLExtension(String guid) + { + using (_notification.PushTaskItem("Loading RML Extension...")) + { + try + { + IsFree = false; + + if (_active_context != null) + { + _active_context.Dispose(); + } + + _active_context = ObservablesContext.CreateDefault(); + LoadRmlProperties(); + + if (guid == null) + { + RmlsExtension rml_extention = GetNewRMLsExtension(SelectedRMLExtension.RMLGuid); + _active_context.RmlsExtensions.Add(rml_extention); + await _active_context.SaveChangesAsync(); + guid = rml_extention.Guid; + } + + ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) + .Set(guid) + .WithUser() + .BuildAsync(); + + ActiveRML = new RmlBuilder(_active_context) + .Set(SelectedRMLExtension.RMLGuid) + .Build(); + + var machineIdsHasTest = (from c in _active_context.ColorProcessParameters.Where(x => x.RmlsExtensionsGuid == guid) + select new { MichineGUID = c.MachineGuid }). + Union (from p in _active_context.RmlExtensionTestResults.Where(x => x.RmlsExtensionsGuid == guid) + select new { MichineGUID = p.MachineGuid }).DistinctBy(x => x).ToList(); + + if(machineIdsHasTest.Count > 0) + { + var MachineGuid = machineIdsHasTest.First().MichineGUID; + Machines.Where(x => machineIdsHasTest.Any(y => y.MichineGUID == x.Guid)).ToList().ForEach(x => x.HasRMLTest = true); + SelectedMachine = Machines.First(x => x.Guid == MachineGuid); + } + else + { + var settings = SettingsManager.Default.GetOrCreate<MachineStudioSettings>(); + if(settings.LastVirtualMachineSerialNumber != null) + { + SelectedMachine = Machines.SingleOrDefault(x => x.SerialNumber == settings.LastVirtualMachineSerialNumber); + } + else + { + SelectedMachine = Machines.First(); + } + } + + ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); + ColorParametersVewVM.RMLExtemtionGUID = guid; + ColorParametersVewVM.SelectedMachineGUID = SelectedMachine != null ? SelectedMachine.Guid : null ; + ColorParametersVewVM.RMLGUID = ActiveRML.Guid; + + TestResultsViewVM = new TestResultsViewVM(_notification, _actionLogManager); + TestResultsViewVM.RMLExtemtionGUID = guid; + TestResultsViewVM.RMLGUID = ActiveRML.Guid; + TestResultsViewVM.SelectedMachineGUID = SelectedMachine != null ? SelectedMachine.Guid : null; + TestResultsViewVM.ThreadName = ActiveRML.Manufacturer; + + if (ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) + { + ColorParametersVewVM.SaveColorParameters -= UpdateStatus; + ColorParametersVewVM.SaveColorParameters += UpdateStatus; + TestResultsViewVM.SaveTestResults -= UpdateStatus; + TestResultsViewVM.SaveTestResults += UpdateStatus; + } + + View.NavigateTo(RMLExtensionNavigationView.RMLExtentionView); + + InvalidateRelayCommands(); + + IsFree = true; + } + catch (Exception ex) + { + //LogManager.Log($"Error loading RML '{ActiveRML.Name}'..."); + _notification.ShowError($"Error loading the selected thread.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + } + + private async void RefreshView(String guid, String rmlGuid) + { + try + { + IsFree = false; + + LoadRmlProperties(); + ActiveRML = ActiveRML = await new RmlBuilder(_active_context) + .Set(rmlGuid) + .BuildAsync(); + ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) + .Set(guid) + .WithUser() + .BuildAsync(); + + InvalidateRelayCommands(); + + IsFree = true; + } + catch (Exception ex) + { + //LogManager.Log($"Error loading RML '{ActiveRML.Name}'..."); + _notification.ShowError($"Error refresh after save the selected thread.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + #endregion + + #region event handlers + + private async void UpdateStatus(object sender, EventArgs e) + { + IsFree = false; + + try + { + ColorParametersVewVM.SaveColorParameters -= UpdateStatus; + TestResultsViewVM.SaveTestResults -= UpdateStatus; + ActiveRMLExtension.RMLStatus = RMLExtensionStatus.InProgress; + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + + await _active_context.SaveChangesAsync(); + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error saving Status of RML Extension"); + _notification.ShowError($"An error occurred while trying to save status of the current RML Extension.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + private void SelectedMachineChanged() + { + if(ColorParametersVewVM != null) + { + ColorParametersVewVM.SelectedMachineGUID = SelectedMachine.Guid; + } + } + + #endregion + + #region Save + + /// <summary> + /// Saves this instance. + /// </summary> + private async void Save() + { + IsFree = false; + + try + { + using (_notification.PushTaskItem("Saving RML Extension...")) + { + if(ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) + { + ActiveRMLExtension.RMLStatus = RMLExtensionStatus.InProgress; + ColorParametersVewVM.SaveColorParameters -= UpdateStatus; + TestResultsViewVM.SaveTestResults -= UpdateStatus; + } + + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRML.LastUpdated = DateTime.UtcNow; + + await _active_context.SaveChangesAsync(); + + // _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlSaved, _authentication.CurrentUser, _rmlBeforeSave.Name, _rmlBeforeSave, rmlAfter, "RML saved using Machine Studio."); + + RefreshView(ActiveRMLExtension.Guid, ActiveRML.Guid); + } + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error saving RML Extension of RML{ActiveRML.Name}"); + _notification.ShowError($"An error occurred while trying to save the current RML Extension.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + #endregion + } +} diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultViewVM.cs new file mode 100644 index 000000000..4e7d84e7f --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultViewVM.cs @@ -0,0 +1,201 @@ +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.BL; +using Tango.BL.ActionLogs; +using Tango.BL.DTO; +using Tango.BL.Entities; +using Tango.BL.Enumerations; +using Tango.Core.Commands; +using Tango.MachineStudio.Common.Notifications; +using Tango.SharedUI; + +namespace Tango.MachineStudio.ThreadExtensions.ViewModels +{ + public class TestResultViewVM : ViewModel + { + private INotificationProvider _notification; + private IActionLogManager _actionLogManager; + + #region Properties + + private string _threadName; + /// <summary> + /// Gets or sets the name of the thread. Using in print + /// </summary> + /// <value> + /// The name of the thread. + /// </value> + public string ThreadName + { + get { return _threadName; } + set + { + _threadName = value; + RaisePropertyChangedAuto(); + } + } + + + private bool _isSelected; + /// <summary> + /// Gets or sets a value indicating whether this instance is selected. + /// </summary> + public bool IsSelected + { + get { return _isSelected; } + set { _isSelected = value; RaisePropertyChangedAuto(); } + } + + private RmlExtensionTestResult _testResult; + + public RmlExtensionTestResult TestResult + { + get { return _testResult; } + set { _testResult = value; + RaisePropertyChangedAuto(); + } + } + + + #endregion + public RelayCommand ExportToFileCommand { get; set; } + + public TestResultViewVM(INotificationProvider notification, IActionLogManager actionLogManager) + { + _notification = notification; + _actionLogManager = actionLogManager; + ExportToFileCommand = new RelayCommand(ExportToFile); + } + + #region save + // public void Save(ObservablesContext active_context) + //{ + // try + // { + // IsFree = false; + + // TestResult.LastUpdated = DateTime.UtcNow; + + // var RmlExtensionTestResultAfterChange = RmlExtensionTestResultDTO.FromObservable(TestResult); + + // active_context.SaveChanges(); + // } + // catch (Exception ex) + // { + // LogManager.Log(ex, "Could not update RmlExtension TestResult."); + // _notification.ShowError($"An error occurred while trying to save RmlExtension TestResult.\n{ex.Message}"); + // } + // finally + // { + // IsFree = true; + // } + //} + #endregion + + private void ExportToFile() + { + SaveFileDialog dlg = new SaveFileDialog(); + try + { + dlg.Title = $"Export excel calibration file for {TestResult.Name}"; + dlg.Filter = "Text Files|*.txt"; + dlg.DefaultExt = ".txt"; + dlg.FileName = $"RML_EXTENSION_{TestResult.Name}.txt"; + if (dlg.ShowDialog().Value) + { + using (StreamWriter outputFile = new StreamWriter(dlg.FileName)) + { + outputFile.WriteLine(String.Format($" {TestResult.Name.ToUpper()} ")); + outputFile.WriteLine(""); + outputFile.WriteLine(""); + outputFile.WriteLine(" Dryer temperature"); + outputFile.WriteLine(""); + outputFile.WriteLine(String.Format($" Dryer temperature : {TestResult.DryerTemperature.ToString()}")); + outputFile.WriteLine(String.Format($" Tunnel temperature : {TestResult.TunnelTemperature.ToString()}")); + outputFile.WriteLine(String.Format($" Tunnel flow : {TestResult.TunnelFlow.ToString()}")); + outputFile.WriteLine(String.Format($" Tunnel AVG temperature : {TestResult.TunnelAvgTemperature.ToString()}")); + outputFile.WriteLine(""); + outputFile.WriteLine(""); + outputFile.WriteLine(" Tension through the thread path"); + outputFile.WriteLine(""); + outputFile.WriteLine(String.Format($" Head : {TestResult.TensionHeadMin.ToString()} - {TestResult.TensionHeadMax.ToString()}")); + outputFile.WriteLine(String.Format($" After dryer : {TestResult.TensionAfterDryerMin.ToString()} - {TestResult.TensioinAfterDryerMax.ToString()}")); + outputFile.WriteLine(String.Format($" Winder : {TestResult.BtsrMin.ToString()} - {TestResult.BtsrMax.ToString()}")); + outputFile.WriteLine(String.Format($" BTSR : {TestResult.TensionHeadMin.ToString()} - {TestResult.TensionHeadMax.ToString()}")); + outputFile.WriteLine(String.Format($" Puller tension : {TestResult.PullerTensionMin.ToString()} - {TestResult.PullerTensionMax.ToString()}")); + outputFile.WriteLine(String.Format($" Winder exit tension: {TestResult.ExitTensionMin.ToString()} - {TestResult.ExitTensionMax.ToString()}")); + + outputFile.WriteLine(""); + outputFile.WriteLine(" Rubbing results"); + outputFile.WriteLine(""); + outputFile.WriteLine(" Color DeltaE CIE 100 % GS 100% DeltaETestResult CIE 200 % GS 200% "); + foreach (var rubbingResult in TestResult.RubbingResults) + { + StringBuilder sb = new StringBuilder(); + //sb.Append(" Color: "); + sb.Append($" { rubbingResult.TestResultColor.ToString()} "); + //sb.Append(" DeltaE CIE 100 % : "); + sb.Append($" { rubbingResult.DeltaeCie100.ToString()} "); + //sb.Append(" GS 100% : "); + sb.Append($" { rubbingResult.Gs100Min.ToString()}-{rubbingResult.Gs100Max.ToString()} "); + //sb.Append(" DeltaE CIE 200 % : "); + sb.Append($" { rubbingResult.DeltaeCie200.ToString()} "); + //sb.Append(" GS 200% : "); + sb.Append($" { rubbingResult.Gs200Min.ToString()}-{rubbingResult.Gs200Max.ToString()} "); + outputFile.WriteLine(sb); + } + outputFile.WriteLine(""); + outputFile.WriteLine(" Mechanical properties"); + outputFile.WriteLine(""); + outputFile.WriteLine(" %Color Color Load at Maximum Load(N) STDEV Percentage Strain at Maximum Load STDEV "); + foreach (var result in TestResult.TensileResults) + { + StringBuilder sb = new StringBuilder(); + //sb.Append(" % Color: "); + sb.Append($" { result.ColorPercent.ToString()}"); + //sb.Append(" Color : "); + sb.Append($" { result.TestResultColor.ToString()}"); + //sb.Append(" Load at Maximum Load(N) : "); + sb.Append($" { result.MaxLoad.ToString()}"); + //sb.Append(" STDEV : "); + sb.Append($" { result.StdevMaxLoad.ToString()}"); + //sb.Append(" Percentage Strain at Maximum Load: "); + sb.Append($" {result.StrainMaxLoad.ToString()}"); + //sb.Append(" STDEV : "); + sb.Append($" { result.StdevStrainMaxLoad.ToString()}"); + outputFile.WriteLine(sb); + } + outputFile.WriteLine(""); + outputFile.WriteLine(" Uniformity"); + outputFile.WriteLine(""); + outputFile.WriteLine(String.Format($" Zone1 : {TestResult.SeverityZone1Min.ToString()} - {TestResult.SeverityZone1Max.ToString()}")); + outputFile.WriteLine(String.Format($" Zone2 : {TestResult.SeverityZone2Min.ToString()} - {TestResult.SeverityZone2Max.ToString()}")); + outputFile.WriteLine(""); + outputFile.WriteLine(" COF"); + outputFile.WriteLine(""); + outputFile.WriteLine(" Thread name Lub Version COF Lub amount "); + outputFile.WriteLine(String.Format($" REF {TestResult.RefLubVersion} {TestResult.RefCof.ToString()} {TestResult.RefLub.ToString()}")); + outputFile.WriteLine(String.Format($" {ThreadName} {TestResult.ThreadLubVersion} {TestResult.ThreadCof.ToString()} {TestResult.ThreadLub.ToString()}")); + + outputFile.WriteLine(""); + outputFile.WriteLine(String.Format($" Comments: {TestResult.Comment}")); + outputFile.WriteLine(String.Format($" Conclusion: {TestResult.Conclusions}")); + outputFile.WriteLine(""); + outputFile.Flush(); + } + + } + } + catch (Exception ex) + { + LogManager.Log(ex, "Error exporting excel file " + dlg.FileName); + _notification.ShowError("An error occurred while trying to export the test result data."); + } + } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultsViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultsViewVM.cs new file mode 100644 index 000000000..cc3a49a23 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultsViewVM.cs @@ -0,0 +1,406 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.AutoComplete.Editors; +using Tango.BL; +using Tango.BL.ActionLogs; +using Tango.BL.Builders; +using Tango.BL.DTO; +using Tango.BL.Entities; +using Tango.BL.Enumerations; +using Tango.Core; +using Tango.Core.Commands; +using Tango.Logging; +using Tango.MachineStudio.Common; +using Tango.MachineStudio.Common.Notifications; +using Tango.MachineStudio.ThreadExtensions.Models; +using Tango.Settings; +using Tango.SharedUI; + +namespace Tango.MachineStudio.ThreadExtensions.ViewModels +{ + public class TestResultsViewVM : ViewModel + { + private INotificationProvider _notification; + private IActionLogManager _actionLogManager; + + private ObservablesContext _active_context; + + public event EventHandler SaveTestResults; + + #region Properties + private SynchronizedObservableCollection<RmlExtensionTestResult> _selectedTestResults; + + public SynchronizedObservableCollection<RmlExtensionTestResult> SelectedTestResults + { + get { return _selectedTestResults; } + set { _selectedTestResults = value; } + } + + + private ObservableCollection<TestResultViewVM> _resultTabs; + + public ObservableCollection<TestResultViewVM> ResultTabs + { + get { return _resultTabs; } + set { _resultTabs = value; } + } + + private TestResultViewVM _selectedTab; + /// <summary> + /// Gets or sets the selected tab. + /// </summary> + public TestResultViewVM SelectedTab + { + get { return _selectedTab; } + set + { + _selectedTab = value; + RaisePropertyChangedAuto(); + + foreach (var tab in ResultTabs.Where(x => x != _selectedTab)) + { + tab.IsSelected = false; + } + + if (_selectedTab != null) + { + _selectedTab.IsSelected = true; + } + + //EnableRenderingForSelectedTabGraphs(); + } + } + + protected string _selectedMachineGuid; + /// <summary> + /// Gets or sets the selected machine. + /// </summary> + public String SelectedMachineGUID + { + get { return _selectedMachineGuid; } + set + { + if (value != null && _selectedMachineGuid != value) + { + _selectedMachineGuid = value; + SelectedMachineChanged(); + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); + } + } + } + + private string _RMLExtentionGUID; + + public string RMLExtemtionGUID + { + get { return _RMLExtentionGUID; } + set { _RMLExtentionGUID = value; + OnRMLExtemtionGUIDChanged(); + } + } + + private string _threadName; + + public string ThreadName + { + get { return _threadName; } + set { _threadName = value; + RaisePropertyChangedAuto(); } + } + + private string _RMLGUID; + public string RMLGUID + { + get { return _RMLGUID; } + set + { + _RMLGUID = value; + } + } + + #endregion + + #region Commands + /// <summary> + /// Gets or sets the add tab command. + /// </summary> + public RelayCommand AddTabCommand { get; set; } + + /// <summary> + /// Gets or sets the remove tab command. + /// </summary> + public RelayCommand<TestResultViewVM> RemoveTabCommand { get; set; } + + /// <summary> + /// Gets or sets the rename tab command. + /// </summary> + public RelayCommand RenameTabCommand { get; set; } + + public RelayCommand ApplyToProcessParametersCommand { get; set; } + + public RelayCommand SaveCommand { get; set; } + + #endregion + + public TestResultsViewVM(INotificationProvider notification, IActionLogManager actionLogManager) + { + _notification = notification; + _actionLogManager = actionLogManager; + ResultTabs = new ObservableCollection<TestResultViewVM>(); + + AddTabCommand = new RelayCommand(() => AddNewTab()); + RemoveTabCommand = new RelayCommand<TestResultViewVM>(RemoveTab); + RenameTabCommand = new RelayCommand(RenameTab); + + ApplyToProcessParametersCommand = new RelayCommand(ApplyToProcessParameters); + SaveCommand = new RelayCommand(Save, () => IsFree); + } + + #region Tabs modification + + /// <summary> + /// Removes the specified tab. + /// </summary> + /// <param name="tab">The tab.</param> + private void RemoveTab(TestResultViewVM tab) + { + if (ResultTabs.Count == 1) + return; + if (_notification.ShowQuestion("Are you sure you want to delete the selected tab?")) + { + _active_context.RubbingResults.RemoveRange(tab.TestResult.RubbingResults); + tab.TestResult.RubbingResults = null; + + _active_context.TensileResults.RemoveRange(tab.TestResult.TensileResults); + tab.TestResult.TensileResults = null; + + _active_context.RmlExtensionTestResults.Remove(tab.TestResult); + + ResultTabs.Remove(tab); + SelectedTab = ResultTabs.LastOrDefault(); + _active_context.SaveChanges(); + + } + } + + /// <summary> + /// Adds a new tab. + /// </summary> + private bool AddNewTab(String name = null) + { + if (ResultTabs.Count > 7) + { + //_notification.ShowError("Cannot exceed the maximum number of 8 tabs. You can remove a tab, or create a new project."); + return false; + } + + if (name == null) + { + name = _notification.ShowTextInput("Enter tab name", "Tab Name", "Test"); + } + + if (!String.IsNullOrWhiteSpace(name)) + { + var tab = CreateNewTestResultVM(name, (ResultTabs.Count + 1)); + ResultTabs.Add(tab); + _active_context.RmlExtensionTestResults.Add(tab.TestResult); + SelectedTab = tab; + return true; + } + else + { + return false; + } + } + + /// <summary> + /// Renames the tab. + /// </summary> + /// <param name="tab">The tab.</param> + private void RenameTab() + { + if (SelectedTab != null) + { + var name = _notification.ShowTextInput("Enter tab name", "Tab Name", SelectedTab.TestResult.Name); + + if (!String.IsNullOrWhiteSpace(name)) + { + SelectedTab.TestResult.Name = name; + } + } + } + #endregion + + #region Loading test results + + private void OnRMLExtemtionGUIDChanged() + { + ResultTabs.Clear(); + SelectedTab = null; + } + + private void SelectedMachineChanged() + { + ResultTabs.Clear(); + SelectedTab = null; + LoadTestResults(); + } + public async void LoadTestResults() + { + if (String.IsNullOrEmpty(SelectedMachineGUID)) + { + _notification.ShowWarning(LogManager.Log($" Please, select machine.", LogCategory.Warning)); + return; + } + + try + { + IsFree = false; + if (_active_context != null) + { + _active_context.Dispose(); + } + _active_context = ObservablesContext.CreateDefault(); + ResultTabs.Clear(); + LogManager.Log("Loading selected test results..."); + + using (_notification.PushTaskItem("Loading Test Results Parameters ...")) + { + var testResults = await new RMLExtensionTestResultsCollectionBuilder(_active_context).SetAll().ForRMLExtension(RMLExtemtionGUID).ForMachine(SelectedMachineGUID).WithRubbingAndTensileResults().BuildAsync(); + SelectedTestResults = testResults.OrderBy(x => x.ResultIndex).ToSynchronizedObservableCollection(); + foreach (var result in SelectedTestResults) + { + ResultTabs.Add(new TestResultViewVM(_notification, _actionLogManager) { TestResult = result, ThreadName = ThreadName }); + if (result.ResultIndex == 1) + { + SelectedTab = ResultTabs[ResultTabs.Count - 1]; + } + } + if (ResultTabs.Count == 0) + { + SelectedTab = CreateNewTestResultVM("Untitled", 1); + ResultTabs.Add(SelectedTab); + _active_context.RmlExtensionTestResults.Add(SelectedTab.TestResult); + await _active_context.SaveChangesAsync(); + } + } + IsFree = true; + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error loading TestResults.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + private TestResultViewVM CreateNewTestResultVM(string name, int index) + { + TestResultViewVM newtab = new TestResultViewVM(_notification, _actionLogManager) { ThreadName = ThreadName }; + newtab.TestResult = new RmlExtensionTestResult() { RmlsExtensionsGuid = RMLExtemtionGUID, MachineGuid = SelectedMachineGUID, ResultIndex = index, Name = name, BtsrMax = 0.0, BtsrMin = 0.0, DryerTemperature = 0, TunnelTemperature = 0, TunnelFlow = 0.0, TunnelAvgTemperature = 0.0, TensionHeadMax = 0.0, + TensionHeadMin = 0.0, TensioinAfterDryerMax = 0.0, TensionAfterDryerMin = 0.0, TensionWinderMax = 0.0, TensionWinderMin = 0.0, PullerTensionMax = 0.0, PullerTensionMin = 0.0, ExitTensionMax = 0.0, ExitTensionMin = 0.0, SeverityZone1Max = 0.0, SeverityZone1Min = 0.0, SeverityZone2Max = 0.0, SeverityZone2Min = 0.0, + RefLubVersion="", RefCof = 0.0, RefLub = 0.0, ThreadLubVersion = "", ThreadCof = 0.0, ThreadLub = 0.0, Conclusions="", Comment=""}; + var rubbingresults = new SynchronizedObservableCollection<RubbingResult>(); + rubbingresults.Add(new RubbingResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.CYAN }); + rubbingresults.Add(new RubbingResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.MAGENTA }); + rubbingresults.Add(new RubbingResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.YELLOW }); + rubbingresults.Add(new RubbingResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.BLACK }); + newtab.TestResult.RubbingResults = rubbingresults; + + var tensileresults = new SynchronizedObservableCollection<TensileResult>(); + tensileresults.Add(new TensileResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.CYAN, ColorPercent = 100 }); + tensileresults.Add(new TensileResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.BLACK, ColorPercent = 100 }); + tensileresults.Add(new TensileResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.CYAN, ColorPercent = 200 }); + tensileresults.Add(new TensileResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.BLACK, ColorPercent = 200 }); + tensileresults.Add(new TensileResult() { RmlExtensionTestResultsGuid = newtab.TestResult.Guid, TestResultColor = TestResultColors.WHITE, ColorPercent = null }); + newtab.TestResult.TensileResults = tensileresults; + + return newtab; + } + + #endregion + #region Save + + public async void ApplyToProcessParameters() + { + try { + if (RMLGUID == null) + return; + + using (var context = ObservablesContext.CreateDefault()) + { + var rml = await new RmlBuilder(context) + .Set(RMLGUID) + .WithActiveParametersGroup() + .BuildAsync(); + if (rml == null || rml.ProcessParametersTablesGroups.ToList().Count == 0) + { + _notification.ShowError("Could not save process parameters an RML with no process group."); + return; + } + + var activeProcessParametersGroup = rml.ProcessParametersTablesGroups.ToList().SingleOrDefault(x => x.Active); + if(activeProcessParametersGroup != null) + { + + var processParametersTables = activeProcessParametersGroup.ProcessParametersTables.OrderBy(x => x.TableIndex).ToSynchronizedObservableCollection().FirstOrDefault(); + processParametersTables.DryerZone1Temp = SelectedTab.TestResult.DryerTemperature == null? 0 : (double)SelectedTab.TestResult.DryerTemperature; + processParametersTables.RBlowerFlow = SelectedTab.TestResult.TunnelFlow == null ? 0 : (double)SelectedTab.TestResult.TunnelFlow; + processParametersTables.RBlowerTemp = SelectedTab.TestResult.TunnelFlow == null ? 0 : (double)SelectedTab.TestResult.TunnelFlow; ; + processParametersTables.LBlowerFlow = SelectedTab.TestResult.TunnelTemperature == null ? 0 : (double)SelectedTab.TestResult.TunnelTemperature; ; + processParametersTables.LBlowerTemp = SelectedTab.TestResult.TunnelTemperature == null ? 0 : (double)SelectedTab.TestResult.TunnelTemperature; ; + await context.SaveChangesAsync(); + } + } + } + catch(Exception ex) + { + LogManager.Log(ex, "Could not save process parameters."); + _notification.ShowError($"An error occurred while trying to save process parameters.\n{ex.Message}"); + } + } + + public async void Save() + { + if (String.IsNullOrEmpty(SelectedMachineGUID)) + { + _notification.ShowWarning(LogManager.Log($"Could not save Test Results. Please, select machine.", LogCategory.Warning)); + return; + } + try + { + IsFree = false; + await Task.Factory.StartNew(() => + { + foreach (var tab in ResultTabs) + { + tab.TestResult.LastUpdated = DateTime.UtcNow; + } + _active_context.SaveChanges(); + }); + + LoadTestResults(); + } + catch (Exception ex) + { + LogManager.Log(ex, "Could not save test results."); + _notification.ShowError($"An error occurred while trying to save test results.\n{ex.Message}"); + } + finally + { + IsFree = true; + EventHandler handler = SaveTestResults; + handler?.Invoke(this, new EventArgs()); + } + } + + #endregion + } +} |
