aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Technician/ViewModels/MachineTechViewVM.cs
blob: 4cc1852a6171f21b126297fb7de7202424446cfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Core;

namespace Tango.MachineStudio.Logging.ViewModels
{
    public class TimelineEventGroup : ExtendedObject
    {
        public String Name { get; set; }

        public ObservableCollection<MachinesEvent> Events { get; set; }

        public TimelineEventGroup()
        {
            Events = new ObservableCollection<MachinesEvent>();
        }

        public TimelineEventGroup(String name) : this()
        {
            Name = name;
        }
    }
}
d='n311' href='#n311'>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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
using Google.Protobuf.Collections;
using Microsoft.Win32;
using RealTimeGraphEx.Controllers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Tango.Core.Helpers;
using Tango.Editors;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.MachineStudio.Common.Diagnostics;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Technician.Editors;
using Tango.MachineStudio.Technician.Project;
using Tango.MachineStudio.Technician.TechItems;
using Tango.PMR.Diagnostics;
using Tango.Settings;
using Tango.SharedUI;
using Tango.Integration.Services;
using Tango.BL.Enumerations;
using Tango.BL;
using Tango.MachineStudio.Common.EventLogging;
using Tango.MachineStudio.Common;

namespace Tango.MachineStudio.Technician.ViewModels
{
    /// <summary>
    /// Represents the MachineTechView View Model.
    /// </summary>
    /// <seealso cref="Tango.SharedUI.ViewModel" />
    /// <seealso cref="Tango.MachineStudio.Common.StudioApplication.IShutdownListener" />
    public class MachineTechViewVM : StudioViewModel<TechnicianModule>
    {
        private List<PropertyInfo> _diagnoticsMonitorsDataProperties;
        private Dictionary<SingleGraphItem, GraphController> _singleControllers;
        private Dictionary<MultiGraphItem, GraphMultiController> _multiControllers;
        private static object _elementsLock = new object();
        private String _lastTechProjectFile;
        private INotificationProvider _notification;
        private IEventLogger _eventLogger;
        private DateTime _lastDiagnosticsResponseUpdate;
        private const int MIN_DIAGNOSTICS_UPDATE_MILI = 500;

        #region Properties

