aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.HardwareDesigner/ViewModels/MainViewVM.cs
blob: c46b1dec173e1193f3366f8230ef5b61d6af179c (plain)
1
2
3
4
5
6
7
8
9
10
11
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

public static class CommonDialogExtensions
{
    public static bool ShowDialogCenter(this CommonDialog dialog)
    {
        return dialog.ShowDialog(Application.Current.MainWindow).Value;
    }
}
a id='n245' href='#n245'>245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.Commands;
using Tango.BL.Entities;
using Tango.MachineStudio.Common.Notifications;
using Tango.SharedUI;
using Tango.BL;
using Tango.SharedUI.Components;
using System.Runtime.CompilerServices;
using Tango.MachineStudio.Common;

namespace Tango.MachineStudio.HardwareDesigner.ViewModels
{
    public class MainViewVM : StudioViewModel
    {
        private INotificationProvider _notification;
        private bool _isNew;
        private ObservablesContext _db;

        private HardwareVersion _selectedVersion;
        public HardwareVersion SelectedVersion
        {
            get { return _selectedVersion; }
            set { _selectedVersion = value; RaisePropertyChangedAuto(); OnSelectedVersionChanged(); }
        }

        private HardwareVersion _currentVersion;
        public HardwareVersion CurrentVersion
        {
            get { return _currentVersion; }
            set { _currentVersion = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private IObservableEntity _selectedHardwareObject;
        public IObservableEntity SelectedHardwareObject
        {
            get { return _selectedHardwareObject; }
            set
            {
                _selectedHardwareObject = value;
                RaisePropertyChangedAuto();
            }
        }

        private ObservableCollection<HardwareVersion> _hardwareVersions;
        public ObservableCollection<HardwareVersion> HardwareVersions
        {
            get { return _hardwareVersions; }
            set { _hardwareVersions = value; RaisePropertyChangedAuto(); }
        }

        public RelayCommand SaveCommand { get; set; }

        public RelayCommand DeleteCommand { get; set; }

        public RelayCommand NewCommand { get; set; }

        public RelayCommand CloneCommand { get; set; }

        public RelayCommand CopyParametersCommand { get; set; }

        public MainViewVM(INotificationProvider notification)
        {
            _notification = notification;

            CurrentVersion = new HardwareVersion();

            SaveCommand = new RelayCommand(Save, () => SelectedVersion != null && IsFree);
            NewCommand = new RelayCommand(New, () => IsFree);
            DeleteCommand = new RelayCommand(Delete, () => !_isNew && SelectedVersion != null && IsFree);

            CurrentVersion = new HardwareVersion();

            CopyParametersCommand = new RelayCommand(CopyParameters, (x) => SelectedVersion != null && IsFree);
            CloneCommand = new RelayCommand(CloneCurrentVersion, () => SelectedVersion != null && IsFree);
        }

        public override void OnApplicationReady()
        {
            Task.Factory.StartNew(() =>
            {
                RefreshVersions();
                CreateDefaultView();
            });
        }

        private void CopyParameters(object obj)
        {
            obj.MapPrimitivesTo(SelectedHardwareObject,
                (prop) =>
                !prop.PropertyType.IsEnum
                &&
                !prop.Name.ToLower().Contains("guid"));
        }

        private void CreateDefaultView()
        {
            if (_db != null) _db.Dispose();

            _db = ObservablesContext.CreateDefault();

            CurrentVersion.HardwareMotors = _db.HardwareMotorTypes.ToList().Select(x => new HardwareMotor() { HardwareMotorType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwareDancers = _db.HardwareDancerTypes.ToList().Select(x => new HardwareDancer() { HardwareDancerType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwarePidControls = _db.HardwarePidControlTypes.ToList().Select(x => new HardwarePidControl() { HardwarePidControlType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwareWinders = _db.HardwareWinderTypes.ToList().Select(x => new HardwareWinder() { HardwareWinderType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwareSpeedSensors = _db.HardwareSpeedSensorTypes.ToList().Select(x => new HardwareSpeedSensor() { HardwareSpeedSensorType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwareBlowers = _db.HardwareBlowerTypes.ToList().Select(x => new HardwareBlower() { HardwareBlowerType = x }).ToSynchronizedObservableCollection();
            CurrentVersion.HardwareBreakSensors = _db.HardwareBreakSensorTypes.ToList().Select(x => new HardwareBreakSensor() { HardwareBreakSensorType = x }).ToSynchronizedObservableCollection();
        }

        private void RefreshVersions()
        {
            using (var db = ObservablesContext.CreateDefault())
            {
                _hardwareVersions = db.HardwareVersions.ToObservableCollection();
                InvokeUI(() =>
                {
                    RaisePropertyChanged(nameof(HardwareVersions));
                });
            }
        }

        private void CreateVersionView(HardwareVersion selectedVersion)
        {
            if (_db != null) _db.Dispose();

            _db = ObservablesContext.CreateDefault();

            CurrentVersion = _db.Adapter.GetHardwareVersion(x => x.Guid == selectedVersion.Guid);


            InvokeUINow(() =>
            {
                ObservablesStaticCollections.Instance.HardwareMotorTypes.Where(x => !CurrentVersion.HardwareMotors.ToList().Exists(y => y.HardwareMotorType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareMotors.Add(new HardwareMotor()
                    {
                        HardwareMotorType = _db.HardwareMotorTypes.SingleOrDefault(y => y.Code == x.Code),
                    });
                });

                CurrentVersion.HardwareMotors = CurrentVersion.HardwareMotors.OrderBy(x => x.HardwareMotorType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwareDancerTypes.Where(x => !CurrentVersion.HardwareDancers.ToList().Exists(y => y.HardwareDancerType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareDancers.Add(new HardwareDancer()
                    {
                        HardwareDancerType = _db.HardwareDancerTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwareDancers = CurrentVersion.HardwareDancers.OrderBy(x => x.HardwareDancerType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwarePidControlTypes.Where(x => !CurrentVersion.HardwarePidControls.ToList().Exists(y => y.HardwarePidControlType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwarePidControls.Add(new HardwarePidControl()
                    {
                        HardwarePidControlType = _db.HardwarePidControlTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwarePidControls = CurrentVersion.HardwarePidControls.OrderBy(x => x.HardwarePidControlType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwareWinderTypes.Where(x => !CurrentVersion.HardwareWinders.ToList().Exists(y => y.HardwareWinderType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareWinders.Add(new HardwareWinder()
                    {
                        HardwareWinderType = _db.HardwareWinderTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwareWinders = CurrentVersion.HardwareWinders.OrderBy(x => x.HardwareWinderType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwareSpeedSensorTypes.Where(x => !CurrentVersion.HardwareSpeedSensors.ToList().Exists(y => y.HardwareSpeedSensorType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareSpeedSensors.Add(new HardwareSpeedSensor()
                    {
                        HardwareSpeedSensorType = _db.HardwareSpeedSensorTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwareSpeedSensors = CurrentVersion.HardwareSpeedSensors.OrderBy(x => x.HardwareSpeedSensorType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwareBlowerTypes.Where(x => !CurrentVersion.HardwareBlowers.ToList().Exists(y => y.HardwareBlowerType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareBlowers.Add(new HardwareBlower()
                    {
                        HardwareBlowerType = _db.HardwareBlowerTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwareBlowers = CurrentVersion.HardwareBlowers.OrderBy(x => x.HardwareBlowerType.Code).ToSynchronizedObservableCollection();

                ObservablesStaticCollections.Instance.HardwareBreakSensorTypes.Where(x => !CurrentVersion.HardwareBreakSensors.ToList().Exists(y => y.HardwareBreakSensorType.Code == x.Code)).ToList().ForEach(x =>
                {
                    CurrentVersion.HardwareBreakSensors.Add(new HardwareBreakSensor()
                    {
                        HardwareBreakSensorType = _db.HardwareBreakSensorTypes.SingleOrDefault(y => y.Code == x.Code)
                    });
                });

                CurrentVersion.HardwareBreakSensors = CurrentVersion.HardwareBreakSensors.OrderBy(x => x.HardwareBreakSensorType.Code).ToSynchronizedObservableCollection();
            });
        }

        private async void OnSelectedVersionChanged()
        {
            if (SelectedVersion != null)
            {
                using (_notification.PushTaskItem("Loading hardware version..."))
                {
                    IsFree = false;

                    await Task.Factory.StartNew(() =>
                    {
                        _isNew = false;
                        var selectedVersion = SelectedVersion;
                        RefreshVersions();
                        var version = _hardwareVersions.SingleOrDefault(X => X.Guid == selectedVersion.Guid);
                        CreateVersionView(SelectedVersion);

                        InvokeUI(() =>
                        {
                            _selectedVersion = version;
                            RaisePropertyChanged(nameof(SelectedVersion));
                        });
                    });

                    IsFree = true;
                }
            }

            InvalidateRelayCommands();
        }

        private async void New()
        {
            String name = _notification.ShowTextInput("Enter hardware version name", "Name");

            if (!String.IsNullOrWhiteSpace(name))
            {
                using (_notification.PushTaskItem("Creating new machine version..."))
                {
                    IsFree = false;

                    await Task.Factory.StartNew(() =>
                    {
                        SelectedVersion = null;
                        CurrentVersion = new HardwareVersion();
                        CurrentVersion.Version = HardwareVersions.Max(x => x.Version) + 1;
                        CurrentVersion.Name = name;
                        CreateDefaultView();

                        _db.HardwareVersions.Add(CurrentVersion);
                        _db.SaveChanges();

                        RefreshVersions();

                        InvokeUI(() =>
                        {
                            _selectedVersion = HardwareVersions.SingleOrDefault(x => x.Guid == CurrentVersion.Guid);
                            RaisePropertyChanged(nameof(SelectedVersion));
                        });

                        _isNew = true;
                        InvalidateRelayCommands();
                    });

                    IsFree = true;
                }
            }
        }

        private async void Save()
        {
            using (_notification.PushTaskItem("Saving hardware version..."))
            {
                try
                {
                    IsFree = false;

                    await Task.Factory.StartNew(() =>
                    {
                        _db.SaveChanges();
                        RefreshVersions();

                        InvokeUI(() =>
                        {
                            SelectedVersion = HardwareVersions.SingleOrDefault(x => x.Guid == CurrentVersion.Guid);
                        });
                    });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Could not save hardware version.");
                    _notification.ShowError($"An error occurred while trying to save this hardware version.\n{ex.Message}");
                }
                finally
                {
                    IsFree = true;
                }
            }
        }

        private async void CloneCurrentVersion()
        {
            if (CurrentVersion != null)
            {
                String name = _notification.ShowTextInput("Enter new hardware configuration name", "Name", CurrentVersion.Name + " - Copy");

                if (!String.IsNullOrWhiteSpace(name))
                {
                    using (_notification.PushTaskItem("Cloning hardware configuration..."))
                    {
                        try
                        {
                            IsFree = false;

                            await Task.Factory.StartNew(() =>
                            {
                                var cloned = CurrentVersion.Clone();
                                cloned.Name = name;
                                cloned.Version = HardwareVersions.Max(x => x.Version) + 1;
                                _db.HardwareVersions.Add(cloned);
                                _db.SaveChanges();
                                RefreshVersions();

                                InvokeUI(() =>
                                {
                                    SelectedVersion = HardwareVersions.SingleOrDefault(x => x.Guid == cloned.Guid);
                                });
                            });
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Could not clone hardware version.");
                            _notification.ShowError($"An error occurred while trying to clone this hardware version.\n{ex.Message}");
                        }
                        finally
                        {
                            IsFree = true;
                        }
                    }
                }
            }

        }

        private async void Delete()
        {
            if (_notification.ShowQuestion("Are you sure you want to delete this hardware version?"))
            {
                using (_notification.PushTaskItem("Deleting hardware version..."))
                {
                    try
                    {
                        IsFree = false;

                        await CurrentVersion.DeleteCascadeAsync(_db);

                        await Task.Factory.StartNew(() =>
                        {
                            SelectedVersion = null;
                            RefreshVersions();

                            CurrentVersion = new HardwareVersion();
                            CreateDefaultView();
                            InvalidateRelayCommands();
                        });
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Could not delete hardware version.");
                        _notification.ShowError($"An error occurred while trying to delete this hardware version.\n{ex.Message}");
                    }
                    finally
                    {
                        IsFree = true;
                    }
                }
            }
        }

        protected override void RaisePropertyChangedAuto([CallerMemberName] string caller = null)
        {
            base.RaisePropertyChangedAuto(caller);
            InvalidateRelayCommands();
        }
    }
}