aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Tango.FSE.UI/Connection/DefaultMachineProvider.cs
blob: 7452117051a34d65bf4cd4d4612e7b1e77ad5edc (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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
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
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.ExtensionMethods;
using Tango.Core.Threading;
using Tango.Emulations.ExternalBridge;
using Tango.FSE.BL;
using Tango.FSE.Common;
using Tango.FSE.Common.Authentication;
using Tango.FSE.Common.Build;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.FSEApplication;
using Tango.FSE.Common.Notifications;
using Tango.FSE.UI.Dialogs;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Operation;
using Tango.Logging;
using Tango.PMR.Integration;
using Tango.SharedUI;
using Tango.Transport;

namespace Tango.FSE.UI.Connection
{
    /// <summary>
    /// Represents the default <see cref="IMachineProvider"/> implementation.
    /// </summary>
    /// <seealso cref="Tango.FSE.Common.FSEExtendedObject" />
    /// <seealso cref="Tango.FSE.Common.Connection.IMachineProvider" />
    public class DefaultMachineProvider : FSEExtendedObject, IMachineProvider
    {
        private List<EventRegistration> _eventRegistrations;
        private String _lastMachineSerialNumber;
        private DateTime _connectionStartTime;
        private System.Timers.Timer _connectionTimer;
        private FSEMachineEventsStateProvider _machineEventsStateProvider;

        [TangoInject]
        private INotificationProvider NotificationProvider { get; set; }

        [TangoInject]
        private IAuthenticationProvider AuthenticationProvider { get; set; }

        [TangoInject]
        private FSEServicesContainer Services { get; set; }

        [TangoInject]
        private IBuildProvider BuildProvider { get; set; }

        #region Events

        /// <summary>
        /// Occurs when machine operator has connected.
        /// </summary>
        public event EventHandler<MachineConnectedEventArgs> MachineConnected;

        /// <summary>
        /// Occurs when the machine operator has disconnected.
        /// </summary>
        public event EventHandler<MachineDisconnectedEventArgs> MachineDisconnected;

        #endregion

        #region Properties

        private Machine _machine;
        /// <summary>
        /// Gets the database machine entity associated with the current machine.
        /// </summary>
        public Machine Machine
        {
            get { return _machine; }
            private set { _machine = value; RaisePropertyChangedAuto(); }
        }

        private bool _isConnected;
        /// <summary>
        /// Gets or sets a value indicating whether a machine is currently connected.
        /// </summary>
        public bool IsConnected
        {
            get { return _isConnected; }
            private set { _isConnected = value; RaisePropertyChangedAuto(); RaisePropertyChanged(nameof(ConnectionType)); RaisePropertyChanged(nameof(IsPPCAvailable)); }
        }

        /// <summary>
        /// Gets the current connected machine connection type.
        /// </summary>
        public MachineConnectionTypes ConnectionType
        {
            get
            {
                if (MachineOperator.GetType() == typeof(ExternalBridgeUsbClient))
                {
                    return MachineConnectionTypes.USB;
                }
                else if (MachineOperator.GetType() == typeof(ExternalBridgeTcpClient))
                {
                    return MachineConnectionTypes.Wifi;
                }
                else if (MachineOperator.GetType() == typeof(ExternalBridgeSignalRClient))
                {
                    return MachineConnectionTypes.SignalR;
                }
                else
                {
                    return MachineConnectionTypes.Emulator;
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="ConnectionType" /> equals <see cref="MachineConnectionTypes.Wifi" /> or <see cref="MachineConnectionTypes.SignalR" />.
        /// </summary>
        public bool IsPPCAvailable
        {
            get { return IsConnected && ConnectionType.IsRemote(); }
        }

        private TimeSpan _connectionTime;
        /// <summary>
        /// Gets the connection time span.
        /// </summary>
        public TimeSpan ConnectionTime
        {
            get { return _connectionTime; }
            set { _connectionTime = value; RaisePropertyChangedAuto(); }
        }

        private bool _isBusy;
        /// <summary>
        /// Gets a value indicating whether this instance is busy connecting/disconnecting.
        /// </summary>
        public bool IsBusy
        {
            get { return _isBusy; }
            private set { _isBusy = value; RaisePropertyChangedAuto(); }
        }

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

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultMachineProvider"/> class.
        /// </summary>
        public DefaultMachineProvider() : base()
        {
            _machineEventsStateProvider = new FSEMachineEventsStateProvider();

            MachineOperator = new ExternalBridgeTcpClient("N/A", "N/A");
            MachineOperator.MachineEventsStateProvider = _machineEventsStateProvider;
            MachineOperator.StateChanged += MachineOperator_StateChanged;
            MachineOperator.As<ExternalBridgeTcpClient>().SessionClosed += DefaultMachineProvider_SessionClosed;

            _connectionTimer = new System.Timers.Timer(1000);
            _connectionTimer.Elapsed += _connectionTimer_Elapsed;
            _connectionTimer.Start();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Connects to the specified machine.
        /// </summary>
        /// <param name="machine">The machine.</param>
        /// <returns></returns>
        public async Task<bool> ConnectToMachine(IExternalBridgeClient machine)
        {
            try
            {
                LogManager.Log($"Connecting to machine '{machine.GetType().Name}' => '{machine.SerialNumber}' => '{machine.Adapter?.Address}'...");

                IsBusy = true;

                MachineConnectionBaseViewVM vm = null;

                LogManager.Log("Invoking machine connection dialog...");

                if (machine.GetType() == typeof(ExternalBridgeUsbClient))
                {
                    vm = await NotificationProvider.ShowDialog(new MachineConnectionUsbViewVM() { Machine = machine });
                }
                else if (machine.GetType() == typeof(EmulatorExternalBridge))
                {
                    vm = await NotificationProvider.ShowDialog(new MachineConnectionEmulatorViewVM() { Machine = machine });
                }
                else if (machine is ExternalBridgeTcpClient)
                {
                    var secureClient = machine.As<ExternalBridgeTcpClient>();

                    if (machine.GetType() == typeof(ExternalBridgeTcpClient))
                    {
                        vm = await NotificationProvider.ShowDialog(new MachineConnectionWifiViewVM(secureClient));
                    }
                    else
                    {
                        vm = await NotificationProvider.ShowDialog(new MachineConnectionSignalRViewVM(secureClient));
                    }

                    secureClient.LoginRequest = new ExternalBridgeLoginRequest()
                    {
                        AppID = BuildProvider.BuildName,
                        HostName = Environment.MachineName,
                        Password = (vm as MachineConnectionWifiViewVM).Password,
                        Intent = (vm as MachineConnectionWifiViewVM).SelectedIntent,
                        RequireSafetyLevelOperations = (vm as MachineConnectionWifiViewVM).RequireSafetyLevelOperations,
                        UserGuid = AuthenticationProvider.CurrentUser.Guid,
                        UserName = AuthenticationProvider.CurrentUser.Contact.FullName
                    };

                    secureClient.ForceProtocolConfiguration = Settings.ForceExternalBridgeProtocolConfiguration;

                    secureClient.ConfigureProtocolRequest = new ConfigureProtocolRequest()
                    {
                        EnableCompression = true,
                        GenericProtocol = GenericMessageProtocol.Bson
                    };

                    LogManager.Log($"Target machine requires a secure connection. Login Request:\n{secureClient.LoginRequest.ToJsonString()}");
                }
                else
                {
                    throw LogManager.Log(new NotSupportedException($"The specified type {machine.GetType().Name} is not supported."));
                }

                if (vm.DialogResult)
                {
                    if (IsConnected)
                    {
                        LogManager.Log("Another machine is currently connected. Disconnecting current machine...");
                        await DisconnectMachine();
                    }

                    IsBusy = true;

                    String serial = vm.GetMachineSerialNumber();
                    machine.SerialNumber = serial;

                    using (var task = NotificationProvider.PushTaskItem($"Connecting to machine '{serial}'..."))
                    {
                        LogManager.Log("Retrieving full machine details...");
                        var machineDB = await Services.MachinesService.GetMachineFull(serial);

                        if (machineDB == null)
                        {
                            throw LogManager.Log(new KeyNotFoundException("The specified machine was not found on the database."));
                        }

                        LogManager.Log("Reassigning previous machine operator event handlers...");
                        ReassignEventHandlers(MachineOperator, machine);

                        MachineOperator = machine;

                        ApplyOperatorSettings();

                        LogManager.Log("Connecting...");
                        await MachineOperator.Connect();

                        Machine = machineDB;

                        LogManager.Log("Machine successfully connected.");

                        IsConnected = true;
                        OnMachineConnected(MachineOperator);

                        if (machine.GetType() == typeof(ExternalBridgeUsbClient) || machine.GetType() == typeof(EmulatorExternalBridge))
                        {
                            LogManager.Log($"Connected machine is of type '{machine.GetType()}' requires uploading hardware configuration upon connection.");

                            task.UpdateProgress("Uploading hardware configuration...");
                            await Task.Delay(1000);

                            try
                            {
                                LogManager.Log("Uploading hardware configuration...");
                                await machine.UploadHardwareConfiguration(Machine.Configuration.HardwareVersion, Machine.Configuration);
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error uploading hardware configuration. The connection will remain but in an unsafe state.");
                                await NotificationProvider.ShowWarning($"Error uploading hardware configuration.\n{ex.FlattenMessage()}");
                            }
                        }

                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// Disconnects the current connected machine.
        /// </summary>
        /// <returns></returns>
        public async Task DisconnectMachine()
        {
            if (IsConnected)
            {
                LogManager.Log($"Disconnecting currently connected machine...");

                using (var task = NotificationProvider.PushTaskItem("Disconnecting from current machine..."))
                {
                    try
                    {
                        await Task.Delay(1500);
                        IsBusy = true;
                        await MachineOperator.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error disconnecting machine.");
                    }
                    finally
                    {
                        IsConnected = false;
                        IsBusy = false;
                        Machine = null;
                        OnMachineDisconnected(MachineOperator, null);
                    }
                }
            }
        }

        /// <summary>
        /// Disconnects the currently connected machine and displays a "waiting for reconnection dialog" with a timeout.
        /// Useful when doing remote application restart.
        /// </summary>
        /// <param name="beginDelay">The amount of time to wait before starting reconnection attempts.</param>
        /// <param name="timeout">The timeout for when to drop the reconnection attempt.</param>
        /// <param name="message">The message to display to the user</param>
        /// <returns></returns>
        public async Task DisconnectAndWaitForReconnection(TimeSpan beginDelay, TimeSpan timeout, String message = null)
        {
            LogManager.Log("Starting disconnect and wait for machine procedure...");
            LogManager.Log("Disconnecting from current machine...");

            IsBusy = true;

            try
            {
                IsConnected = false;
                await MachineOperator.Disconnect();
                LogManager.Log("Machine disconnected.");
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error disconnecting machine. Never mind...");
            }
            finally
            {
                OnMachineDisconnected(MachineOperator, null);
            }

            bool aborted = false;
            MachineWaitForConnectionViewVM vm = new MachineWaitForConnectionViewVM(MachineOperator, (int)timeout.TotalSeconds, message);
            vm.RequestCancel += (_, __) =>
            {
                vm.BlockCancel = true;
                aborted = true;
            };

            ThreadFactory.StartNew(() =>
            {
                Thread.Sleep(beginDelay);

                while (!aborted)
                {
                    LogManager.Log("Trying to reconnect (controlled disconnection)...");

                    try
                    {
                        MachineOperator.Connect().Wait();
                        IsConnected = true;
                        OnMachineConnected(MachineOperator);
                        LogManager.Log("Machine reconnected successfully. Closing dialog...");

                        InvokeUI(() =>
                        {
                            vm.Close(false);
                        });
                        break;
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error reconnecting to machine. Maybe next time...");
                    }

                    if (aborted) break;

                    Thread.Sleep(10000); //Try every 10 seconds..
                }

                if (!IsConnected)
                {
                    InvokeUI(() =>
                    {
                        vm.Close(false);
                    });
                }
            });

            System.Timers.Timer connectionTimer = new System.Timers.Timer();
            connectionTimer.Interval = 1000;
            connectionTimer.Elapsed += (_, __) =>
            {
                vm.RemainingSeconds--;

                if (vm.RemainingSeconds == 0 || IsConnected || aborted)
                {
                    vm.BlockCancel = true;
                    aborted = true;
                    connectionTimer.Stop();
                    connectionTimer.Dispose();
                }
            };
            connectionTimer.Start();

            await NotificationProvider.ShowDialog(vm);
            aborted = true;
            IsBusy = false;

            bool abortedByUser = vm.RemainingSeconds > 0;

            if (!IsConnected)
            {
                if (abortedByUser)
                {
                    LogManager.Log("Auto reconnection aborted by user.");
                }
                else
                {
                    LogManager.Log("Failed to auto-reconnect to the last machine (controlled disconnection).", LogCategory.Error);
                    await NotificationProvider.ShowError($"Failed to reconnect to the last connected machine.");
                }
            }
        }

        #endregion

        #region Machine Operator Event Handlers

        private void MachineOperator_StateChanged(object sender, TransportComponentState state)
        {
            if (IsConnected && state == TransportComponentState.Failed)
            {
                IsConnected = false;

                LogManager.Log($"Current machine connection has failed and disconnected after a period of {ConnectionTime} with exception: {MachineOperator.FailedStateException.FlattenMessage()}");
                LogManager.Log($"Trying reconnection procedure within {Settings.AutoMachineReconnectionTimeoutSeconds} seconds...");

                OnMachineDisconnected(MachineOperator, MachineOperator.FailedStateException);

                InvokeUI(async () =>
                {
                    var vm = await NotificationProvider.ShowDialog<MachineConnectionLostViewVM>(new MachineConnectionLostViewVM(MachineOperator, MachineOperator.FailedStateException.FlattenMessage(), Settings.AutoMachineReconnectionTimeoutSeconds));

                    if (vm.DialogResult)
                    {
                        try
                        {
                            LogManager.Log("Auto reconnection dialog accepted...");

                            IsBusy = true;
                            using (var task = NotificationProvider.PushTaskItem($"Reconnecting to machine '{Machine.SerialNumber}'..."))
                            {
                                await Task.Delay(2000);
                                await MachineOperator.Connect();
                                IsConnected = true;
                                OnMachineConnected(MachineOperator);

                                LogManager.Log("Machine reconnected successfully.");
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Failed to reconnect to the last machine.");
                            await NotificationProvider.ShowError($"Failed to reconnect to the last connected machine.\n{ex.FlattenMessage()}");
                        }
                        finally
                        {
                            IsBusy = false;
                        }
                    }
                    else
                    {
                        LogManager.Log("Auto reconnection dialog canceled. Reconnection aborted.");
                    }
                });
            }
        }

        private void DefaultMachineProvider_SessionClosed(object sender, EventArgs e)
        {
            IsConnected = false;

            String message = "The connection has been terminated by the remote machine.";

            LogManager.Log(message);

            OnMachineDisconnected(MachineOperator, new Exception(message));

            InvokeUI(() =>
            {
                NotificationProvider.ShowError(message);
            });
        }

        #endregion

        #region Event Handlers

        private void _connectionTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (IsConnected)
            {
                ConnectionTime = DateTime.Now - _connectionStartTime;
            }
        }

        #endregion

        #region Virtual Methods

        protected virtual void OnMachineConnected(IExternalBridgeClient machineOperator)
        {
            MachineConnected?.Invoke(this, new MachineConnectedEventArgs()
            {
                MachineOperator = machineOperator,
                DifferentFromPrevious = machineOperator.SerialNumber != _lastMachineSerialNumber,
            });

            _lastMachineSerialNumber = machineOperator.SerialNumber;
            _connectionStartTime = DateTime.Now;
        }

        protected virtual void OnMachineDisconnected(IExternalBridgeClient machineOperator, Exception exception)
        {
            machineOperator?.MachineEventsStateProvider.Reset();

            LogManager.Log($"Machine disconnected. Total connection time: {DateTime.Now - _connectionStartTime}.");

            MachineDisconnected?.Invoke(this, new MachineDisconnectedEventArgs()
            {
                MachineOperator = machineOperator,
                Exception = exception
            });
        }

        #endregion

        #region Private Methods

        private void ApplyOperatorSettings()
        {
            LogManager.Log("Applying machine operator settings...");

            MachineOperator.MachineEventsStateProvider = _machineEventsStateProvider;
            MachineOperator.EnableDiagnostics = true;
            MachineOperator.EnableMachineStatusUpdates = true;
            MachineOperator.EnableEmbeddedDebugging = true;
            MachineOperator.EnableEventsNotification = true;
            MachineOperator.EnableJobResume = false;
            MachineOperator.UseKeepAlive = true;
            MachineOperator.JobUnitsMethod = JobUnitsMethods.Device;
            MachineOperator.JobRunsLogger.JobSource = Tango.BL.Enumerations.JobSource.Remote;
            MachineOperator.KeepAliveTimeout = TimeSpan.FromSeconds(5);
            MachineOperator.KeepAliveRetries = 4;
            MachineOperator.RequestTimeout = TimeSpan.FromSeconds(10);
            MachineOperator.ContinuousRequestTimeout = TimeSpan.FromSeconds(10);

            if (ConnectionType.IsRemote())
            {
                ExternalBridgeTcpClient tcpClient = MachineOperator.As<ExternalBridgeTcpClient>();
                tcpClient.EnableApplicationLogs = true;
                tcpClient.InjectApplicationLogsToDefaultLogManager = false;
                tcpClient.LogEmbeddedDebuggingToFile = false;
            }
        }

        #endregion

        #region Machine Operator Event & Request Handlers Reassignment

        private class EventRegistration
        {
            public Delegate Handler { get; set; }
            public EventInfo EventInfo { get; set; }

            public void RemoveHandler(Object instance)
            {
                try
                {
                    EventInfo.RemoveEventHandler(instance, Handler);
                }
                catch
                {
                    Debug.WriteLine($"Cannot remove handler '{Handler.Method.Name}' for event '{instance.GetType().Name}.{EventInfo.Name}'.");
                }
            }

            public void AddHandler(Object instance)
            {
                try
                {
                    EventInfo.AddEventHandler(instance, Handler);
                }
                catch
                {
                    Debug.WriteLine($"Cannot add handler '{Handler.Method.Name}' for event '{instance.GetType().Name}.{EventInfo.Name}'.");
                }
            }
        }

        /// <summary>
        /// Reassigns the event handlers from the previous connected machine to a new one.
        /// </summary>
        /// <param name="oldInstance">The old instance.</param>
        /// <param name="newInstance">The new instance.</param>
        /// <exception cref="NullReferenceException"></exception>
        private void ReassignEventHandlers(IMachineOperator oldInstance, IMachineOperator newInstance)
        {
            oldInstance.CopyRequestHandlers(newInstance);

            if (_eventRegistrations == null)
            {
                _eventRegistrations = GetEventsRegistrations(oldInstance);
            }

            foreach (var registration in _eventRegistrations)
            {
                registration.RemoveHandler(oldInstance);
                registration.AddHandler(newInstance);
            }
        }

        private List<EventRegistration> GetEventsRegistrations(IMachineOperator instance)
        {
            List<EventRegistration> registrations = new List<EventRegistration>();

            var instanceEvents = instance.GetType().GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList();

            foreach (var ev in instanceEvents)
            {
                if (ev.IsMulticast)
                {

                    FieldInfo eventField = null;
                    Type type = instance.GetType();

                    while (eventField == null)
                    {
                        eventField = type.GetField(ev.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);

                        if (eventField == null)
                        {
                            type = type.BaseType;
                        }

                        if (type == typeof(Object))
                        {
                            break;
                        }
                    }

                    if (eventField == null)
                    {
                        throw new NullReferenceException($"Could not locate event field for '{ev.Name}'.");
                    }

                    var eventDelegate = (MulticastDelegate)type.GetField(ev.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static).GetValue(instance);

                    if (eventDelegate != null)
                    {
                        foreach (var handler in eventDelegate.GetInvocationList())
                        {
                            registrations.Add(new EventRegistration()
                            {
                                EventInfo = ev,
                                Handler = handler,
                            });
                        }
                    }
                }
            }

            return registrations;
        }

        #endregion

        #region Application Ready

        /// <summary>
        /// Called when is ready and user is logged-in. (happens every time a user logs-in)
        /// </summary>
        public void OnApplicationReady(IFSEApplicationManager applicationManager)
        {
            _machineEventsStateProvider.Init();
        }

        #endregion
    }
}