        private ObservableCollection<IElementEditor> _elements;
        /// <summary>
        /// Gets or sets the visual elements.
        /// </summary>
        public ObservableCollection<IElementEditor> Elements
        {
            get { return _elements; }
            set { _elements = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<TechItem> _availableTechItems;
        /// <summary>
        /// Gets or sets the available tech items.
        /// </summary>
        public ObservableCollection<TechItem> AvailableTechItems
        {
            get { return _availableTechItems; }
            set { _availableTechItems = value; RaisePropertyChangedAuto(); }
        }

        private TechItem _selectedTechItem;
        /// <summary>
        /// Gets or sets the selected available tech item.
        /// </summary>
        public TechItem SelectedTechItem
        {
            get { return _selectedTechItem; }
            set { _selectedTechItem = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the db adapter.
        /// </summary>
        public ObservablesEntitiesAdapter Adapter { get; set; }

        /// <summary>
        /// Gets or sets the application manager.
        /// </summary>
        public IStudioApplicationManager ApplicationManager { get; set; }

        private IMachineOperator _machineOperator;
        /// <summary>
        /// Gets or sets the machine operator.
        /// </summary>
        public IMachineOperator MachineOperator
        {
            get { return _machineOperator; }
            set { _machineOperator = value; RaisePropertyChangedAuto(); }
        }

        private bool _disableRendering;
        /// <summary>
        /// Gets or sets a value indicating whether [disable rendering].
        /// </summary>
        public bool DisableRendering
        {
            get { return _disableRendering; }
            set { _disableRendering = value; RaisePropertyChangedAuto(); OnDisableRenderingChanged(); }
        }

        private bool _hideMenu;
        /// <summary>
        /// Gets or sets a value indicating whether [hide menu].
        /// </summary>
        public bool HideMenu
        {
            get { return _hideMenu; }
            set { _hideMenu = value; RaisePropertyChangedAuto(); }
        }

        private PushDiagnosticsResponse _currentDiagnosticsResponse;
        /// <summary>
        /// Gets or sets the current diagnostics response.
        /// </summary>
        public PushDiagnosticsResponse CurrentDiagnosticsResponse
        {
            get { return _currentDiagnosticsResponse; }
            set { _currentDiagnosticsResponse = value; RaisePropertyChanged(nameof(CurrentDiagnosticsResponse)); }
        }

        private int _currentDiagnosticsResponseSize;
        /// <summary>
        /// Gets or sets the size of the current diagnostics response.
        /// </summary>
        /// <value>
        /// The size of the current diagnostics response.
        /// </value>
        public int CurrentDiagnosticsResponseSize
        {
            get { return _currentDiagnosticsResponseSize; }
            set { _currentDiagnosticsResponseSize = value; RaisePropertyChanged(nameof(CurrentDiagnosticsResponseSize)); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the save as project command.
        /// </summary>
        public RelayCommand SaveAsProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the save project command.
        /// </summary>
        public RelayCommand SaveProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the open project command.
        /// </summary>
        public RelayCommand OpenProjectCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MachineTechViewVM"/> class.
        /// </summary>
        /// <param name="applicationManager">The application manager.</param>
        /// <param name="notificationProvider">The notification provider.</param>
        public MachineTechViewVM(IStudioApplicationManager applicationManager, INotificationProvider notificationProvider, IDiagnosticsFrameProvider _diagnosticsFrameProvider, IEventLogger eventLogger)
        {
            _notification = notificationProvider;
            _eventLogger = eventLogger;
            _singleControllers = new Dictionary<SingleGraphItem, GraphController>();
            _multiControllers = new Dictionary<MultiGraphItem, GraphMultiController>();
            AvailableTechItems = TechItem.GetAvailableTechItems().ToObservableCollection();
            SelectedTechItem = AvailableTechItems.FirstOrDefault();
            _diagnoticsMonitorsDataProperties = typeof(DiagnosticsMonitors).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
            ApplicationManager = applicationManager;
            ApplicationManager.ConnectedMachineChanged += ApplicationManager_ConnectedMachineChanged;

            Adapter = ObservablesEntitiesAdapter.Instance;
            Elements = new ObservableCollection<IElementEditor>();

            OpenProjectCommand = new RelayCommand(OpenProject);
            SaveAsProjectCommand = new RelayCommand(SaveAsProject);
            SaveProjectCommand = new RelayCommand(SaveProject);

            _lastTechProjectFile = SettingsManager.Default.MachineStudio.TechnicianModule.LasTechProjectFile;

            if (File.Exists(_lastTechProjectFile))
            {
                OpenProjectFile(_lastTechProjectFile);
            }

            _diagnosticsFrameProvider.FrameReceived += DiagnosticsFrameProvider_FrameReceived;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Applications the manager connected machine changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="machine">The machine.</param>
        private void ApplicationManager_ConnectedMachineChanged(object sender, IExternalBridgeClient machine)
        {
            MachineOperator = machine;
        }

        /// <summary>
        /// Handles the diagnostics frame provider data.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="response">The response.</param>
        private void DiagnosticsFrameProvider_FrameReceived(object sender, PushDiagnosticsResponse response)
        {
            PopulateDiagnosticsData(response);
        }

        #endregion

        #region Populate Diagnostics Data

        /// <summary>
        /// Populates the diagnostics data to the proper elements.
        /// </summary>
        /// <param name="data">The data.</param>
        private void PopulateDiagnosticsData(PushDiagnosticsResponse data)
        {
            if (DateTime.Now > _lastDiagnosticsResponseUpdate.AddMilliseconds(MIN_DIAGNOSTICS_UPDATE_MILI))
            {
                CurrentDiagnosticsResponse = data;
                _lastDiagnosticsResponseUpdate = DateTime.Now;
                CurrentDiagnosticsResponseSize = data.CalculateSize();
            }


            lock (_elementsLock)
            {
                var elements = Elements.ToList();

                foreach (var item in elements.Select(x => x.HostedElement as TechItem))
                {
                    if (item.GetType() == typeof(MonitorItem))
                    {
                        MonitorItem monitorItem = item as MonitorItem;

                        if (DateTime.Now > monitorItem.LastUpdateTime.AddMilliseconds(monitorItem.UpdateInterval))
                        {
                            var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == monitorItem.TechMonitor.Name);

                            if (prop != null)
                            {
                                monitorItem.Value = GetDataLastValue(monitorItem.TechMonitor, prop.GetValue(data.Monitors));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(MeterItem))
                    {
                        MeterItem meterItem = item as MeterItem;

                        if (DateTime.Now > meterItem.LastUpdateTime.AddMilliseconds(meterItem.UpdateInterval))
                        {
                            var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == meterItem.TechMonitor.Name);

                            if (prop != null)
                            {
                                meterItem.Value = GetDataLastValue(meterItem.TechMonitor, prop.GetValue(data.Monitors));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(SingleGraphItem))
                    {
                        SingleGraphItem graphItem = item as SingleGraphItem;

                        var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == graphItem.TechMonitor.Name);

                        if (prop != null)
                        {
                            GraphController controller = null;

                            if (_singleControllers.TryGetValue(graphItem, out controller))
                            {
                                controller.PushData(GetDataArray(graphItem.TechMonitor, prop.GetValue(data.Monitors)));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(MultiGraphItem))
                    {
                        MultiGraphItem graphItem = item as MultiGraphItem;

                        var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == graphItem.TechMonitor.Name);

                        if (prop != null)
                        {
                            GraphMultiController controller = null;

                            if (_multiControllers.TryGetValue(graphItem, out controller))
                            {
                                controller.PushData(GetDataMatrix(graphItem.TechMonitor, prop.GetValue(data.Monitors)));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(DigitalOutItem))
                    {
                        DigitalOutItem digitalOutItem = item as DigitalOutItem;

                        var digitalPin = data.DigitalPins.SingleOrDefault(x => x.Port == digitalOutItem.TechIo.Port);

                        if (digitalPin != null)
                        {
                            digitalOutItem.EffectiveValue = digitalPin.Value;
                        }
                    }
                    else if (item.GetType() == typeof(DigitalInItem))
                    {
                        DigitalInItem digitalInItem = item as DigitalInItem;

                        var digitalPin = data.DigitalPins.SingleOrDefault(x => x.Port == digitalInItem.TechIo.Port);

                        if (digitalPin != null)
                        {
                            digitalInItem.Value = digitalPin.Value;
                        }
                    }
                    else if (item.GetType() == typeof(ControllerItem))
                    {
                        ControllerItem controllerItem = item as ControllerItem;

                        if (DateTime.Now > controllerItem.LastUpdateTime.AddMilliseconds(controllerItem.UpdateInterval))
                        {
                            var componentState = data.ComponentsStates.SingleOrDefault(x => (int)x.Component == controllerItem.TechController.Code);

                            if (componentState != null)
                            {
                                controllerItem.EffectiveValue = componentState.Value;
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Gets the last data point from a protobuf repeated field.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private double GetDataLastValue(TechMonitor monitor, object value)
        {
            if (!monitor.MultiChannel)
            {
                RepeatedField<double> arr = value as RepeatedField<double>;
                return arr.LastOrDefault();
            }
            else
            {
                RepeatedField<DoubleArray> arr = value as RepeatedField<DoubleArray>;
                return arr.Last().Data.Last();
            }
        }

        /// <summary>
        /// Gets the data array from a protobuf repeated field.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private List<double> GetDataArray(TechMonitor monitor, object value)
        {
            return (value as RepeatedField<double>).ToList();
        }

        /// <summary>
        /// Gets the data matrix from a protobuf repeated field of <see cref="DoubleArray"/>.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private List<List<double>> GetDataMatrix(TechMonitor monitor, object value)
        {
            DoubleArray[] arrayOfDoubles = Enumerable.ToArray(value as IEnumerable<DoubleArray>);
            return arrayOfDoubles.Select(x => x.Data.ToList()).ToList();
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the disable rendering has been changed
        /// </summary>
        protected virtual void OnDisableRenderingChanged()
        {
            foreach (var controller in _singleControllers)
            {
                controller.Value.ChangeRenderMode(!DisableRendering);
            }

            foreach (var controller in _multiControllers)
            {
                controller.Value.ChangeRenderMode(!DisableRendering);
            }
        }

        #endregion

        #region Add/Remove Element

        /// <summary>
        /// Creates a new tech element by the specified bounds and the current selected element.
        /// </summary>
        /// <param name="bounds">The bounds.</param>
        public void CreateElement(Rect bounds)
        {
            CreateElement(SelectedTechItem, bounds);
        }

        /// <summary>
        /// Creates a new tech element by the specified tech item instance and bounds.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="bounds">The bounds.</param>
        private void CreateElement(TechItem item, Rect bounds)
        {
            if (item is MonitorItem)
            {
                CreateElement<MonitorElementEditor, MonitorItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
            }
            else if (item is MeterItem)
            {
                CreateElement<MeterElementEditor, MeterItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
            }
            else if (item is SingleGraphItem)
            {
                var editor = CreateElement<SingleGraphElementEditor, SingleGraphItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
                InitSingleGraphitem(editor.GraphItem, editor);
            }
            else if (item is MultiGraphItem)
            {
                var editor = CreateElement<MultiGraphElementEditor, MultiGraphItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => x.MultiChannel).FirstOrDefault());
                InitMultiGraphItem(editor.GraphItem, editor);
            }
            else if (item is MotorItem)
            {
                var editor = CreateElement<MotorElementEditor, MotorItem, HardwareMotorType>(bounds, Adapter.HardwareMotorTypes.FirstOrDefault());
                InitMotorItem(editor.MotorItem);
            }
            else if (item is DispenserItem)
            {
                var editor = CreateElement<DispenserElementEditor, DispenserItem, TechDispenser>(bounds, Adapter.TechDispensers.FirstOrDefault());
                InitDispenserItem(editor.DispenserItem);
            }
            else if (item is ThreadMotionItem)
            {
                var editor = CreateElement<ThreadMotionElementEditor, ThreadMotionItem, object>(bounds, null);
                InitThreadMotionItem(editor.ThreadMotionItem);
            }
            else if (item is MotorGroupItem)
            {
                var editor = CreateElement<MotorGroupElementEditor, MotorGroupItem, object>(bounds, null);
                InitMotorGroupItem(editor.MotorGroupItem);
            }
            else if (item is DigitalOutItem)
            {
                var editor = CreateElement<DigitalOutElementEditor, DigitalOutItem, TechIo>(bounds, Adapter.TechIos.Where(x => x.Type == IOType.DigitalOutput.ToInt32()).FirstOrDefault());
                InitDigitalOutItem(editor.DigitalOutItem);
            }
            else if (item is DigitalInItem)
            {
                CreateElement<DigitalInElementEditor, DigitalInItem, TechIo>(bounds, Adapter.TechIos.Where(x => x.Type == IOType.DigitalInput.ToInt32()).FirstOrDefault());
            }
            else if (item is ControllerItem)
            {
                var editor = CreateElement<ControllerElementEditor, ControllerItem, TechController>(bounds, Adapter.TechControllers.FirstOrDefault());
                InitControllerItem(editor.ControllerItem);
            }
        }

        /// <summary>
        /// Creates a new element by the specified editor type, tech item type, bounds and tech item constructor value.
        /// </summary>
        /// <typeparam name="Editor">The type of the editor.</typeparam>
        /// <typeparam name="Tech">The type of the tech.</typeparam>
        /// <typeparam name="Value">The type of the value.</typeparam>
        /// <param name="bounds">The bounds.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private Editor CreateElement<Editor, Tech, Value>(Rect bounds, Value value) where Editor : IElementEditor where Tech : TechItem
        {
            TechItem item = Activator.CreateInstance(typeof(Tech), new object[] { value }) as TechItem;
            IElementEditor editor = Activator.CreateInstance(typeof(Editor), new object[] { ((Tech)item), bounds }) as IElementEditor;
            Elements.Add(editor);
            return (Editor)editor;
        }

        /// <summary>
        /// Creates a new element by the specified editor type and tech item instance.
        /// </summary>
        /// <typeparam name="Editor">The type of the editor.</typeparam>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        private Editor CreateElement<Editor>(TechItem item) where Editor : IElementEditor
        {
            IElementEditor editor = Activator.CreateInstance(typeof(Editor), new object[] { item, item.GetBounds() }) as IElementEditor;
            Elements.Add(editor);
            return (Editor)editor;
        }

        /// <summary>
        /// Adds a new tech item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void AddTechItem(TechItem item)
        {
            if (item is MonitorItem)
            {
                (item as MonitorItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<MonitorElementEditor>(item);
            }
            else if (item is MeterItem)
            {
                (item as MeterItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<MeterElementEditor>(item);
            }
            else if (item is SingleGraphItem)
            {
                (item as SingleGraphItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<SingleGraphElementEditor>(item);
                InitSingleGraphitem(editor.GraphItem, editor);
            }
            else if (item is MultiGraphItem)
            {
                (item as MultiGraphItem).TechMonitor = Adapter.TechMonitors.Where(x => x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<MultiGraphElementEditor>(item);
                InitMultiGraphItem(editor.GraphItem, editor);
            }
            else if (item is MotorItem)
            {
                (item as MotorItem).HardwareMotorType = Adapter.HardwareMotorTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<MotorElementEditor>(item);
                InitMotorItem(editor.MotorItem);
            }
            else if (item is DispenserItem)
            {
                (item as DispenserItem).TechDispenser = Adapter.TechDispensers.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<DispenserElementEditor>(item);
                InitDispenserItem(editor.DispenserItem);
            }
            else if (item is ThreadMotionItem)
            {
                var editor = CreateElement<ThreadMotionElementEditor>(item);
                InitThreadMotionItem(editor.ThreadMotionItem);
            }
            else if (item is MotorGroupItem)
            {
                var editor = CreateElement<MotorGroupElementEditor>(item);
                InitMotorGroupItem(editor.MotorGroupItem);
            }
            else if (item is DigitalOutItem)
            {
                (item as DigitalOutItem).TechIo = Adapter.TechIos.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<DigitalOutElementEditor>(item);
                InitDigitalOutItem(editor.DigitalOutItem);
            }
            else if (item is DigitalInItem)
            {
                (item as DigitalInItem).TechIo = Adapter.TechIos.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<DigitalInElementEditor>(item);
            }
            else if (item is ControllerItem)
            {
                (item as ControllerItem).TechController = Adapter.TechControllers.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<ControllerElementEditor>(item);
                InitControllerItem(editor.ControllerItem);
            }
        }

        /// <summary>
        /// Called when elements have been removed
        /// </summary>
        /// <param name="elements">The elements.</param>
        public void OnElementsRemoved(List<IElementEditor> elements)
        {
            //foreach (var element in elements)
            //{
            //    if (element.HostedElement is SingleGraphItem)
            //    {
            //        _singleControllers.Remove(element.HostedElement as SingleGraphItem);
            //        (element.HostedElement as SingleGraphItem).Editor.InnerGraph.InnerGraph.Dispose();
            //    }
            //    else if (element.HostedElement is MultiGraphItem)
            //    {
            //        _multiControllers.Remove(element.HostedElement as MultiGraphItem);
            //        (element.HostedElement as MultiGraphItem).Editor.InnerGraph.InnerGraph.Dispose();
            //    }
            //}
        }

        /// <summary>
        /// Called when elements have been pasted
        /// </summary>
        /// <param name="elements">The elements.</param>
        public void OnElementsPasted(List<IElementEditor> elements)
        {
            foreach (var element in elements)
            {
                if (element is SingleGraphElementEditor)
                {
                    var graphItem = element.HostedElement as SingleGraphItem;
                    var editor = element as SingleGraphElementEditor;
                    graphItem.Editor = editor;
                    editor.InnerGraph.InnerGraph.MaxPoints = Common.Helpers.GraphsHelper.GetMaxPoints(graphItem.TechMonitor.PointsPerFrame);

                    GraphController controller = new GraphController();
                    editor.InnerGraph.Controller = controller;

                    _singleControllers.Add(graphItem, controller);
                }
                else if (element is MultiGraphElementEditor)
                {
                    var graphItem = element.HostedElement as MultiGraphItem;
                    var editor = element as MultiGraphElementEditor;
                    editor.InnerGraph.InnerGraph.MaxPoints = Common.Helpers.GraphsHelper.GetMaxPoints(graphItem.TechMonitor.PointsPerFrame);
                    graphItem.Editor = editor;


                    GraphMultiController controller = new GraphMultiController();

                    for (int i = 0; i < graphItem.TechMonitor.ChannelCount; i++)
                    {
                        controller.AddSeries(new RealTimeGraphEx.DataSeries.DataYSeries()
                        {
                            UseFillAndStroke = true,
                            Name = graphItem.TechMonitor.Name.First() + (i + 1).ToString(),
                            Stroke = new SolidColorBrush(ColorHelper.GetRandomColor()),
                        });
                    }

                    editor.InnerGraph.Controller = controller;

                    _multiControllers.Add(graphItem, controller);
                }
                else if (element is MotorElementEditor)
                {
                    var motorItem = element.HostedElement as MotorItem;
                    InitMotorItem(motorItem);
                }
                else if (element is DispenserElementEditor)
                {
                    var dispenser = element.HostedElement as DispenserItem;
                    InitDispenserItem(dispenser);
                }
                else if (element is DigitalOutItem)
                {
                    var ioItem = element.HostedElement as DigitalOutItem;
                    InitDigitalOutItem(ioItem);
                }
                else if (element is ThreadMotionItem)
                {
                    var threadMotionItem = element.HostedElement as ThreadMotionItem;
                    InitThreadMotionItem(threadMotionItem);
                }
                else if (element is MotorGroupItem)
                {
                    var motorGroupItem = element.HostedElement as MotorGroupItem;
                    InitMotorGroupItem(motorGroupItem);
                }
                else if (element is ControllerItem)
                {
                    var controllerItem = element.HostedElement as ControllerItem;
                    InitControllerItem(controllerItem);
                }
            }
        }

        #endregion

        #region Init Tech Items

        /// <summary>
        /// Initializes the motor item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitMotorItem(MotorItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            Code = item.HardwareMotorType.Code,
                            Direction = MotorDirection.Forward,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            Code = item.HardwareMotorType.Code,
                        });
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            Code = item.HardwareMotorType.Code,
                            Direction = MotorDirection.Backward,
                        });
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            Code = item.HardwareMotorType.Code,
                        });
                    }
                    else if (action == MotorActionType.HomingStarted)
                    {
                        item.HomingProgress = 0;
                        item.IsHoming = true;
                        item.IsHomingCompleted = false;

                        MachineOperator.StartMotorHoming(new MotorHomingRequest()
                        {
                            Code = item.HardwareMotorType.Code
                        })
                        .Subscribe((response) =>
                        {

                            item.HomingMaximumProgress = response.MaxProgress;
                            item.HomingProgress = response.Progress;

                        }, () =>
                        {

                            item.IsHoming = false;
                            item.IsHomingCompleted = true;

                        });
                    }
                    else if (action == MotorActionType.HomingStopped)
                    {
                        await MachineOperator.StopMotorHoming(new MotorAbortHomingRequest()
                        {
                            Code = item.HardwareMotorType.Code,
                        });

                        item.IsHoming = false;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the dispenser item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitDispenserItem(DispenserItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartDispenserJogging(new DispenserJoggingRequest()
                        {
                            Code = item.TechDispenser.Code,
                            Direction = MotorDirection.Forward,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await MachineOperator.StopDispenserJogging(new DispenserAbortJoggingRequest()
                        {
                            Code = item.TechDispenser.Code,
                        });
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await MachineOperator.StartDispenserJogging(new DispenserJoggingRequest()
                        {
                            Code = item.TechDispenser.Code,
                            Direction = MotorDirection.Backward,
                        });
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopDispenserJogging(new DispenserAbortJoggingRequest()
                        {
                            Code = item.TechDispenser.Code,
                        });
                    }
                    else if (action == MotorActionType.HomingStarted)
                    {
                        item.HomingProgress = 0;
                        item.IsHoming = true;
                        item.IsHomingCompleted = false;

                        MachineOperator.StartDispenserHoming(new DispenserHomingRequest()
                        {
                            Code = item.TechDispenser.Code
                        })
                        .Subscribe((response) =>
                        {

                            item.HomingMaximumProgress = response.MaxProgress;
                            item.HomingProgress = response.Progress;

                        }, () =>
                        {

                            item.IsHoming = false;
                            item.IsHomingCompleted = true;

                        });
                    }
                    else if (action == MotorActionType.HomingStopped)
                    {
                        await MachineOperator.StopDispenserHoming(new DispenserAbortHomingRequest()
                        {
                            Code = item.TechDispenser.Code,
                        });

                        item.IsHoming = false;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the single graph item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="editor">The editor.</param>
        private void InitSingleGraphitem(SingleGraphItem item, SingleGraphElementEditor editor)
        {
            editor.InnerGraph.InnerGraph.MaxPoints = Common.Helpers.GraphsHelper.GetMaxPoints(item.TechMonitor.PointsPerFrame);
            item.Editor = editor;

            GraphController controller = new GraphController();
            editor.InnerGraph.Controller = controller;

            _singleControllers.Add(item, controller);
        }

        /// <summary>
        /// Initializes the multi graph item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="editor">The editor.</param>
        private void InitMultiGraphItem(MultiGraphItem item, MultiGraphElementEditor editor)
        {
            editor.InnerGraph.InnerGraph.MaxPoints = Common.Helpers.GraphsHelper.GetMaxPoints(item.TechMonitor.PointsPerFrame);
            item.Editor = editor;

            GraphMultiController controller = new GraphMultiController();

            for (int i = 0; i < item.TechMonitor.ChannelCount; i++)
            {
                controller.AddSeries(new RealTimeGraphEx.DataSeries.DataYSeries()
                {
                    UseFillAndStroke = true,
                    Name = item.TechMonitor.Name.First() + (i + 1).ToString(),
                    Stroke = new SolidColorBrush(ColorHelper.GetRandomColor()),
                });
            }

            editor.InnerGraph.Controller = controller;

            _multiControllers.Add(item, controller);
        }

        /// <summary>
        /// Initializes the thread motion item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitThreadMotionItem(ThreadMotionItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartThreadJogging(new ThreadJoggingRequest()
                        {
                            Direction = MotorDirection.Forward,
                        });
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await MachineOperator.StartThreadJogging(new ThreadJoggingRequest()
                        {
                            Direction = MotorDirection.Backward,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased || action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopThreadJogging(new ThreadAbortJoggingRequest());
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format(String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName)));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the motor group item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitMotorGroupItem(MotorGroupItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            Code = motor.Code,
                            Direction = MotorDirection.Forward,
                        })));
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            Code = motor.Code,
                        })));
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            Code = motor.Code,
                            Direction = MotorDirection.Backward,
                        })));
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            Code = motor.Code,
                        })));
                    }
                    //else if (action == MotorActionType.HomingStarted)
                    //{
                    //    item.HomingProgress = 0;
                    //    item.IsHoming = true;
                    //    item.IsHomingCompleted = false;

