diff options
| author | Victoria Plitt <Victoria.Plitt@twine-s.com> | 2021-07-04 15:25:08 +0300 |
|---|---|---|
| committer | Victoria Plitt <Victoria.Plitt@twine-s.com> | 2021-07-04 15:25:08 +0300 |
| commit | 8a0b8f6abe3d143b43131a330e0ee39c2547ce8f (patch) | |
| tree | 7178cbe758b1adefb37c53be6839446e18d9d791 /Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels | |
| parent | b29f337cff7513e0fe0e4b98e6bc7970da89e837 (diff) | |
| download | Tango-8a0b8f6abe3d143b43131a330e0ee39c2547ce8f.tar.gz Tango-8a0b8f6abe3d143b43131a330e0ee39c2547ce8f.zip | |
After Virus
Diffstat (limited to 'Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels')
4 files changed, 1152 insertions, 499 deletions
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 index b2e677339..ae90263d2 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/ColorParametersVewVM.cs +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/ColorParametersVewVM.cs @@ -21,6 +21,11 @@ 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 { @@ -28,10 +33,10 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels { private INotificationProvider _notification; private IActionLogManager _actionLogManager; - + private ObservablesContext _active_context; - private ObservablesContext _machineDbContext; - // private ColorProcessParameterDTO _hwBeforeSave; + + public event EventHandler SaveColorParameters; #region Properties @@ -48,7 +53,7 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels RaisePropertyChangedAuto(); } } - + private ObservableCollection<ColorProcessData> _magentaProcessData; public ObservableCollection<ColorProcessData> MagentaProcessData { @@ -76,7 +81,7 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels RaisePropertyChangedAuto(); } } - + private ObservableCollection<ColorProcessData> _yellowProcessData; public ObservableCollection<ColorProcessData> YellowProcessData { @@ -167,7 +172,8 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels public PlotProperties CyanPlot { get { return _cyanPlot; } - set { + set + { _cyanPlot = value; RaisePropertyChangedAuto(); } @@ -196,23 +202,32 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels get { return _blackPlot; } set { _blackPlot = value; } } - /// <summary> - /// Gets or sets the machines providers. - /// </summary> - public ISuggestionProvider MachinesProvider { get; set; } - protected Machine _selectedMachine; + private string _RMLExtentionGUID; + + public string RMLExtemtionGUID + { + get { return _RMLExtentionGUID; } + set + { + _RMLExtentionGUID = value; + OnRMLExtensionGUIDChanged(); + } + } + + protected string _selectedMachineGuid; /// <summary> /// Gets or sets the selected machine. /// </summary> - public Machine SelectedMachine + public String SelectedMachineGUID { - get { return _selectedMachine; } + get { return _selectedMachineGuid; } set { - if (value != null && _selectedMachine != value) + if (value != null && _selectedMachineGuid != value) { - _selectedMachine = value; + _selectedMachineGuid = value; + SelectedMachineChanged(); RaisePropertyChangedAuto(); InvalidateRelayCommands(); } @@ -229,25 +244,27 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels public bool IsViewLoaded { get { return _isViewLoaded; } - set { - if(_isViewLoaded != value) + set + { + if (_isViewLoaded != value) { _isViewLoaded = value; } } } - - private Dictionary<string, ColorProcessData> _removedColorProcessDataBeforeSave; - - public Dictionary<string, ColorProcessData> RemovedColorProcessDataBeforeSave - { - get { return _removedColorProcessDataBeforeSave; } - set { _removedColorProcessDataBeforeSave = 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<FactorColors> FlytoRMLLiquidFactorsCommand { get; set; } + public RelayCommand ImportCyanDataCommand { get; set; } public RelayCommand ImportMagentaDataCommand { get; set; } public RelayCommand ImportYellowDataCommand { get; set; } @@ -259,9 +276,10 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels if (LoadColorDataFromExcel(out items) && items != null) { MagentaProcessData.Clear(); - items.ForEach(x => MagentaProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid})); + 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("MAGENTA"); + UpdateFactorsOnChangeProcessData(FactorColors.MAGENTA); } } @@ -271,9 +289,10 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels if (LoadColorDataFromExcel(out items) && items != null) { YellowProcessData.Clear(); - items.ForEach(x => YellowProcessData.Add(new ColorProcessData() { InkNlCm = x.NlCm, L = x.L, A = x.A, B = x.B, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid})); + 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("YELLOW"); + UpdateFactorsOnChangeProcessData(FactorColors.YELLOW); } } @@ -283,21 +302,28 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels 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("CYAN"); + UpdateFactorsOnChangeProcessData(FactorColors.CYAN); } } + private void FlytoRMLLiquidFactors(FactorColors obj) + { + throw new NotImplementedException(); + } + 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("BLACK"); + UpdateFactorsOnChangeProcessData(FactorColors.BLACK); } } @@ -336,19 +362,8 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels _notification = notification; _actionLogManager = actionLogManager; _isViewLoaded = false; - RemovedColorProcessDataBeforeSave = new Dictionary<string, ColorProcessData>(); + RemovedColorProcessDataBeforeSave = new List<string>(); - MachinesProvider = new SuggestionProvider((filter) => - { - try - { - return _machineDbContext.Machines.Where(x => x.SerialNumber.StartsWith(filter)).ToList(); - } - catch - { - return null; - } - }); CyanProcessData = new ObservableCollection<ColorProcessData>(); CyanProcessData.CollectionChanged += OnCyanCollectionChanged; @@ -362,115 +377,125 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels BlackProcessData = new ObservableCollection<ColorProcessData>(); BlackProcessData.CollectionChanged += OnBlackCollectionChanged; - CyanPlot = new PlotProperties("CYAN"); - YellowPlot = new PlotProperties("YELLOW"); - MagentaPlot = new PlotProperties("MAGENTA"); - BlackPlot = new PlotProperties("BLACK"); - + 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); + + FlytoRMLLiquidFactorsCommand = new RelayCommand<FactorColors>(FlytoRMLLiquidFactors, () => IsFree); } + #region Loading - public async void LoadColorParameters(string RMLExtemtionGUID) + 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(); } - if (_machineDbContext != null) - { - _machineDbContext.Dispose(); - } - - - LogManager.Log("Initializing machine Db context..."); - - _machineDbContext = ObservablesContext.CreateDefault(); - _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).FirstOrDefault(); - if(currentcolorProcessParameter != null) + + 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(); + SelectedColorProcessParameter = new ColorProcessParametersBuilder(_active_context).Set(currentcolorProcessParameter.Guid).WithColorProcessData().WithColorProcessFactor().Build(); } - + if (SelectedColorProcessParameter == null) { - SelectedColorProcessParameter = new ColorProcessParameter() { RmlsExtensionsGuid = RMLExtemtionGUID }; + SelectedColorProcessParameter = new ColorProcessParameter() { RmlsExtensionsGuid = RMLExtemtionGUID, MachineGuid = SelectedMachineGUID }; SelectedColorProcessParameter.WhitePointL = 0.0; SelectedColorProcessParameter.WhitePointA = 0.0; SelectedColorProcessParameter.WhitePointB = 0.0; - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "CYAN", FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "MAGENTA", FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "YELLOW", FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "BLACK", FactorPercent = 100, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "CYAN", FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "MAGENTA", FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "YELLOW", FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "BLACK", FactorPercent = 200, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "CYAN", FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "MAGENTA", FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "YELLOW", FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "BLACK", FactorPercent = 1, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "CYAN", FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "MAGENTA", FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "YELLOW", FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); - SelectedColorProcessParameter.ColorProcessFactor.Add(new ColorProcessFactor() { ColorName = "BLACK", FactorPercent = 1111, ColorProcessParametersGuid = SelectedColorProcessParameter.Guid }); + 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.ColorProcessFactor.Where(x => x.FactorPercent == 100).ToObservableCollection(); + Factor100ProcessData = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 100).ToObservableCollection(); - Factor200ProcessData = SelectedColorProcessParameter.ColorProcessFactor.Where(x => x.FactorPercent == 200).ToObservableCollection(); + Factor200ProcessData = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 200).ToObservableCollection(); - MinInkUptake = SelectedColorProcessParameter.ColorProcessFactor.Where(x => x.FactorPercent == 1).ToObservableCollection(); + MinInkUptake = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 1).ToObservableCollection(); - MaxInkUptake = SelectedColorProcessParameter.ColorProcessFactor.Where(x => x.FactorPercent == 1111).ToObservableCollection(); + MaxInkUptake = SelectedColorProcessParameter.ColorProcessFactors.Where(x => x.FactorPercent == 1111).ToObservableCollection(); RemovedColorProcessDataBeforeSave.Clear(); - var cyanDataList = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "CYAN").ToList().OrderBy(x => x.InkNlCm ).ToList(); + var cyanDataList = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == FactorColors.CYAN).ToList().OrderBy(x => x.InkNlCm).ToList(); CyanProcessData.Clear(); - cyanDataList.ForEach( y => CyanProcessData.Add(y)); + cyanDataList.ForEach(y => CyanProcessData.Add(y)); - var magentaDatalist = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "MAGENTA").ToList().OrderBy(x => x.InkNlCm).ToList(); ; + 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.ColorName == "YELLOW").ToList().OrderBy(x => x.InkNlCm).ToList(); ; + 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.ColorName == "BLACK").ToList().OrderBy(x => x.InkNlCm).ToList(); ; + 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.ColorProcessFactor.ToList().ForEach(x => UpdateFactorsOnChangeProcessData(x.ColorName)); + SelectedColorProcessParameter.ColorProcessFactors.ToList().ForEach(x => UpdateFactorsOnChangeProcessData(x.FactorColor)); + } + + private void OnRMLExtensionGUIDChanged() + { + SelectedColorProcessParameter = null; } + private void SelectedMachineChanged() + { + SelectedColorProcessParameter = null; + LoadColorParameters(); + } #endregion #region Update Plot @@ -488,83 +513,21 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels private void OnCyanCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Reset) - { - var cyanProcessData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "CYAN").ToObservableCollection(); - foreach (ColorProcessData item in cyanProcessData) - { - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - item.PropertyChanged -= CyanMeasurementModelPropertyChanged; - } - // UpdateFactorsOnChangeProcessData("Cyan"); - } - else if (e.Action == NotifyCollectionChangedAction.Remove) - { - foreach (ColorProcessData item in e.OldItems) - { - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - item.PropertyChanged -= CyanMeasurementModelPropertyChanged; - } - UpdateFactorsOnChangeProcessData("CYAN"); - } - else if (e.Action == NotifyCollectionChangedAction.Add) - { - foreach (ColorProcessData item in e.NewItems) - { - item.ColorName = "CYAN"; - item.ColorProcessParametersGuid = SelectedColorProcessParameter.Guid; - SelectedColorProcessParameter.ColorProcessData.Add(item); - RemovedColorProcessDataBeforeSave.Remove(item.Guid); - item.PropertyChanged += CyanMeasurementModelPropertyChanged; - } - } + OnColorCollectionChange(e, FactorColors.CYAN, CyanMeasurementModelPropertyChanged); } private void CyanMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) { - if(IsFree) + if (IsFree) { CyanPlot.CreateGraph(CyanProcessData.ToList(), true); - UpdateFactorsOnChangeProcessData("CYAN"); + UpdateFactorsOnChangeProcessData(FactorColors.CYAN); } } - + private void OnMagentaCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Reset) - { - var magentaProcessData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "MAGENTA").ToObservableCollection(); - foreach (ColorProcessData item in magentaProcessData) - { - item.PropertyChanged -= MagentaMeasurementModelPropertyChanged; - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - } - // UpdateFactorsOnChangeProcessData("Magenta"); - } - else if (e.Action == NotifyCollectionChangedAction.Remove) - { - foreach (ColorProcessData item in e.OldItems) - { - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - item.PropertyChanged -= MagentaMeasurementModelPropertyChanged; - } - UpdateFactorsOnChangeProcessData("MAGENTA"); - } - else if (e.Action == NotifyCollectionChangedAction.Add) - { - foreach (ColorProcessData item in e.NewItems) - { - item.ColorName = "MAGENTA"; - item.ColorProcessParametersGuid = SelectedColorProcessParameter.Guid; - SelectedColorProcessParameter.ColorProcessData.Add(item); - RemovedColorProcessDataBeforeSave.Remove(item.Guid); - item.PropertyChanged += MagentaMeasurementModelPropertyChanged; - } - } + OnColorCollectionChange(e, FactorColors.MAGENTA, MagentaMeasurementModelPropertyChanged); } private void MagentaMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) @@ -572,44 +535,13 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels if (IsFree) { MagentaPlot.CreateGraph(MagentaProcessData.ToList(), true); - UpdateFactorsOnChangeProcessData("MAGENTA"); + UpdateFactorsOnChangeProcessData(FactorColors.MAGENTA); } } private void OnYellowCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Reset) - { - var yellowProcessData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "YELLOW").ToObservableCollection(); - foreach (ColorProcessData item in yellowProcessData) - { - item.PropertyChanged -= YellowMeasurementModelPropertyChanged; - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - } - //UpdateFactorsOnChangeProcessData("Yellow"); - } - else if (e.Action == NotifyCollectionChangedAction.Remove) - { - foreach (ColorProcessData item in e.OldItems) - { - SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - item.PropertyChanged -= YellowMeasurementModelPropertyChanged; - } - UpdateFactorsOnChangeProcessData("YELLOW"); - } - else if (e.Action == NotifyCollectionChangedAction.Add) - { - foreach (ColorProcessData item in e.NewItems) - { - item.ColorName = "YELLOW"; - item.ColorProcessParametersGuid = SelectedColorProcessParameter.Guid; - SelectedColorProcessParameter.ColorProcessData.Add(item); - RemovedColorProcessDataBeforeSave.Remove(item.Guid); - item.PropertyChanged += YellowMeasurementModelPropertyChanged; - } - } + OnColorCollectionChange(e, FactorColors.YELLOW, YellowMeasurementModelPropertyChanged); } private void YellowMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) @@ -617,56 +549,58 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels if (IsFree) { YellowPlot.CreateGraph(YellowProcessData.ToList(), false); - UpdateFactorsOnChangeProcessData("YELLOW"); + UpdateFactorsOnChangeProcessData(FactorColors.YELLOW); } } - + private void OnBlackCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if(e.Action == NotifyCollectionChangedAction.Reset) + 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 blackProcessData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName == "BLACK").ToObservableCollection(); - foreach (ColorProcessData item in blackProcessData) + var processData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.FactorColor == color).ToObservableCollection(); + + foreach (ColorProcessData item in processData) { - item.PropertyChanged -= BlackMeasurementModelPropertyChanged; + item.PropertyChanged -= eventHandler; SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; } - //UpdateFactorsOnChangeProcessData("Black"); + //UpdateFactorsOnChangeProcessData(color); } else if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (ColorProcessData item in e.OldItems) { SelectedColorProcessParameter.ColorProcessData.Remove(item); - RemovedColorProcessDataBeforeSave[item.Guid] = item; - item.PropertyChanged -= BlackMeasurementModelPropertyChanged; + item.PropertyChanged -= eventHandler; + RemovedColorProcessDataBeforeSave.Add(item.Guid); } - UpdateFactorsOnChangeProcessData("BLACK"); + UpdateFactorsOnChangeProcessData(color); } else if (e.Action == NotifyCollectionChangedAction.Add) { foreach (ColorProcessData item in e.NewItems) { - item.ColorName = "BLACK"; + item.FactorColor = color; item.ColorProcessParametersGuid = SelectedColorProcessParameter.Guid; SelectedColorProcessParameter.ColorProcessData.Add(item); - RemovedColorProcessDataBeforeSave.Remove(item.Guid); - item.PropertyChanged += BlackMeasurementModelPropertyChanged; + item.PropertyChanged += eventHandler; } - - } - } - - private void BlackMeasurementModelPropertyChanged(object sender, PropertyChangedEventArgs e) - { - if (IsFree) - { - BlackPlot.CreateGraph(BlackProcessData.ToList(), true); - UpdateFactorsOnChangeProcessData("BLACK"); } } - #endregion #region update factors @@ -676,100 +610,155 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels /// </summary> /// <param name="factor">The factor.</param> /// <param name="item">The item.</param> - private void UpdateFactor(ColorProcessFactor factor, ColorProcessData item) + private void UpdateFactor(ColorProcessFactor factor, DataPoint point) { if (factor == null) return; - if (item == null) + if (point.X == 0) { factor.InkNlCm = 0; factor.L = factor.A = factor.B = 0.0; return; } - factor.InkNlCm = item.InkNlCm; - factor.L = item.L; - factor.A = item.A; - factor.B = item.B; + 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(string color) + private void UpdateFactorsOnChangeProcessData(FactorColors color) { - bool isLtype = color.ToLower() == "yellow" ? false : true; - var processData = SelectedColorProcessParameter.ColorProcessData.Where(x => x.ColorName.ToLower() == color.ToLower()).ToObservableCollection(); + 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; - ColorProcessData minInk = null; - ColorProcessData maxInk = null; + //ColorProcessData closest100 = null; + //ColorProcessData closest200 = null; - var minDifference100 = double.MaxValue; - var minDifference200 = double.MaxValue; + //var minDifference100 = double.MaxValue; + //var minDifference200 = double.MaxValue; if (processData.Count == 0) return; - foreach (var item in processData) + //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 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; - } - if (minInk == null || minInk.InkNlCm > item.InkNlCm) + 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)) { - minInk = item; - } - if (maxInk == null || maxInk.InkNlCm < item.InkNlCm) - { - maxInk = item; + calculatedX = CalculateXValue(factor, new DataPoint(prevItem.InkNlCm, prevItem.L), new DataPoint(item.InkNlCm, item.L)); + break; + } + prevItem = item; } - UpdateFactor(Factor100ProcessData.FirstOrDefault(x => x.ColorName == color), closest100); - UpdateFactor(Factor200ProcessData.FirstOrDefault(x => x.ColorName == color), closest200); - UpdateFactor(MinInkUptake.FirstOrDefault(x => x.ColorName == color), minInk); - UpdateFactor(MaxInkUptake.FirstOrDefault(x => x.ColorName == color), maxInk); + + 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; - await Task.Factory.StartNew(() => - { - SelectedColorProcessParameter.LastUpdated = DateTime.UtcNow; - var colorProcessParameterAfterChange = ColorProcessParameterDTO.FromObservable(SelectedColorProcessParameter); + SelectedColorProcessParameter.LastUpdated = DateTime.UtcNow; - foreach (KeyValuePair<string, ColorProcessData> item in RemovedColorProcessDataBeforeSave) + foreach (var item in RemovedColorProcessDataBeforeSave) + { + var existingColorProcessData = await _active_context.ColorProcessData.FirstOrDefaultAsync(y => y.Guid == item); + if (existingColorProcessData != null) { - var existingColorProcessData = _active_context.ColorProcessData.FirstOrDefault(y => y.Guid == item.Value.Guid); - if (existingColorProcessData != null) - { - _active_context.ColorProcessData.Remove(existingColorProcessData); - } + _active_context.ColorProcessData.Remove(existingColorProcessData); } - _active_context.SaveChanges(); - - }); - LoadColorParameters(SelectedColorProcessParameter.RmlsExtensionsGuid); + } + 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) { @@ -779,9 +768,11 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels 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 index 3fde7abbe..09befb26f 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/MainViewVM.cs +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/MainViewVM.cs @@ -25,6 +25,8 @@ 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; namespace Tango.MachineStudio.ThreadExtensions.ViewModels { @@ -33,34 +35,55 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels private INotificationProvider _notification; private IAuthenticationProvider _authentication; private IActionLogManager _actionLogManager; - private RmlsExtensionDTO _rmlExtensionBeforeSave; - + private ObservablesContext _rmlExtentions_context; private ObservablesContext _active_context; + private List<User> _allUsers; + #region properties - private ObservableCollection<RmlsExtension> _rmlsExtension; - public ObservableCollection<RmlsExtension> RmlsExtensions + //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 _rmlsExtension; } - set { _rmlsExtension = value; + get { return _rmlExtensions; } + set { _rmlExtensions = value; RaisePropertyChangedAuto(); } } - - private RmlsExtension _activeRMLExtention; - public RmlsExtension ActiveRMLExtention + private RmlsExtension _ActiveRMLExtension; + public RmlsExtension ActiveRMLExtension { - get { return _activeRMLExtention; } - set { _activeRMLExtention = value; + get { return _ActiveRMLExtension; } + set { _ActiveRMLExtension = value; RaisePropertyChangedAuto(); } } - private RmlsExtension _selectedRMLExtension; - public RmlsExtension SelectedRMLExtension + 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(); } + set { _selectedRMLExtension = value; + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); } } private ICollectionView _rmlExtCollectionView; @@ -91,20 +114,26 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels set { _brands = value; RaisePropertyChangedAuto(); } } - private ObservableCollection<YarnColor> _yarnColor; - public ObservableCollection<YarnColor> YarnColor + private ObservableCollection<YarnWhiteShade> _yarnWhiteShade; + public ObservableCollection<YarnWhiteShade> YarnWhiteShade { - get { return _yarnColor; } - set { _yarnColor = value; RaisePropertyChangedAuto(); } + get { return _yarnWhiteShade; } + set { _yarnWhiteShade = value; RaisePropertyChangedAuto(); } } - - private ObservableCollection<YarnEndUse> _enduse; - public ObservableCollection<YarnEndUse> EndUse + 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 { @@ -112,8 +141,8 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels set { _family = value; RaisePropertyChangedAuto(); } } - private ObservableCollection<YarnGeometry> _geometry; - public ObservableCollection<YarnGeometry> Geometry + private ObservableCollection<FiberShape> _geometry; + public ObservableCollection<FiberShape> Geometry { get { return _geometry; } set { _geometry = value; RaisePropertyChangedAuto(); } @@ -133,20 +162,30 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels set { _group = value; RaisePropertyChangedAuto(); } } - private ObservableCollection<YarnManufacturer> _manufacturer; - public ObservableCollection<YarnManufacturer> Manufacturer + //private ObservableCollection<YarnManufacturer> _manufacturer; + //public ObservableCollection<YarnManufacturer> Manufacturer + //{ + // get { return _manufacturer; } + // set { _manufacturer = value; RaisePropertyChangedAuto(); } + //} + private List<String> _manufacturers; + + public List<String> Manufacturers { - get { return _manufacturer; } - set { _manufacturer = value; RaisePropertyChangedAuto(); } + get { return _manufacturers; } + set { _manufacturers = value; + RaisePropertyChangedAuto(); + } } - private ObservableCollection<YarnMaterial> _materials; - public ObservableCollection<YarnMaterial> Materials + + private ObservableCollection<MediaMaterial> _materials; + public ObservableCollection<MediaMaterial> Materials { get { return _materials; } set { _materials = value; RaisePropertyChangedAuto(); } } - + private ObservableCollection<YarnSubFamily> _subFamilies; public ObservableCollection<YarnSubFamily> SubFamilies { @@ -185,9 +224,9 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels set { _Filter = value; RaisePropertyChangedAuto(); OnFilterChanged(); } } - private void OnFilterChanged() + private async void OnFilterChanged() { - RmlExtCollectionView.Refresh(); + await LoadRmlExtentions(); } private ColorParametersVewVM _colorParametersVewVM; @@ -196,98 +235,70 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels get { return _colorParametersVewVM; } set { _colorParametersVewVM = value; RaisePropertyChangedAuto(); } } - #endregion - #region commands - - public RelayCommand SaveCommand { get; set; } - - public RelayCommand ManageRmlExtensionCommand { get; set; } - - public RelayCommand AddRmlExtCommand { get; set; } - - public RelayCommand RemoveRmlExtensionCommand { get; set; } - - public RelayCommand CloneRmlExtensionCommand { get; set; } - - public RelayCommand BackToThreadExtensionViewsCommand { get; set; } - - - private void BackToThreadExtensionViews(object obj) + private TestResultsViewVM _testResultsViewVM; + public TestResultsViewVM TestResultsViewVM { - View.NavigateTo(ThreadExtensionNavigationView.ThreadExtensionsView); - LoadRmlExtentions(); + get { return _testResultsViewVM; } + set { _testResultsViewVM = value; RaisePropertyChangedAuto(); } } - private async void CloneSelectedRmlExtension(object obj) + protected Machine _selectedMachine; + /// <summary> + /// Gets or sets the selected machine. + /// </summary> + public Machine SelectedMachine { - using (_notification.PushTaskItem("Cloning thread...")) + get { return _selectedMachine; } + set { - try + if (value != null && _selectedMachine != value) { - IsFree = false; - - using (var context = ObservablesContext.CreateDefault()) - { - RmlsExtension rml_extention = await new RmlExtensionsBuilder(_rmlExtentions_context).Set(SelectedRMLExtension.Guid).WithUser().BuildAsync(); - - RmlsExtension cloned = new RmlsExtension(); - rml_extention.MapPropertiesTo(cloned, MappingFlags.NoReferenceTypes); - - cloned.Guid = Guid.NewGuid().ToString(); - cloned.ID = 0; - - - context.RmlsExtensions.Add(cloned); - await context.SaveChangesAsync(); - - //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlCreated, _authentication.CurrentUser, cloned.Name, cloned, "RML cloned from Machine Studio."); - } - - LoadRmlExtentions(); - } - catch (Exception ex) - { - LogManager.Log(ex, "Error cloning thread."); - _notification.ShowError($"An error occurred while trying to clone the selected thread\n{ex.Message}"); - } - finally - { - IsFree = true; + _selectedMachine = value; + SelectedMachineChanged(); + RaisePropertyChangedAuto(); + InvalidateRelayCommands(); } } } - private async void RemoveRmlExtension(object obj) + private ObservableCollection<MachineModel> _machines; + /// <summary> + /// Gets or sets the Machines. + /// </summary> + public ObservableCollection<MachineModel> Machines { - if (_notification.ShowQuestion(" Are you sure you want to delete the selected RML Extension?")) + get { - using (_notification.PushTaskItem("Removing RML Extension...")) - { - try - { - IsFree = false; - - await SelectedRMLExtension.DeleteCascadeAsync(_rmlExtentions_context); - //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlDeleted, _authentication.CurrentUser, SelectedRML.Name, SelectedRML, "RML deleted from Machine Studio."); + return _machines; + } - LoadRmlExtentions(); - } - catch (Exception ex) - { - LogManager.Log(ex, $"Error removing selected RML {SelectedRMLExtension?.Name}."); - _notification.ShowError($"An error occurred while trying to remove the selected RML Extension.\n{ex.FlattenMessage()}"); - LoadRmlExtentions(); - } - finally - { - IsFree = true; - } - } + 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(); } + #endregion + public MainViewVM(INotificationProvider notificationProvider, IAuthenticationProvider authentication, IActionLogManager actionLogManager) { _notification = notificationProvider; @@ -296,21 +307,20 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels BackToThreadExtensionViewsCommand = new RelayCommand(BackToThreadExtensionViews, () => IsFree); SaveCommand = new RelayCommand(Save, () => IsFree); - ManageRmlExtensionCommand = new RelayCommand(() => LoadActiveRMLExtention(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); - RemoveRmlExtensionCommand = new RelayCommand(RemoveRmlExtension, () => SelectedRMLExtension != null); - CloneRmlExtensionCommand = new RelayCommand(CloneSelectedRmlExtension, () => SelectedRMLExtension != null); - AddRmlExtCommand = new RelayCommand(AddNewRmlExtention); + ManageRmlExtensionCommand = new RelayCommand(() => LoadActiveRMLExtension(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); } public override void OnApplicationReady() { - LoadRmlExtentions(); } + #region Loading - private async void LoadRmlExtentions() + private async Task LoadRmlExtentions() { + var filter = Filter.ToStringOrEmpty().ToLower(); + try { IsFree = false; @@ -320,19 +330,36 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels if (_rmlExtentions_context != null) _rmlExtentions_context.Dispose(); _rmlExtentions_context = ObservablesContext.CreateDefault(); - RmlsExtensions = await new RMLExtentionsCollectionBuilder(_rmlExtentions_context).SetAll().WithUser().WithYarnProperties().BuildAsync(); - - RmlExtCollectionView = CollectionViewSource.GetDefaultView(RmlsExtensions); - RmlExtCollectionView.SortDescriptions.Add(new SortDescription(nameof(Rml.LastUpdated), ListSortDirection.Descending)); - - RmlExtCollectionView.Filter = (rml) => - { - RmlsExtension r = rml as RmlsExtension; - return String.IsNullOrWhiteSpace(Filter) - || r.Name.ToLower().Contains(Filter.ToLower()); - }; + 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) @@ -348,84 +375,68 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels private void LoadRmlProperties() { Applications = _active_context.YarnApplications.ToObservableCollection(); - Brands = _active_context.YarnBrand.ToObservableCollection(); - YarnColor = _active_context.YarnColor.ToObservableCollection(); - EndUse = _active_context.YarnEndUse.ToObservableCollection(); - Family = _active_context.YarnFamily.ToObservableCollection(); - Geometry = _active_context.YarnGeometry.ToObservableCollection(); - GlossLevel = _active_context.YarnGlossLevel.ToObservableCollection(); - Group = _active_context.YarnGroup.ToObservableCollection(); - Manufacturer = _active_context.YarnManufacturer.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(); - Materials = _active_context.YarnMaterials.ToObservableCollection(); - SubFamilies = _active_context.YarnSubFamily.ToObservableCollection(); - Texturing = _active_context.YarnTexturing.ToObservableCollection(); - YarnTypes = _active_context.YarnType.ToObservableCollection(); - IndustrySector = _active_context.YarnIndustrysector.ToObservableCollection(); } - - private async void AddNewRmlExtention(object obj) + + private RmlsExtension GetNewRMLsExtension( string RML_Guid) { - using (_notification.PushTaskItem("Creating new RML Extension...")) - { - IsFree = false; - - if (_active_context != null) - { - _active_context.Dispose(); - } - - _active_context = ObservablesContext.CreateDefault(); - - LoadRmlProperties(); - - RmlsExtension rml_extention = new RmlsExtension(); - rml_extention.Created = DateTime.UtcNow; - rml_extention.UserGuid = _authentication.CurrentUser.Guid; - rml_extention.YarnManufacturer = Manufacturer.FirstOrDefault(); - rml_extention.YarnBrand = Brands.FirstOrDefault(); - rml_extention.Country = null; - rml_extention.YarnEndUse = EndUse.FirstOrDefault(); - rml_extention.YarnApplications = 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.YarnGeometry = Geometry.FirstOrDefault(); - rml_extention.YarnColor = YarnColor.FirstOrDefault(); - rml_extention.YarnGlossLevel = GlossLevel.FirstOrDefault(); - rml_extention.LinearDensity = 0; - rml_extention.YarnUnit = YarnUnits.DTEX; - rml_extention.YarnPlies = Plies.P1; - rml_extention.FilamentCount = 0; - rml_extention.TwistTpm = 0; - rml_extention.YarnTwistDirections = TwistDirections.S; - 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"; - - _active_context.RmlsExtensions.Add(rml_extention); - await _active_context.SaveChangesAsync(); + 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(); - //_actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlCreated, _authentication.CurrentUser, rml.Name, rml, "Rml created using Machine Studio."); - ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); - LoadActiveRMLExtention(rml_extention.Guid); + //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; - IsFree = true; - } + return rml_extention; } - private async void LoadActiveRMLExtention(String guid) + private async void LoadActiveRMLExtension(String guid) { using (_notification.PushTaskItem("Loading RML Extension...")) { @@ -439,17 +450,60 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels } _active_context = ObservablesContext.CreateDefault(); - LoadRmlProperties(); - ActiveRMLExtention = await new RmlExtensionsBuilder(_active_context) - .Set(guid) - .WithUser() - .BuildAsync(); + 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 machinesWithTest = _active_context.RmlExtensionTestResults.Select(x => x.MachineGuid).ToList(); + var machinesWithTest2 = + Join(_active_context.ColorProcessParameters.Select(y => y.MachineGuid), st1 => st1, st2=> st2, (st1, st2)=>).ToList(); + Machines = ObservablesStaticCollections.Instance.Machines.Select(x => new MachineModel() + { + Guid = x.Guid, + Name = x.Name, + SerialNumber = x.SerialNumber + }).ToObservableCollection(); + var settings = SettingsManager.Default.GetOrCreate<MachineStudioSettings>(); + SelectedMachine = ObservablesStaticCollections.Instance.Machines.SingleOrDefault(x => x.SerialNumber == settings.LastVirtualMachineSerialNumber); ColorParametersVewVM = new ColorParametersVewVM(_notification, _actionLogManager); - ColorParametersVewVM.LoadColorParameters(guid); - View.NavigateTo(ThreadExtensionNavigationView.ThreadExtentionView); + ColorParametersVewVM.RMLExtemtionGUID = guid; + ColorParametersVewVM.SelectedMachineGUID = SelectedMachine.Guid; + + TestResultsViewVM = new TestResultsViewVM(_notification, _actionLogManager); + TestResultsViewVM.RMLExtemtionGUID = guid; + TestResultsViewVM.ThreadName = ActiveRML.Manufacturer; + + var machineGuidsWithTests = await _active_context.RmlExtensionTestResults.Where(x => x.RmlsExtensionsGuid == guid).Select(y => y.MachineGuid).ToListAsync(); + if(machineGuidsWithTests.Count > 0) + { + + } + + if (ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) + { + ColorParametersVewVM.SaveColorParameters -= UpdateStatus; + ColorParametersVewVM.SaveColorParameters += UpdateStatus; + TestResultsViewVM.SaveTestResults -= UpdateStatus; + TestResultsViewVM.SaveTestResults += UpdateStatus; + } + + View.NavigateTo(RMLExtensionNavigationView.RMLExtentionView); InvalidateRelayCommands(); @@ -466,22 +520,18 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels } } } - - private async void RefreshView(String guid) + + private async void RefreshView(String guid, String rmlGuid) { try { IsFree = false; - - //if (_active_context != null) - //{ - // _active_context.Dispose(); - //} - - //_active_context = ObservablesContext.CreateDefault(); - + LoadRmlProperties(); - ActiveRMLExtention = await new RmlExtensionsBuilder(_active_context) + ActiveRML = ActiveRML = await new RmlBuilder(_active_context) + .Set(rmlGuid) + .BuildAsync(); + ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) .Set(guid) .WithUser() .BuildAsync(); @@ -493,7 +543,7 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels catch (Exception ex) { //LogManager.Log($"Error loading RML '{ActiveRML.Name}'..."); - _notification.ShowError($"Error refresh the selected thread.\n{ex.FlattenMessage()}"); + _notification.ShowError($"Error refresh after save the selected thread.\n{ex.FlattenMessage()}"); } finally { @@ -503,34 +553,75 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels #endregion - private async void Save() + #region event handlers + + private async void UpdateStatus(object sender, EventArgs e) { IsFree = false; try { - using (_notification.PushTaskItem("Saving RML Extension...")) - { + ColorParametersVewVM.SaveColorParameters -= UpdateStatus; + TestResultsViewVM.SaveTestResults -= UpdateStatus; + ActiveRMLExtension.RMLStatus = RMLExtensionStatus.InProgress; + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; - ActiveRMLExtention.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; + } + } - ColorParametersVewVM.Save(); + private void SelectedMachineChanged() + { + if(ColorParametersVewVM != null) + { + ColorParametersVewVM.SelectedMachineGUID = SelectedMachine.Guid; + } + } - var rmlExtensionAfter = RmlsExtensionDTO.FromObservable(ActiveRMLExtention); + #endregion - await _active_context.SaveChangesAsync(); + #region Save - //ColorParametersVewVM.LoadColorParameters(ActiveRMLExtention.Guid); - // _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.RmlSaved, _authentication.CurrentUser, _rmlBeforeSave.Name, _rmlBeforeSave, rmlAfter, "RML saved using Machine Studio."); + /// <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; + } - _rmlExtensionBeforeSave = rmlExtensionAfter; + ActiveRMLExtension.LastUpdated = DateTime.UtcNow; + ActiveRML.LastUpdated = DateTime.UtcNow; + + await _active_context.SaveChangesAsync(); - RefreshView(SelectedRMLExtension.Guid); + // _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 {ActiveRMLExtention.Name}"); + 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 @@ -538,5 +629,7 @@ namespace Tango.MachineStudio.ThreadExtensions.ViewModels 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..c60d5e4fa --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ThreadExtensions/ViewModels/TestResultsViewVM.cs @@ -0,0 +1,368 @@ +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.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(); + } + } + /// <summary> + /// Gets or sets the machines providers. + /// </summary> + //public ISuggestionProvider MachinesProvider { get; set; } + + protected Machine _selectedMachine; + /// <summary> + /// Gets or sets the selected machine. + /// </summary> + public Machine SelectedMachine + { + get { return _selectedMachine; } + set + { + if (value != null && _selectedMachine != value) + { + _selectedMachine = 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(); } + } + + + #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 FlytoProcessParametersCommand { 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); + + FlytoProcessParametersCommand = new RelayCommand(FlytoProcessParameters); + 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; + var settings = SettingsManager.Default.GetOrCreate<MachineStudioSettings>(); + + SelectedMachine = ObservablesStaticCollections.Instance.Machines.SingleOrDefault(x => x.SerialNumber == settings.LastVirtualMachineSerialNumber); + } + + private void SelectedMachineChanged() + { + ResultTabs.Clear(); + SelectedTab = null; + LoadTestResults(); + } + public async void LoadTestResults() + { + if (SelectedMachine == null || SelectedMachine.Guid == null) + { + _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(SelectedMachine.Guid).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 = SelectedMachine.Guid, 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 void FlytoProcessParameters() + { + + } + + public async void Save() + { + if (SelectedMachine == null || SelectedMachine.Guid == null) + { + _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 + } +} |
