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);
        }
    }
}
Parse(request.Version); if (latestVersion == null || local_version > Version.Parse(latestVersion.Version)) { String newVersionFileName = "Machine Studio v" + local_version.ToString() + ".zip"; var manager = new BlobStorageManager(); var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER); var blob = container.CreateEmptyBlob(newVersionFileName); response.Token = Guid.NewGuid().ToString(); response.BlobAddress = blob.GenerateWriteSignature(TimeSpan.FromMinutes(30)); MachineStudioPendingUpload pending_upload = new MachineStudioPendingUpload() { UserGuid = user.Guid, Comments = request.Comments, Token = response.Token, Version = request.Version, BlobName = blob.Name, }; if (request.WithInstaller) { String installerVersionFileName = "Machine Studio v" + local_version.ToString() + ".exe"; var installerBlob = container.CreateEmptyBlob(installerVersionFileName); response.InstallerBlobAddress = installerBlob.GenerateWriteSignature(TimeSpan.FromMinutes(30)); pending_upload.InstallerBlobName = installerBlob.Name; } _pendingUploads.Add(pending_upload); } else { throw new ArgumentException("New version must be greater than latest version."); } } else { throw new AuthenticationException("Invalid user credentials."); } } return response; } /// <summary> /// Notifies about a version upload completion. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Invalid Token.</exception> [HttpPost] [JwtTokenFilter] public UploadCompletedResponse NotifyVersionUploadCompleted(UploadCompletedRequest request) { MachineStudioPendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token); if (upload != null) { _pendingUploads.RemoveAll(x => x.Token == upload.Token); using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { db.MachineStudioVersions.Add(new MachineStudioVersion() { Comments = upload.Comments, BlobName = upload.BlobName, InstallerBlobName = upload.InstallerBlobName, UserGuid = upload.UserGuid, Version = upload.Version, }); db.SaveChanges(); } return new UploadCompletedResponse(); } else { throw new ArgumentException("Invalid Token."); } } /// <summary> /// Gets the latest version. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> [HttpPost] public LatestVersionResponse GetLatestVersion(LatestVersionRequest request) { using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { var version = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); return new LatestVersionResponse() { Version = version != null ? version.Version : "0.0.0.0" }; } } /// <summary> /// Login to the service. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> /// <exception cref="AuthenticationException"></exception> [HttpPost] public LoginResponse Login(LoginRequest request) { AuthenticationResult authResult = null; User user = null; DataSource dataSource = null; IHashGenerator hash = new BasicHashGenerator(); Version client_version; if (!Version.TryParse(request.Version, out client_version)) { client_version = new Version("1.0.0.0"); } bool versionChangeRequired = false; String requiredVersion = null; bool isPasswordOK = false; try { authResult = _ad_manager.ValidateUserCredentials(request.Email, request.Password); isPasswordOK = true; } catch { } //Login via Active Directory if (request.Method == LoginMethod.ActiveDirectory) { try { authResult = _ad_manager.ValidateUserCredentials(request.Email, request.Password); } catch (Exception ex) { throw new AuthenticationException(ex.FlattenMessage()); } if (!_ad_manager.CanUserAccessCurrentEnvironment(request.Email)) { throw new AuthenticationException($"You do not have permissions to access the {MachineServiceConfig.DEPLOYMENT_SLOT.ToDescription()} environment."); } using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { db.Roles.ToList(); db.Permissions.ToList(); db.UsersRoles.ToList(); db.RolesPermissions.ToList(); user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower()).WithRolesAndPermissions().WithDeleted().Build(); if (user == null) { user = new User(); user.Email = request.Email; user.Password = hash.Encrypt(request.Password); user.Organization = db.Organizations.Include(x => x.Address).Single(x => x.Name == "Twine"); user.Address = user.Organization.Address.Clone(); user.Contact = new Contact() { FirstName = authResult.UserInfo.GivenName, LastName = authResult.UserInfo.FamilyName, FullName = authResult.UserInfo.GivenName + " " + authResult.UserInfo.FamilyName, Email = request.Email, }; db.UsersRoles.Add(new UsersRole() { User = user, Role = db.Roles.Single(x => (Roles)x.Code == Roles.User), }); db.UsersRoles.Add(new UsersRole() { User = user, Role = db.Roles.Single(x => (Roles)x.Code == Roles.MachineStudioUser), }); user.Password = hash.Encrypt(request.Password); db.Users.Add(user); } else { if (user.Deleted) { throw new AuthenticationException("Your account has been disabled. Please contact your administrator."); } } user.LastLogin = DateTime.UtcNow; db.SaveChanges(); } dataSource = new DataSource() { Address = MachineServiceConfig.DB_ADDRESS, Catalog = MachineServiceConfig.DB_CATALOG, Type = Core.DataSourceType.Azure, IntegratedSecurity = false, UserName = request.Email, Password = request.Password, }; } //Login via Database standard user else { var password = hash.Encrypt(request.Password); using (var db = ObservablesContextHelper.CreateContext()) { user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower() && (isPasswordOK || x.Password == password)).WithRolesAndPermissions().WithDeleted().Build(); if (user == null) { throw new AuthenticationException("Invalid email or password."); } if (user.Deleted) { throw new AuthenticationException("Your account has been disabled. Please contact your administrator."); } user.LastLogin = DateTime.UtcNow; db.SaveChanges(); } SQLServerManager sqlServer = new SQLServerManager(); var accessToken = sqlServer.GetAccessToken(); dataSource = new DataSource() { Address = MachineServiceConfig.DB_ADDRESS, Catalog = MachineServiceConfig.DB_CATALOG, Type = Core.DataSourceType.AccessToken, IntegratedSecurity = false, AccessToken = accessToken.AccessToken, AccessTokenExpiration = accessToken.ExpiresOn.UtcDateTime }; } //Enforce Machine Studio Version ? if (MachineServiceConfig.ENFORCE_MACHINE_STUDIO_VERSION) { using (var db = ObservablesContextHelper.CreateContext()) { var latest_version = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); if (latest_version != null && Version.Parse(latest_version.Version) != client_version) { versionChangeRequired = true; requiredVersion = latest_version.Version; } } } //Return data source return new LoginResponse() { DataSource = dataSource, AccessToken = WebToken<TokenObject>.CreateNew(MachineServiceConfig.JWT_TOKEN_SECRET, new TokenObject() { UserGuid = user.Guid, }, DateTime.UtcNow.AddDays(1)).AccessToken, VersionChangeRequired = versionChangeRequired, RequiredVersion = requiredVersion, PasswordChangeRequired = request.Method == LoginMethod.StandardUser && user.PasswordChangeRequired }; } [JwtTokenFilter] public RefreshTokenResponse RefreshToken(RefreshTokenRequest request) { SQLServerManager sqlServer = new SQLServerManager(); var accessToken = sqlServer.GetAccessToken(); //TokenManager tokenManager = new TokenManager(); //tokenManager.UpdateToken(request.AccessToken, accessToken.AccessToken, accessToken.ExpiresOn.UtcDateTime); return new RefreshTokenResponse() { AccessToken = accessToken.AccessToken, Expiration = accessToken.ExpiresOn.UtcDateTime, }; } [HttpPost] [JwtTokenFilter] public DownloadLatestPPCVersionResponse DownloadLatestPPCVersion(DownloadLatestPPCVersionRequest request) { DownloadLatestPPCVersionResponse response = new DownloadLatestPPCVersionResponse(); using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber); if (machine == null) { throw new AuthenticationException("The specified serial number could not be found."); } var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); response.Version = latest_machine_version.Version; var manager = new BlobStorageManager(); var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER); var blob = container.GetBlockBlobReference(latest_machine_version.BlobName); response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60)); if (!String.IsNullOrWhiteSpace(MachineServiceConfig.CDN_ENDPOINT)) { response.CdnAddress = MachineServiceConfig.CDN_ENDPOINT + blob.Uri.AbsolutePath; } DbCredentials credentials = new DbCredentials(); using (SmoManager smo = new SmoManager()) { credentials = smo.CreateRandomLoginAndUser(); Task.Delay(TimeSpan.FromMinutes(PPCController.SQL_TEMP_CREDENTIALS_EXP_MINUTS)).ContinueWith((x) => { using (SmoManager m = new SmoManager()) { m.DeleteLoginAndUser(credentials.UserName); } }); } response.DataSource = new DataSource() { Address = MachineServiceConfig.DB_ADDRESS, Catalog = MachineServiceConfig.DB_CATALOG, UserName = credentials.UserName, Password = credentials.Password, IntegratedSecurity = false, Type = DataSourceType.SQLServer, }; } return response; } #endregion } }