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; using Tango.Core.Helpers; using Tango.Documents; namespace Tango.MachineStudio.ThreadExtensions.ViewModels { public class MainViewVM : StudioViewModel { public enum MachineTestResultsTabs { ColorParameters, TestResults } private INotificationProvider _notification; private IAuthenticationProvider _authentication; private IActionLogManager _actionLogManager; private ObservablesContext _active_context; private List _allUsers; #region properties //private ObservableCollection _rmlsExtension; //public ObservableCollection RmlsExtensions //{ // get { return _rmlsExtension; } // set { _rmlsExtension = value; // RaisePropertyChangedAuto(); } //} private List _rmlExtensions; public List 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; ///// ///// Gets or sets the RML collection view. ///// //public ICollectionView RmlExtCollectionView //{ // get { return _rmlExtCollectionView; } // set // { // _rmlExtCollectionView = value; // RaisePropertyChangedAuto(); // } //} private ObservableCollection _applications; public ObservableCollection Applications { get { return _applications; } set { _applications = value; RaisePropertyChangedAuto(); } } private ObservableCollection _brands; public ObservableCollection Brands { get { return _brands; } set { _brands = value; RaisePropertyChangedAuto(); } } private ObservableCollection _yarnWhiteShade; public ObservableCollection YarnWhiteShade { get { return _yarnWhiteShade; } set { _yarnWhiteShade = value; RaisePropertyChangedAuto(); } } private ObservableCollection _enduse; public ObservableCollection EndUse { get { return _enduse; } set { _enduse = value; RaisePropertyChangedAuto(); } } private ObservableCollection _units; public ObservableCollection Units { get { return _units; } set { _units = value; RaisePropertyChangedAuto(); } } private ObservableCollection _family; public ObservableCollection Family { get { return _family; } set { _family = value; RaisePropertyChangedAuto(); } } private ObservableCollection _geometry; public ObservableCollection Geometry { get { return _geometry; } set { _geometry = value; RaisePropertyChangedAuto(); } } private ObservableCollection _glosslevel; public ObservableCollection GlossLevel { get { return _glosslevel; } set { _glosslevel = value; RaisePropertyChangedAuto(); } } private ObservableCollection _group; public ObservableCollection Group { get { return _group; } set { _group = value; RaisePropertyChangedAuto(); } } private List _manufacturers; public List Manufacturers { get { return _manufacturers; } set { _manufacturers = value; RaisePropertyChangedAuto(); } } private ObservableCollection _materials; public ObservableCollection Materials { get { return _materials; } set { _materials = value; RaisePropertyChangedAuto(); } } private ObservableCollection _subFamilies; public ObservableCollection SubFamilies { get { return _subFamilies; } set { _subFamilies = value; RaisePropertyChangedAuto(); } } private ObservableCollection _texturing; public ObservableCollection Texturing { get { return _texturing; } set { _texturing = value; RaisePropertyChangedAuto(); } } private ObservableCollection _yarnTypes; public ObservableCollection YarnTypes { get { return _yarnTypes; } set { _yarnTypes = value; RaisePropertyChangedAuto(); } } private ObservableCollection _industrySector; public ObservableCollection IndustrySector { get { return _industrySector; } set { _industrySector = value; RaisePropertyChangedAuto(); } } private String _RMLFilter; /// /// Gets or sets the search filter. /// public String RMLFilter { get { return _RMLFilter; } set { _RMLFilter = 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(); } } private ColorCalibrationViewVM _colorCalibrationViewVM; public ColorCalibrationViewVM ColorCalibrationViewVM { get { return _colorCalibrationViewVM; } set { _colorCalibrationViewVM = value; RaisePropertyChangedAuto(); } } private ColorShadeViewVM _solorShadeViewVM; public ColorShadeViewVM ColorShadeViewVM { get { return _solorShadeViewVM; } set { _solorShadeViewVM = value; RaisePropertyChangedAuto(); } } protected MachineModel _selectedMachine; /// /// Gets or sets the selected machine. /// public MachineModel SelectedMachine { get { return _selectedMachine; } set { if (value != null && _selectedMachine != value) { _selectedMachine = value; SelectedMachineChanged(); RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } } private ObservableCollection _machines; /// /// Gets or sets the Machines. /// public ObservableCollection Machines { get { return _machines; } set { _machines = value; LoadFilteredMachines(); RaisePropertyChanged(nameof(Machines)); } } private ObservableCollection _filteremachines; /// /// Gets or sets the Machines. /// public ObservableCollection FilteredMachines { get { return _filteremachines; } set { _filteremachines = value; RaisePropertyChanged(nameof(FilteredMachines)); } } private bool _showWithData; /// /// Gets or sets the bool show with data only. /// public bool ShowWithData { get { return _showWithData; } set { if(_showWithData != value) { _showWithData = value; RaisePropertyChangedAuto(); LoadFilteredMachines(); } } } private void LoadFilteredMachines() { if(_showWithData) FilteredMachines = Machines.Where(x => x.HasRMLTest).OrderBy(x => x.LastUpdated).ToObservableCollection(); else { FilteredMachines = Machines.OrderBy(x=>x.Name).ToObservableCollection(); } } private bool _canEdit; public bool CanEdit { get { return _canEdit; } set { _canEdit = value; RaisePropertyChangedAuto(); } } //private MachineTestResultsTabs PreviosSelectedTab { get; set; } //private MachineTestResultsTabs _selectedTab; //public MachineTestResultsTabs SelectedTab //{ // get { return _selectedTab; } // set { // PreviosSelectedTab = _selectedTab; // _selectedTab = value; // OnSelectedMachineTestResultsTabChanged(); // RaisePropertyChangedAuto(); // } //} #endregion #region commands public RelayCommand SaveCommand { get; set; } public RelayCommand ExportToFileCommand { get; set; } public RelayCommand ManageRmlExtensionCommand { get; set; } public RelayCommand BackToThreadExtensionViewsCommand { get; set; } private async void BackToThreadExtensionViews(object obj) { //if ( _notification.ShowQuestion("Are you sure you want to exit the RML without saving changes?")) { 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(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(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(ObservableCollection collection, DbSet dbColection, ref string name) where T : class { AddItemDialogVM vm = ViewModelLocator.AddItemDialogVM; vm.Name = ""; PropertyInfo pi = typeof(T).GetProperty("Name"); bool returnValue = false; _notification.ShowModalDialog(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(ObservableCollection collection, DbSet 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(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; _showWithData = false; BackToThreadExtensionViewsCommand = new RelayCommand(BackToThreadExtensionViews, () => IsFree); SaveCommand = new RelayCommand(Save, () => IsFree); ExportToFileCommand = new RelayCommand(ExportRMLToExcel, () => IsFree); ManageRmlExtensionCommand = new RelayCommand(() => LoadActiveRMLExtension(SelectedRMLExtension.Guid), () => SelectedRMLExtension != null); AddManufacturerItemCommand = new RelayCommand(AddManufacturerItem); EditManufacturerItemCommand = new RelayCommand(EditManufacturerItem, () => ActiveRML !=null && ActiveRML.Manufacturer != ""); AddBrandItemCommand = new RelayCommand(AddBrandItem); EditBrandItemCommand = new RelayCommand(EditBrandItem, () => ActiveRMLExtension != null && 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() { var env = SettingsManager.Default.GetOrCreate().DeploymentSlot; CanEdit = env == Web.DeploymentSlot.DEV || env == Web.DeploymentSlot.TEST || env == Web.DeploymentSlot.PROCESS; } #region Loading private async Task LoadRmlExtentions() { var filter = RMLFilter.ToStringOrEmpty().ToLower(); try { IsFree = false; using (ObservablesContext db = ObservablesContext.CreateDefault()) { if (Brands == null) Brands = db.YarnBrands.ToObservableCollection(); if (_allUsers == null) { _allUsers = new List(); var users = await db.Users.Include(x => x.Contact).ToListAsync(); foreach (var user in users) { UserModel model = new UserModel(); model.Guid = user.Guid; model.Name = user.Contact.FullName; _allUsers.Add(model); } } var q = (from c in db.Rmls.Where(x => x.Name.ToLower().Contains(filter)) join p in db.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).Name, 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, Level = x.RMLExtesion == null ? RMLExtensionLevel.One : x.RMLExtesion.Level, }).ToList(); RmlExtensions = q; } } 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(); } 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; rml_extention.Level = RMLExtensionLevel.One; 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(); var machines = await new MachinesCollectionBuilder(_active_context).SetAll().WithConfiguration().BuildListAsync(); Machines = machines.Select(x => new MachineModel() { Guid = x.Guid, Name = x.Name, SerialNumber = x.SerialNumber, IdsPacks = x.Configuration.IdsPacks.Where(z => !z.IsEmpty), LastUpdated = x.LastUpdated, HasRMLTest = false }).ToObservableCollection(); if (guid == null) { RmlsExtension rml_extention = GetNewRMLsExtension(SelectedRMLExtension.RMLGuid); _active_context.RmlsExtensions.Add(rml_extention); await _active_context.SaveChangesAsync(); guid = rml_extention.Guid; } ActiveRML = await new RmlBuilder(_active_context).Set(SelectedRMLExtension.RMLGuid).WithLiquidFactors().BuildAsync(); ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) .Set(guid) .BuildAsync(); if (!String.IsNullOrEmpty(ActiveRML.Manufacturer) && false == Manufacturers.Any(x => x == ActiveRML.Manufacturer)) { _active_context.YarnManufacturers.Add(new YarnManufacturer() { Name = ActiveRML.Manufacturer }); await _active_context.SaveChangesAsync(); Manufacturers.Add(ActiveRML.Manufacturer); } //var colorProcessParameters = _active_context.ColorProcessParameters.Where(x => x.RmlsExtensionsGuid == guid).Select(x=>x.MachineGuid).ToList(); //var TestResultsCollection = await new RMLExtensionTestResultsCollectionBuilder(_active_context).SetAll().ForRMLExtension(guid).BuildAsync(); //var test1 = TestResultsCollection.Select(x => x.MachineGuid).ToList(); //var ColorCalibration = await new RMLExtensionColorCalibrationBuilder(_active_context).SetAll().ForRMLExtension(guid).WithTests().BuildAsync(); //var test12 = ColorCalibration.Where(x=>x.RmlExtensionColorCalibrationsTests!= null && x.RmlExtensionColorCalibrationsTests.Count() > 0).Select(x => x.MachineGuid).ToList(); //var testResults = await new RMLExtensionColorShadeBuilder(_active_context).SetAll().ForRMLExtension(guid).WithTests().BuildAsync(); //var test13 = testResults.Where(x => x.RmlExtensionColorShadesTests != null && x.RmlExtensionColorShadesTests.Count() > 0).Select(x => x.MachineGuid).ToList(); //var ulist = colorProcessParameters.Union(test1).Union(test12).Union(test13).ToList(); 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) { ShowWithData = true; var MachineGuid = machineIdsHasTest.First().MichineGUID; Machines.Where(x => machineIdsHasTest.Any(y => y.MichineGUID == x.Guid)).ToList().ForEach(x => x.HasRMLTest = true); LoadFilteredMachines(); SelectedMachine = FilteredMachines.First(); } else { var settings = SettingsManager.Default.GetOrCreate(); if (settings.LastVirtualMachineSerialNumber != null) { SelectedMachine = Machines.SingleOrDefault(x => x.SerialNumber == settings.LastVirtualMachineSerialNumber); } if(SelectedMachine == null) { 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; ColorCalibrationViewVM = new ColorCalibrationViewVM(_notification, _actionLogManager); ColorCalibrationViewVM.RMLExtentionGUID = guid; ColorCalibrationViewVM.ActiveRML = ActiveRML; ColorCalibrationViewVM.RMLGUID = ActiveRML.Guid; ColorCalibrationViewVM.Machine = SelectedMachine; ColorShadeViewVM = new ColorShadeViewVM(_notification, _actionLogManager); ColorShadeViewVM.RMLExtentionGUID = guid; ColorShadeViewVM.RMLGUID = ActiveRML.Guid; ColorShadeViewVM.SelectedMachineGUID = SelectedMachine != null ? SelectedMachine.Guid : null; ; if (ActiveRMLExtension.RMLStatus == RMLExtensionStatus.New) { ColorParametersVewVM.SaveColorParameters -= UpdateStatus; ColorParametersVewVM.SaveColorParameters += UpdateStatus; TestResultsViewVM.SaveTestResults -= UpdateStatus; TestResultsViewVM.SaveTestResults += UpdateStatus; ColorCalibrationViewVM.SaveColorCalibration -= UpdateStatus; ColorCalibrationViewVM.SaveColorCalibration += UpdateStatus; ColorShadeViewVM.SaveColorShadesEvent -= UpdateStatus; ColorShadeViewVM.SaveColorShadesEvent += 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; ColorCalibrationViewVM.SaveColorCalibration -= UpdateStatus; ColorShadeViewVM.SaveColorShadesEvent -= 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; } if(TestResultsViewVM != null) { TestResultsViewVM.SelectedMachineGUID = SelectedMachine.Guid; } if(ColorCalibrationViewVM != null) { ColorCalibrationViewVM.Machine = SelectedMachine; } if(ColorShadeViewVM != null) { ColorShadeViewVM.SelectedMachineGUID = SelectedMachine.Guid; } } #endregion #region Save /// /// Saves this instance. /// 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 #region selections //private void OnSelectedMachineTestResultsTabChanged() // { //if(SelectedTab == MachineTestResultsTabs.ColorParameters) // { //if(PreviosSelectedTab == MachineTestResultsTabs.TestResults && TestResultsViewVM != null) //{ // TestResultsViewVM.Save(); //} //save //if (_notification.ShowQuestion("Are you sure you want to exit this page without saving changes?")) // } // else if(SelectedTab == MachineTestResultsTabs.TestResults) // { //if (PreviosSelectedTab == MachineTestResultsTabs.ColorParameters && ColorParametersVewVM != null) //{ // ColorParametersVewVM.Save(); //} //} // } #endregion #region Export / Import Excel public void ExportRMLToExcel() { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Excel Documents|*.xlsx"; if (dlg.ShowDialog().Value) { using (_notification.PushTaskItem("Exporting RML to file...")) { Task.Factory.StartNew(() => { try { IsFree = false; Stream stream = null; bool dispose = false; String file = AssemblyHelper.GetCurrentAssemblyFolder() + "\\Templates\\ExportRMLTemplate.xlsx"; if (File.Exists(file)) { stream = File.OpenRead(file); dispose = true; } else { stream = EmbeddedResourceHelper.GetEmbeddedResourceStream("Tango.MachineStudio.ThreadExtensions.Templates.ExportRMLTemplate.xlsx"); } byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); File.WriteAllBytes(dlg.FileName, data); if (dispose) { stream.Dispose(); } ExcelWriter writer = new ExcelWriter(dlg.FileName); //ActiveRMLExtension = await new RmlExtensionsBuilder(_active_context) // .Set(guid) // .WithUser() // .BuildAsync(); //ActiveRML = new RmlBuilder(_active_context) // .Set(SelectedRMLExtension.RMLGuid) // .Build(); List threadCharacteristicsExelModels = new List(); ThreadCharacteristicsExcelModel model = new ThreadCharacteristicsExcelModel(); model.ThreadName = ActiveRML.Name; model.Manufacturer = ActiveRML.Manufacturer == null? "": ActiveRML.Manufacturer; model.Brand = ActiveRMLExtension.YarnBrand == null ? "": ActiveRMLExtension.YarnBrand.Name; model.Country = ActiveRMLExtension.Country == null? "" : ActiveRMLExtension.Country; model.EndUse = ActiveRML.MediaPurpose == null ? "" : ActiveRML.MediaPurpose.Name; model.Applications = ActiveRMLExtension.YarnApplication == null ? "" : ActiveRMLExtension.YarnApplication.Name; model.IndustrySector = ActiveRMLExtension.YarnIndustrysector == null ? "" : ActiveRMLExtension.YarnIndustrysector.Name; model.Material = ActiveRML.MediaMaterial == null ? "" : ActiveRML.MediaMaterial.Name; model.Type = ActiveRMLExtension.YarnType == null ? "" : ActiveRMLExtension.YarnType.Name; model.SubFamily = ActiveRMLExtension.YarnSubFamily == null ? "" : ActiveRMLExtension.YarnSubFamily.Name; model.Family = ActiveRMLExtension.YarnFamily == null ? "" : ActiveRMLExtension.YarnFamily.Name; model.Group = ActiveRMLExtension.YarnGroup == null ? "" : ActiveRMLExtension.YarnGroup.Name; model.Texturing = ActiveRMLExtension.YarnTexturing == null ? "" : ActiveRMLExtension.YarnTexturing.Name; model.Geometry = ActiveRML.FiberShape == null ? "" : ActiveRML.FiberShape.Name; model.Color = ActiveRMLExtension.YarnWhiteShade == null ? "" : ActiveRMLExtension.YarnWhiteShade.Name; model.GlossLevel = ActiveRMLExtension.YarnGlossLevel == null ? "" : ActiveRMLExtension.YarnGlossLevel.Name; model.LinearDensity = ActiveRML.FiberSize; model.Unit = ActiveRML.LinearMassDensityUnit == null ? "" : ActiveRML.LinearMassDensityUnit.Name; model.Plies = (int) ActiveRML.RMLPlies; model.FilamentCountPerPlie = ActiveRML.PliesPerFiber; model.LinearDensityCount = ActiveRML.DencityCount; model.CountDen = ActiveRML.DencityCount; model.FiberCount = ActiveRML.FiberCount; model.Twist = ActiveRMLExtension.TwistTpm; model.TwistDirection = ActiveRMLExtension.YarnTwistDirections.ToDescription(); threadCharacteristicsExelModels.Add(model); writer.WriteData(threadCharacteristicsExelModels, "Thread characteristics", 2); List colorParametrsExcelList = new List(); List testResultsExcelModelList = new List(); foreach(var machine in Machines) { if (machine.HasRMLTest) { ColorParametrsExcelModel colorParametrsExcelModel = new ColorParametrsExcelModel(); colorParametrsExcelModel.Thread_name = ActiveRML.Name; colorParametrsExcelModel.MachineNumber = machine.SerialNumber.ToString(); colorParametrsExcelModel.White_point_L = ActiveRML.WhitePointL; colorParametrsExcelModel.White_point_a = ActiveRML.WhitePointA; colorParametrsExcelModel.White_point_B = ActiveRML.WhitePointB; ColorParametersVewVM.WritetoExcel(colorParametrsExcelModel, machine.Guid); colorParametrsExcelList.Add(colorParametrsExcelModel); TestResultsViewVM.LoadTestResultsExcel(testResultsExcelModelList, machine.Guid, machine.SerialNumber); //ColorCalibrationViewVM.WritetoExcel } } writer.WriteData(colorParametrsExcelList, "Color parameters"); writer.WriteData(testResultsExcelModelList.OrderBy(x => x.Machine_number), "Machine tests results"); writer.Dispose(); InvokeUI(() => { _notification.ShowInfo("RML extensions exported successfully."); }); } catch (Exception ex) { LogManager.Log(ex, $"Error exporting RML extensions to {dlg.FileName}"); InvokeUI(() => { _notification.ShowError($"An error occurred while trying to export the RML extensions. Make sure the selected excel file is closed and data is valid.\n{ex.FlattenMessage()}"); }); } finally { IsFree = true; } }); } } } #endregion } }