aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Logging/ViewModels/EventsViewVM.cs
blob: 2c3886ea4fb6a07bfcd82b2e35e60ef89eedad77 (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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Core.Commands;
using Tango.MachineStudio.Common.EventLogging;
using Tango.MachineStudio.Common.Messages;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Logging.Navigation;
using Tango.MachineStudio.Logging.Views;
using Tango.SharedUI;
using System.Data.Entity;

namespace Tango.MachineStudio.Logging.ViewModels
{
    public class EventsViewVM : ViewModel
    {
        private INotificationProvider _notification;
        private IStudioApplicationManager _application;
        private IEventLogger _eventLogger;
        private ObservableCollection<MachinesEvent> _realTimeEvents;
        private LoggingNavigationManager _navigation;
        private bool _dialog_shown;
        private ObservablesContext _db;
        private List<MachinesEvent> _history_events;

        private Machine _selectedMachine;
        public Machine SelectedMachine
        {
            get { return _selectedMachine; }
            set
            {
                if (_selectedMachine != value)
                {
                    _selectedMachine = value; RaisePropertyChangedAuto(); OnSelectedMachineChanged();
                }
            }
        }

        private ObservableCollection<MachinesEvent> _events;
        public ObservableCollection<MachinesEvent> Events
        {
            get { return _events; }
            set { _events = value; RaisePropertyChangedAuto(); }
        }

        private MachinesEvent _selectedEvent;
        public MachinesEvent SelectedEvent
        {
            get { return _selectedEvent; }
            set { _selectedEvent = value; RaisePropertyChangedAuto(); OnSelectedEventChanged(); }
        }

        private ObservableCollection<DateTime> _dates;
        public ObservableCollection<DateTime> Dates
        {
            get { return _dates; }
            set { _dates = value; RaisePropertyChangedAuto(); }
        }

        private DateTime _selectedDate;
        public DateTime SelectedDate
        {
            get { return _selectedDate; }
            set { _selectedDate = value; RaisePropertyChangedAuto(); OnSelectedDateChanged(); }
        }

        private DateTime _minDate;
        public DateTime MinDate
        {
            get { return _minDate; }
            set { _minDate = value; RaisePropertyChangedAuto(); }
        }

        private DateTime _maxDate;
        public DateTime MaxDate
        {
            get { return _maxDate; }
            set { _maxDate = value; RaisePropertyChangedAuto(); }
        }

        private bool _isRealTime;
        public bool IsRealTime
        {
            get { return _isRealTime; }
            set { _isRealTime = value; RaisePropertyChangedAuto(); OnSelectedDateChanged(); }
        }

        private TimelineViewVM _timelineViewVM;

        public TimelineViewVM TimelineViewVM
        {
            get { return _timelineViewVM; }
            set { _timelineViewVM = value; RaisePropertyChangedAuto(); }
        }

        public RelayCommand<MachinesEvent> DisplayTimelineCommand { get; set; }

        public RelayCommand NavigateToEventsCommand { get; set; }

        public RelayCommand NavigateToHomeCommand { get; set; }

        public EventsViewVM(INotificationProvider notification, IEventLogger eventLogger, IStudioApplicationManager application, LoggingNavigationManager navigation)
        {
            TimelineViewVM = new TimelineViewVM(notification);

            _navigation = navigation;
            _application = application;
            _notification = notification;
            _eventLogger = eventLogger;
            _realTimeEvents = new ObservableCollection<MachinesEvent>();
            _eventLogger.NewLog += _eventLogger_NewLog;

            DisplayTimelineCommand = new RelayCommand<MachinesEvent>(DisplayTimeline);
            NavigateToEventsCommand = new RelayCommand(() => _navigation.NavigateTo(LoggingNavigationView.EventsView));
            NavigateToHomeCommand = new RelayCommand(() => _navigation.NavigateTo(LoggingNavigationView.HomeView));
        }

        private void _eventLogger_NewLog(object sender, MachinesEvent machineEvent)
        {
            InvokeUI(() =>
            {
                _realTimeEvents.Insert(0, machineEvent);
            });
        }

        private async void OnSelectedMachineChanged()
        {
            if (SelectedMachine != null)
            {
                using (_notification.PushTaskItem("Loading machine events..."))
                {
                    try
                    {
                        await Task.Factory.StartNew(() =>
                        {
                            _db = ObservablesContext.CreateDefault();

                            _db.EventTypes.Load();

                            DateTime now = DateTime.UtcNow.AddMonths(-1);

                            _history_events = _db.MachinesEvents.Where(x => x.MachineGuid == SelectedMachine.Guid && x.DateTime > now).Include(x => x.User).Include(x => x.User.Contact).Include(x => x.Machine).ToList();

                            Dates = new ObservableCollection<DateTime>();

                            foreach (var day in _history_events.GroupBy(x => x.DateTime.DayOfYear).Select(x => x.First().DateTime).OrderByDescending(x => x))
                            {
                                Dates.Add(day);
                            }

                            if (Dates.Count > 0)
                            {
                                MinDate = Dates.Min();
                                MaxDate = Dates.Max();
                            }

                            SelectedDate = Dates.FirstOrDefault();
                        });
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error loading machine events.");
                        _notification.ShowError($"An error occurred while trying to load the selected machine events.\n{ex.FlattenMessage()}");
                    }
                }
            }
        }

        private void OnSelectedDateChanged()
        {
            if (SelectedDate != null && SelectedMachine != null)
            {
                if (IsRealTime)
                {
                    Events = _realTimeEvents;
                }
                else if (_history_events != null)
                {
                    Events = _history_events.Where(x => x.DateTime.DayOfYear == SelectedDate.Date.DayOfYear).OrderByDescending(x => x.DateTime).ToObservableCollection();
                }
            }
        }

        private void OnSelectedEventChanged()
        {
            if (SelectedEvent != null && SelectedEvent.Type != BL.Enumerations.EventTypes.APPLICATION_STARTED && !_dialog_shown)
            {
                _dialog_shown = true;
                _notification.ShowModalDialog<EventDetailsViewVM, EventDetailsView>(new EventDetailsViewVM(SelectedEvent), (x) =>
                {

                }, () =>
                {
                    _dialog_shown = false;
                });
            }
        }

        private void DisplayTimeline(MachinesEvent ev)
        {
            var events = Events.OrderBy(x => x.DateTime).SkipWhile(x => x != ev).Skip(1).TakeWhile(x => x.DateTime > ev.DateTime && x.Type != BL.Enumerations.EventTypes.APPLICATION_STARTED).ToObservableCollection();
            events.Insert(0, ev);

            TimelineViewVM.Initialize(events.ToList());

            _navigation.NavigateTo(LoggingNavigationView.TimelineWrapperView);
        }
    }
}
class="na">[ExternalBridgeRequestHandlerMethod(typeof(FolderDownloadRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnFolderDownloadRequest(FolderDownloadRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); if (!Directory.Exists(request.Path)) { throw new FileNotFoundException("Could not find the specified directory."); } var tempFile = TemporaryManager.CreateImaginaryFile(); ZipFile.CreateFromDirectory(request.Path, tempFile); FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Download, tempFile); operation.IsPathTempZip = true; _operations.Add(operation.Id, operation); await receiver.SendGenericResponse(new FolderDownloadResponse() { OperationId = operation.Id, Length = new FileInfo(tempFile).Length }, token); } [ExternalBridgeRequestHandlerMethod(typeof(ChunkUploadRequest))] public async Task OnChunkUploadRequest(ChunkUploadRequest request, String token, ITransporter receiver) { this.ThrowIfDisabled(); FileSystemOperation operation; _operations.TryGetValue(request.OperationId, out operation); if (operation == null) { throw new ArgumentException("Invalid operation id."); } using (var stream = new FileStream(operation.Path, FileMode.Append)) { stream.Write(request.Data, 0, request.Data.Length); } if (request.IsCompleted) { if (!operation.IsPathTempZip) { File.Copy(operation.Path, operation.UploadPostPath, true); try { File.Delete(operation.Path); } catch { } } else { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(operation.Path)) { zip.ExtractAll(operation.UploadPostPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); } try { File.Delete(operation.Path); } catch { } } } await receiver.SendGenericResponse(new ChunkUploadResponse(), token, new TransportResponseConfig() { Priority = QueuePriority.Low }); } [ExternalBridgeRequestHandlerMethod(typeof(ChunkDownloadRequest))] public async Task OnChunkDownloadRequest(ChunkDownloadRequest request, String token, ITransporter receiver) { this.ThrowIfDisabled(); FileSystemOperation operation; _operations.TryGetValue(request.OperationId, out operation); if (operation == null) { throw new ArgumentException("Invalid operation id."); } FileStream stream = null; bool removeTempZipFile = false; try { stream = new FileStream(operation.Path, FileMode.Open); stream.Position = request.Position; byte[] data = new byte[Math.Min(request.MaxChunkSize, stream.Length - stream.Position)]; if (stream.Position + data.Length == stream.Length) { removeTempZipFile = true; } await stream.ReadAsync(data, 0, data.Length); stream.Dispose(); stream = null; await receiver.SendGenericResponse(new ChunkDownloadResponse() { Data = data }, token, new TransportResponseConfig() { Priority = QueuePriority.Low }); } catch (Exception ex) { stream?.Dispose(); throw ex; } finally { if (operation.IsPathTempZip && removeTempZipFile) { try { if (File.Exists(operation.Path)) { File.Delete(operation.Path); } } catch { } } } } [ExternalBridgeRequestHandlerMethod(typeof(AbortOperationRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnAbortOperationRequest(AbortOperationRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); FileSystemOperation operation; _operations.TryGetValue(request.OperationId, out operation); if (operation == null) { throw new ArgumentException("Invalid operation id."); } if (operation.Mode == FileSystemOperationMode.Upload) { if (File.Exists(operation.Path)) { File.Delete(operation.Path); } } else if (operation.IsPathTempZip) { if (File.Exists(operation.Path)) { File.Delete(operation.Path); } } await receiver.SendGenericResponse(new AbortOperationResponse(), token); } [ExternalBridgeRequestHandlerMethod(typeof(MoveRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnMoveRequest(MoveRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); _manager.Move(request); await receiver.SendGenericResponse(new MoveResponse(), token); } [ExternalBridgeRequestHandlerMethod(typeof(CopyRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnCopyRequest(CopyRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); _manager.Copy(request); await receiver.SendGenericResponse(new CopyResponse(), token); } [ExternalBridgeRequestHandlerMethod(typeof(DeleteRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnDeleteRequest(DeleteRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); _manager.Delete(request.Path); await receiver.SendGenericResponse(new DeleteResponse(), token); } [ExternalBridgeRequestHandlerMethod(typeof(CreateFolderRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnCreateFolderRequest(CreateFolderRequest request, String token, ExternalBridgeReceiver receiver) { this.ThrowIfDisabled(); var dto = _manager.CreateFolder(request.Path, request.FolderName); await receiver.SendGenericResponse(new CreateFolderResponse() { FolderItem = dto }, token); } [ExternalBridgeRequestHandlerMethod(typeof(PerformDiskSpaceOptimizationRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnPerformDiskSpaceOptimizationRequest(PerformDiskSpaceOptimizationRequest request, String token, ExternalBridgeReceiver receiver) { var deletedBytes = _manager.PerformDiskSpaceOptimization(); await receiver.SendGenericResponse(new PerformDiskSpaceOptimizationResponse() { DeletedBytes = deletedBytes }, token); } [ExternalBridgeRequestHandlerMethod(typeof(GetLogFilesRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)] public async Task OnGetLogFilesRequest(GetLogFilesRequest request, String token, ExternalBridgeReceiver receiver) { FolderItem folder = null; if (request.LogFileType == RemoteLogFileType.Application) { var fileLogger = LogManager.RegisteredLoggers.SingleOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger; if (fileLogger == null) { throw new InvalidOperationException("Could not locate the application file logger."); } folder = await _manager.GetFolder(fileLogger.Folder, false, "*.log") as FolderItem; } else { if (MachineOperator.EmbeddedLogsFolder == null) { throw new InvalidOperationException("The firmware file logger folder could not be read."); } folder = await _manager.GetFolder(MachineOperator.EmbeddedLogsFolder, false, "*.log") as FolderItem; } GetLogFilesResponse response = new GetLogFilesResponse(); foreach (var file in folder.Items.OfType<FileItem>().OrderByDescending(x => x.DateCreated).DistinctBy(x => x.Name)) { response.LogFiles.Add(new RemoteLogFile() { DateModified = file.DateModified, DateCreated = file.DateCreated, Name = file.Name, Path = file.Path, Length = new FileInfo(file.Path).Length }); } await receiver.SendGenericResponse(response, token); } public void OnReceiverDisconnected(ExternalBridgeReceiver receiver) { if (_webRtcClients.ContainsKey(receiver)) { try { LogManager.Log("External bridge receiver disconnected. Disposing file system service WebRTC channel..."); var webRtcTransporter = _webRtcClients[receiver]; _webRtcClients.Remove(receiver); webRtcTransporter.Dispose(); } catch (Exception ex) { LogManager.Log(ex, "Error disposing the WebRTC channel."); } } } } }