                    //    MachineOperator.StartMotorHoming(new MotorHomingRequest()
                    //    {
                    //        Code = item.TechMotor.Code
                    //    })
                    //    .Subscribe((response) =>
                    //    {

                    //        item.HomingMaximumProgress = response.Message.MaxProgress;
                    //        item.HomingProgress = response.Message.Progress;

                    //    }, () =>
                    //    {

                    //        item.IsHoming = false;
                    //        item.IsHomingCompleted = true;

                    //    });
                    //}
                    //else if (action == MotorActionType.HomingStopped)
                    //{
                    //    await MachineOperator.StopMotorHoming(new MotorAbortHomingRequest()
                    //    {
                    //        Code = item.TechMotor.Code,
                    //    });

                    //    item.IsHoming = false;
                    //}
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the digital out item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitDigitalOutItem(DigitalOutItem item)
        {
            item.ValueChanged += async (x, value) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetDigitalOut(new SetDigitalOutRequest() { Port = item.TechIo.Port, Value = value });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician set digital out command on '{0}'.", item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician set digital out command on '{0}'.", item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the controller item.
        /// </summary>
        /// <param name="item">The controller item.</param>
        private void InitControllerItem(ControllerItem item)
        {
            item.ValueChanged += async (x, value) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetComponentValue(new SetComponentValueRequest()
                    {
                        Component = (ValueComponent)item.TechController.Code,
                        Value = value
                    });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician set value component command on '{0}'.", item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician set value component command on '{0}'.", item.TechName));
                }
            };
        }

        /// <summary>
        /// Checks the machine operator.
        /// </summary>
        /// <exception cref="InvalidOperationException">No machine connected.</exception>
        private void CheckMachineOperator()
        {
            if (MachineOperator == null || MachineOperator.State != Transport.TransportComponentState.Connected)
            {
                throw new InvalidOperationException("No machine connected.");
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Opens a file open dialog to select a project file.
        /// </summary>
        public void OpenProject()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Select Technician Project File";
            dlg.Filter = "Technician Project File|*.tpf";

            if (dlg.ShowDialog().Value)
            {
                OpenProjectFile(dlg.FileName);
            }
        }

        /// <summary>
        /// Opens the specified project file path.
        /// </summary>
        /// <param name="fileName">File path.</param>
        public void OpenProjectFile(String fileName)
        {
            LoadProject(MachineTechViewProject.Load(fileName));
            _lastTechProjectFile = fileName;
        }

        /// <summary>
        /// Loads the specified project.
        /// </summary>
        /// <param name="project">The project.</param>
        public void LoadProject(MachineTechViewProject project)
        {
            using (_notification.PushTaskItem("Loading technician project file..."))
            {
                Elements.Clear();
                _singleControllers.Clear();
                _multiControllers.Clear();

                foreach (var item in project.Items)
                {
                    if (item is MotorGroupItem)
                    {
                        (item as MotorGroupItem).TechMotors = ObservablesEntitiesAdapter.Instance.HardwareMotorTypes.Where(x => (item as MotorGroupItem).ItemsGuids.Contains(x.Guid)).ToObservableCollection();
                    }

                    AddTechItem(item);
                }
            }
        }

        /// <summary>
        /// Opens the file save dialog for selecting a project file target.
        /// </summary>
        private void SaveAsProject()
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "Select Technician Project Location";
            dlg.Filter = "Technician Project File|*.tpf";

            if (dlg.ShowDialog().Value)
            {
                SaveProjectFile(dlg.FileName);
            }
        }

        /// <summary>
        /// Saves the current project to the specified file path.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        private void SaveProjectFile(String fileName)
        {
            using (_notification.PushTaskItem("Saving technician project file..."))
            {
                MachineTechViewProject project = GenerateProjectFile();
                project.Save(fileName);
                _lastTechProjectFile = fileName;
            }
        }

        /// <summary>
        /// Saves the current opened project file. If not project file is opened will call <see cref="SaveAsProject"/>.
        /// </summary>
        private void SaveProject()
        {
            if (File.Exists(_lastTechProjectFile))
            {
                SaveProjectFile(_lastTechProjectFile);
            }
            else
            {
                SaveAsProject();
            }
        }

        /// <summary>
        /// Generates a project file from the current element setup.
        /// </summary>
        /// <returns></returns>
        private MachineTechViewProject GenerateProjectFile()
        {
            MachineTechViewProject project = new MachineTechViewProject();

            foreach (var element in Elements)
            {
                if (element.HostedElement is MotorGroupItem)
                {
                    var group = element.HostedElement as MotorGroupItem;
                    group.ItemsGuids = group.TechMotors.Select(x => x.Guid).ToList();
                }

                (element.HostedElement as TechItem).SetBounds(element.GetBounds());
                project.Items.Add(element.HostedElement as TechItem);
            }

            return project;
        }

        #endregion

        #region IStudioModuleVM

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();
            _singleControllers.ToList().ForEach(x => x.Value.ChangeRenderMode(true));
        }

        public override void OnNavigatedFrom()
        {
            base.OnNavigatedFrom();
            _singleControllers.ToList().ForEach(x => x.Value.ChangeRenderMode(false));
        }

        public override void OnShuttingDown()
        {
            InvokeUINow(() =>
            {
                SettingsManager.Default.MachineStudio.TechnicianModule.LasTechProjectFile = _lastTechProjectFile;
            });
        }

        #endregion
    }
}