From cd467ed8a6afec8dcf50d8dc71c75d9d445f7489 Mon Sep 17 00:00:00 2001 From: Roy Ben-Shabat Date: Thu, 5 Dec 2019 11:30:45 +0200 Subject: Working on PPC packages... --- .../Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs') diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs index 01e67d3ce..4cc4ee46f 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs @@ -275,6 +275,66 @@ namespace Tango.PPC.UI.ViewModels base.OnApplicationReady(); StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Update.Extension, HandleSoftwareUpdatePackageLoaded); + + if (ApplicationManager.IsAfterUpdate) + { + RunPostUpdatePackages(); + } + } + + #endregion + + #region Post Update Packages + + private async void RunPostUpdatePackages() + { + await Task.Delay(1000); + + LogManager.Log("Application was loaded after an update. Checking for required post-update packages..."); + + bool required = false; + + try + { + required = await MachineUpdateManager.PostUpdatePackagesRequired(); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error checking for post-update packages."); + } + + if (required) + { + LogManager.Log("Post-update packages found and needs to be installed. Navigating to machine update and running post-update packages..."); + await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); + await NavigateTo(MachineUpdateView.UpdateProgressView); + try + { + var result = await MachineUpdateManager.RunPostUpdatePackages(); + + LogManager.Log("Post-update packages installed successfully."); + + await Task.Delay(2000); + + if (result.RestartRequired) + { + LogManager.Log("Restart required. Restarting..."); + ApplicationManager.Restart(); + } + else + { + await NavigationManager.NavigateTo(Common.Navigation.NavigationView.LayoutView); + } + } + catch (Exception ex) + { + LogManager.Log(ex, "Error occurred while running post-update packages."); + } + } + else + { + LogManager.Log("No post-update packages installation required."); + } } #endregion -- cgit v1.3.1 From 00f7facd947e0e8ce05a43d4f9d036e8f9a6a69e Mon Sep 17 00:00:00 2001 From: Roy Ben Shabat Date: Sat, 7 Dec 2019 22:46:37 +0200 Subject: Implemented auto check for update notification on PPC... Related Work Items: #1460 --- Software/DB/PPC/Tango.mdf | Bin 75497472 -> 75497472 bytes Software/DB/PPC/Tango_log.ldf | Bin 53673984 -> 53673984 bytes .../MachineUpdate/IMachineUpdateManager.cs | 13 +++++ .../MachineUpdate/MachineUpdateManager.cs | 61 +++++++++++++++++++++ .../PPC/Tango.PPC.UI/Images/update_available.png | Bin 0 -> 2573 bytes .../Navigation/DefaultNavigationManager.cs | 1 + .../UpdateAvailableNotificationItem.cs | 42 ++++++++++++++ .../UpdateAvailableNotificationItemView.xaml | 26 +++++++++ .../UpdateAvailableNotificationItemView.xaml.cs | 30 ++++++++++ .../PPC/Tango.PPC.UI/Tango.PPC.UI.csproj | 11 +++- .../Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs | 56 +++++++++++++++++++ .../PPC/Tango.PPC.UI/Views/LayoutView.xaml | 8 ++- 12 files changed, 244 insertions(+), 4 deletions(-) create mode 100644 Software/Visual_Studio/PPC/Tango.PPC.UI/Images/update_available.png create mode 100644 Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs create mode 100644 Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml create mode 100644 Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml.cs (limited to 'Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs') diff --git a/Software/DB/PPC/Tango.mdf b/Software/DB/PPC/Tango.mdf index de2de9f2b..a84785a6e 100644 Binary files a/Software/DB/PPC/Tango.mdf and b/Software/DB/PPC/Tango.mdf differ diff --git a/Software/DB/PPC/Tango_log.ldf b/Software/DB/PPC/Tango_log.ldf index d7d04ca21..e97b6d351 100644 Binary files a/Software/DB/PPC/Tango_log.ldf and b/Software/DB/PPC/Tango_log.ldf differ diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs index 299e18e57..3655aa462 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs @@ -11,6 +11,19 @@ namespace Tango.PPC.Common.MachineUpdate { public interface IMachineUpdateManager { + /// + /// Occurs when an application update is available. + /// + event EventHandler UpdateAvailable; + + /// + /// Gets or sets a value indicating whether to automatically check for new application updates. + /// + bool AutoCheckForUpdates { get; set; } + + /// + /// Gets the current machine update progress status. + /// MachineUpdateProgress Status { get; } /// diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs index 658c323de..e98f6d717 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs @@ -37,9 +37,16 @@ namespace Tango.PPC.Common.MachineUpdate private IPackageRunner _packageRunner; private PPCWebClient _client; private List _logs; + private System.Timers.Timer _checkForUpdateTimer; + private bool _isUpdating; #region Events + /// + /// Occurs when an application update is available. + /// + public event EventHandler UpdateAvailable; + /// /// Occurs when there is a text log message available. /// @@ -55,12 +62,25 @@ namespace Tango.PPC.Common.MachineUpdate #region Properties private MachineUpdateProgress _status; + /// + /// Gets the current machine update progress status. + /// public MachineUpdateProgress Status { get { return _status; } private set { _status = value; RaisePropertyChangedAuto(); } } + private bool _autoCheckForUpdates; + /// + /// Gets or sets a value indicating whether to automatically check for new application updates. + /// + public bool AutoCheckForUpdates + { + get { return _autoCheckForUpdates; } + set { _autoCheckForUpdates = value; RaisePropertyChangedAuto(); } + } + #endregion #region Constructors @@ -79,6 +99,10 @@ namespace Tango.PPC.Common.MachineUpdate _logs = new List(); LogManager.NewLog += LogManager_NewLog; + + _checkForUpdateTimer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds); + _checkForUpdateTimer.Elapsed += _checkForUpdateTimer_Elapsed; + _checkForUpdateTimer.Start(); } #endregion @@ -159,6 +183,8 @@ namespace Tango.PPC.Common.MachineUpdate LogManager.Log(xx, "Error notifying update failed."); } } + + _isUpdating = false; } private async void OnCompleted(MachineUpdateResult result, TaskCompletionSource completionSource, DownloadUpdateResponse response, String dbBackupFile) @@ -186,6 +212,8 @@ namespace Tango.PPC.Common.MachineUpdate LogManager.Log(ex, "Error notifying update completed."); } } + + _isUpdating = false; } private void OnCompleted(UpdateDBResponse response) @@ -205,6 +233,8 @@ namespace Tango.PPC.Common.MachineUpdate LogManager.Log(ex, "Error notifying database completed."); } } + + _isUpdating = false; } private void OnFailed(Exception ex, UpdateDBResponse response, bool performDatabaseRollback, String dbBackupFile, Tango.Core.DataSource localDataSource) @@ -256,6 +286,8 @@ namespace Tango.PPC.Common.MachineUpdate LogManager.Log(xx, "Error notifying database failed."); } } + + _isUpdating = false; } private String GetLogsStringAndClear() @@ -295,6 +327,8 @@ namespace Tango.PPC.Common.MachineUpdate try { + _isUpdating = true; + var machineServiceAddress = SettingsManager.Default.GetOrCreate().GetMachineServiceAddress(); LogManager.Log($"Starting machine update for serial number {serialNumber}..."); @@ -594,6 +628,7 @@ namespace Tango.PPC.Common.MachineUpdate return Task.Factory.StartNew(() => { + _isUpdating = true; UpdateDBResponse update_response = null; var localDataSource = SettingsManager.Default.GetOrCreate().DataSource; bool performDatabaseRollback = false; @@ -930,5 +965,31 @@ namespace Tango.PPC.Common.MachineUpdate } #endregion + + #region Auto Check For Update + + private async void _checkForUpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + if (AutoCheckForUpdates && !_isUpdating) + { + _checkForUpdateTimer.Stop(); + + try + { + var response = await CheckForUpdate(_machineProvider.Machine.SerialNumber); + if (response.IsUpdateAvailable) + { + _checkForUpdateTimer.Interval = TimeSpan.FromMinutes(60).TotalMilliseconds; + LogManager.Log($"New application version detected ({response.Version}). Raising event..."); + UpdateAvailable?.Invoke(this, response); + } + } + catch { } + + _checkForUpdateTimer.Start(); + } + } + + #endregion } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Images/update_available.png b/Software/Visual_Studio/PPC/Tango.PPC.UI/Images/update_available.png new file mode 100644 index 000000000..cafcf1d83 Binary files /dev/null and b/Software/Visual_Studio/PPC/Tango.PPC.UI/Images/update_available.png differ diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Navigation/DefaultNavigationManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/Navigation/DefaultNavigationManager.cs index 4c36c3cbe..2a825cc19 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Navigation/DefaultNavigationManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Navigation/DefaultNavigationManager.cs @@ -129,6 +129,7 @@ namespace Tango.PPC.UI.Navigation toView = MainView.Instance.NavigationControl.NavigateTo(view.ToString(), () => { + _currentVM = toView.DataContext; NotifyOnNavigated(fromView.DataContext, toView.DataContext); }); diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs new file mode 100644 index 000000000..4dea142b0 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.PPC.Common.Notifications; + +namespace Tango.PPC.UI.Notifications.NotificationItems +{ + /// + /// Represents a simple text message notification item which can be inserted into the application notifications panel. + /// + /// + public class UpdateAvailableNotificationItem : NotificationItem + { + /// + /// Initializes a new instance of the class. + /// + public UpdateAvailableNotificationItem() + { + CanClose = true; + } + + private String _version; + /// + /// Gets or sets the message. + /// + public String Version + { + get { return _version; } + set { _version = value; RaisePropertyChangedAuto(); } + } + + /// + /// Gets or sets the view type. + /// + public override Type ViewType + { + get { return typeof(UpdateAvailableNotificationItemView); } + } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml new file mode 100644 index 000000000..c4533b843 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml @@ -0,0 +1,26 @@ + + + + + + + + Version + + is available! + Tap to start updating your system. + + + + + diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml.cs new file mode 100644 index 000000000..791d40540 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Tango.PPC.UI.Notifications.NotificationItems +{ + /// + /// Represents the view. + /// + /// + /// + public partial class UpdateAvailableNotificationItemView : UserControl + { + public UpdateAvailableNotificationItemView() + { + InitializeComponent(); + } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Tango.PPC.UI.csproj b/Software/Visual_Studio/PPC/Tango.PPC.UI/Tango.PPC.UI.csproj index 3225eacc1..ab5492ab6 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Tango.PPC.UI.csproj +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Tango.PPC.UI.csproj @@ -149,6 +149,10 @@ + + + UpdateAvailableNotificationItemView.xaml + @@ -245,6 +249,10 @@ MainWindow.xaml Code + + MSBuild:Compile + Designer + Designer MSBuild:Compile @@ -365,6 +373,7 @@ + @@ -621,7 +630,7 @@ if $(ConfigurationName) == Debug copy /Y "$(TargetDir)Packages" "$(TargetDir)" - + \ No newline at end of file diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs index 4cc4ee46f..25a4f8c4b 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs @@ -12,6 +12,7 @@ using Tango.PPC.Common; using Tango.PPC.Common.MachineUpdate; using Tango.PPC.Common.Web; using Tango.PPC.UI.Dialogs; +using Tango.PPC.UI.Notifications.NotificationItems; using Tango.PPC.UI.ViewsContracts; namespace Tango.PPC.UI.ViewModels @@ -36,6 +37,7 @@ namespace Tango.PPC.UI.ViewModels private DbCompareResult _db_compare_result; private bool _isChecking; private CheckForUpdateResponse _checkUpdateResponse; + private UpdateAvailableNotificationItem _updateNotificationItem; #region Properties @@ -125,6 +127,8 @@ namespace Tango.PPC.UI.ViewModels NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule); NavigateTo(MachineUpdateView.UpdateCheckView); }); + + machineUpdateManager.UpdateAvailable += MachineUpdateManager_UpdateAvailable; } #endregion @@ -280,6 +284,24 @@ namespace Tango.PPC.UI.ViewModels { RunPostUpdatePackages(); } + else + { + MachineUpdateManager.AutoCheckForUpdates = MachineProvider.Machine.AutoCheckForUpdates; + } + } + + /// + /// Called when the navigation system has navigated to this VM view. + /// + public override void OnNavigatedTo() + { + base.OnNavigatedTo(); + + if (_updateNotificationItem != null) + { + _updateNotificationItem.Close(); + _updateNotificationItem = null; + } } #endregion @@ -389,5 +411,39 @@ namespace Tango.PPC.UI.ViewModels } #endregion + + #region Auto Check For Update + + private void MachineUpdateManager_UpdateAvailable(object sender, CheckForUpdateResponse e) + { + if (!IsVisible && _updateNotificationItem == null) + { + LogManager.Log($"New application version detected ({e.Version}). Pushing notification..."); + + InvokeUI(() => + { + _updateNotificationItem = new UpdateAvailableNotificationItem(); + _updateNotificationItem.Version = Version.Parse(e.Version).ToString(3); + _updateNotificationItem.Pressed += (_, __) => + { + _updateNotificationItem = null; + + if (!IsVisible) + { + LogManager.Log("Update available notification pressed. Navigating to update view..."); + NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); + CheckForUpdates(); + } + }; + _updateNotificationItem.Closed += (_, __) => + { + _updateNotificationItem = null; + }; + NotificationProvider.PushNotification(_updateNotificationItem); + }); + } + } + + #endregion } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/LayoutView.xaml b/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/LayoutView.xaml index 0cc21aa28..9315f9f0e 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/LayoutView.xaml +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/LayoutView.xaml @@ -239,10 +239,12 @@ - - + + + + - + -- cgit v1.3.1 From 3cd59dd3b04168ad91cb1fe51231e9b3ddd74705 Mon Sep 17 00:00:00 2001 From: Roy Ben Shabat Date: Sun, 8 Dec 2019 00:19:54 +0200 Subject: Implemented fast database update detection of RMLL, Hardware Versions & Color Catalogs. Related Work Items: #1622 --- Software/DB/PPC/Tango.mdf | Bin 75497472 -> 75497472 bytes Software/DB/PPC/Tango_log.ldf | Bin 53673984 -> 53673984 bytes .../ViewModels/MainViewVM.cs | 1 + .../ViewModels/MainViewVM.cs | 1 + .../MachineUpdate/MachineUpdateManager.cs | 23 +++++++++++++-- .../PPC/Tango.PPC.Common/Tango.PPC.Common.csproj | 3 +- .../Tango.PPC.Common/Web/CheckForUpdateRequest.cs | 11 ++++++++ .../Tango.PPC.Common/Web/CheckForUpdateResponse.cs | 7 +++++ .../PPC/Tango.PPC.Common/Web/UpdatedEntity.cs | 31 +++++++++++++++++++++ .../UpdateAvailableNotificationItem.cs | 10 +++++++ .../UpdateAvailableNotificationItemView.xaml | 16 +++++++---- .../Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs | 13 ++++++++- .../Controllers/PPCController.cs | 28 +++++++++++++++++++ 13 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 Software/Visual_Studio/PPC/Tango.PPC.Common/Web/UpdatedEntity.cs (limited to 'Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs') diff --git a/Software/DB/PPC/Tango.mdf b/Software/DB/PPC/Tango.mdf index a84785a6e..92884377a 100644 Binary files a/Software/DB/PPC/Tango.mdf and b/Software/DB/PPC/Tango.mdf differ diff --git a/Software/DB/PPC/Tango_log.ldf b/Software/DB/PPC/Tango_log.ldf index e97b6d351..9a2dcca84 100644 Binary files a/Software/DB/PPC/Tango_log.ldf and b/Software/DB/PPC/Tango_log.ldf differ diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Catalogs/ViewModels/MainViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Catalogs/ViewModels/MainViewVM.cs index 652ad3093..3cc4406d6 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Catalogs/ViewModels/MainViewVM.cs +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Catalogs/ViewModels/MainViewVM.cs @@ -305,6 +305,7 @@ namespace Tango.MachineStudio.Catalogs.ViewModels try { IsFree = false; + ActiveCatalog.LastUpdated = DateTime.UtcNow; await _activeCatalogContext.SaveChangesAsync(); await LoadCatalogs(); _notification.ShowInfo("Catalog updated successfully."); diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.HardwareDesigner/ViewModels/MainViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.HardwareDesigner/ViewModels/MainViewVM.cs index 7ebcbeb55..256ed24d6 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.HardwareDesigner/ViewModels/MainViewVM.cs +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.HardwareDesigner/ViewModels/MainViewVM.cs @@ -418,6 +418,7 @@ namespace Tango.MachineStudio.HardwareDesigner.ViewModels await Task.Factory.StartNew(() => { + CurrentVersion.LastUpdated = DateTime.UtcNow; _db.SaveChanges(); RefreshVersions(); diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs index e98f6d717..5296a9f34 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using Tango.BL; using Tango.Core; using Tango.Core.DB; using Tango.Core.ExtensionMethods; @@ -594,6 +595,8 @@ namespace Tango.PPC.Common.MachineUpdate { return Task.Factory.StartNew(() => { + _isUpdating = true; + var machineServiceAddress = SettingsManager.Default.GetOrCreate().GetMachineServiceAddress(); LogManager.Log($"Connecting to machine service on {machineServiceAddress}..."); @@ -606,12 +609,28 @@ namespace Tango.PPC.Common.MachineUpdate request.SerialNumber = serialNumber; request.Version = _app_manager.Version.ToString(); + try + { + using (ObservablesContext db = ObservablesContext.CreateDefault()) + { + request.Rmls = db.Rmls.ToList().Select(x => new UpdatedEntity(x)).ToList(); + request.HardwareVersions = db.HardwareVersions.ToList().Select(x => new UpdatedEntity(x)).ToList(); + request.Catalogs = db.ColorCatalogs.ToList().Select(x => new UpdatedEntity(x)).ToList(); + } + } + catch (Exception ex) + { + LogManager.Log(ex, "An error occurred while trying to fill the existing database entities before checking for updates."); + } + CheckForUpdateResponse update_response = null; update_response = _client.CheckForUpdates(request).Result; LogManager.Log($"Check for update response received: {Environment.NewLine}{update_response.ToJsonString()}"); + _isUpdating = false; + return update_response; }); } @@ -977,10 +996,10 @@ namespace Tango.PPC.Common.MachineUpdate try { var response = await CheckForUpdate(_machineProvider.Machine.SerialNumber); - if (response.IsUpdateAvailable) + if (response.IsUpdateAvailable || response.IsDatabaseUpdateAvailable) { _checkForUpdateTimer.Interval = TimeSpan.FromMinutes(60).TotalMilliseconds; - LogManager.Log($"New application version detected ({response.Version}). Raising event..."); + LogManager.Log($"New {(response.IsDatabaseUpdateAvailable ? "database updates" : "application version")} detected ({response.Version}). Raising event..."); UpdateAvailable?.Invoke(this, response); } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj b/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj index 671cac4f1..e3a23903e 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj @@ -226,6 +226,7 @@ + @@ -406,7 +407,7 @@ - + \ No newline at end of file diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs index b98848e4f..0feb32aaf 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs @@ -11,5 +11,16 @@ namespace Tango.PPC.Common.Web { public String SerialNumber { get; set; } public String Version { get; set; } + + public List Rmls { get; set; } + public List HardwareVersions { get; set; } + public List Catalogs { get; set; } + + public CheckForUpdateRequest() + { + Rmls = new List(); + HardwareVersions = new List(); + Catalogs = new List(); + } } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateResponse.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateResponse.cs index 370c0f5ea..63d870834 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateResponse.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateResponse.cs @@ -10,8 +10,15 @@ namespace Tango.PPC.Common.Web public class CheckForUpdateResponse : WebResponseMessage { public bool IsUpdateAvailable { get; set; } + public bool IsDatabaseUpdateAvailable { get; set; } public String Version { get; set; } public bool SetupFirmware { get; set; } public bool SetupFPGA { get; set; } + public UpdateDBResponse UpdateDBResponse { get; set; } + + public CheckForUpdateResponse() + { + UpdateDBResponse = new UpdateDBResponse(); + } } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/UpdatedEntity.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/UpdatedEntity.cs new file mode 100644 index 000000000..faee20678 --- /dev/null +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/UpdatedEntity.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.BL; + +namespace Tango.PPC.Common.Web +{ + public class UpdatedEntity + { + public UpdatedEntity() + { + + } + + public UpdatedEntity(IObservableEntity entity) : this() + { + Guid = entity.Guid; + LastUpdated = entity.LastUpdated; + } + + public String Guid { get; set; } + public DateTime LastUpdated { get; set; } + + public override string ToString() + { + return $"{Guid} | {LastUpdated}"; + } + } +} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs index 4dea142b0..9e336f276 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItem.cs @@ -31,6 +31,16 @@ namespace Tango.PPC.UI.Notifications.NotificationItems set { _version = value; RaisePropertyChangedAuto(); } } + private bool _isDatabaseUpdate; + /// + /// Gets or sets a value indicating whether this instance is database update. + /// + public bool IsDatabaseUpdate + { + get { return _isDatabaseUpdate; } + set { _isDatabaseUpdate = value; RaisePropertyChangedAuto(); } + } + /// /// Gets or sets the view type. /// diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml index c4533b843..fc9b05b9b 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Notifications/NotificationItems/UpdateAvailableNotificationItemView.xaml @@ -14,12 +14,16 @@ - - Version - - is available! - Tap to start updating your system. - + + + + Version + + is available! + Tap to start updating your system. + + + diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs index 25a4f8c4b..0371e94da 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs @@ -162,6 +162,16 @@ namespace Tango.PPC.UI.ViewModels LatestVersion = response.Version; await NavigateTo(MachineUpdateView.UpdateAvailableView); } + else if (response.IsDatabaseUpdateAvailable) + { + IsDbUpdate = true; + _db_compare_result = new DbCompareResult() + { + RequiresUpdate = true, + UpdateDBResponse = response.UpdateDBResponse + }; + await NavigateTo(MachineUpdateView.UpdateAvailableView); + } else { _db_compare_result = await MachineUpdateManager.UpdateDBCheck(MachineProvider.Machine.SerialNumber); @@ -418,12 +428,13 @@ namespace Tango.PPC.UI.ViewModels { if (!IsVisible && _updateNotificationItem == null) { - LogManager.Log($"New application version detected ({e.Version}). Pushing notification..."); + LogManager.Log($"New {(e.IsDatabaseUpdateAvailable ? "database updates" : "application version")} detected ({e.Version}). Pushing notification..."); InvokeUI(() => { _updateNotificationItem = new UpdateAvailableNotificationItem(); _updateNotificationItem.Version = Version.Parse(e.Version).ToString(3); + _updateNotificationItem.IsDatabaseUpdate = e.IsDatabaseUpdateAvailable && !e.IsUpdateAvailable; _updateNotificationItem.Pressed += (_, __) => { _updateNotificationItem = null; diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs index f0239978f..2dee09e69 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs @@ -314,6 +314,34 @@ namespace Tango.MachineService.Controllers response.Version = latest_machine_version.Version; + //Compare database + + var rmls = db.Rmls.Select(x => new { x.Guid, x.LastUpdated }).ToList(); + var hardwareVersions = db.HardwareVersions.Select(x => new { x.Guid, x.LastUpdated }).ToList(); + var catalogs = db.ColorCatalogs.Select(x => new { x.Guid, x.LastUpdated }).ToList(); + + bool hasDatabaseUpdates = false; + + hasDatabaseUpdates = rmls.Exists(x => request.Rmls.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Rmls.Exists(y => x.Guid == y.Guid)); + + if (!hasDatabaseUpdates) + { + hasDatabaseUpdates = hardwareVersions.Exists(x => request.HardwareVersions.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.HardwareVersions.Exists(y => x.Guid == y.Guid)); + } + + if (!hasDatabaseUpdates) + { + hasDatabaseUpdates = catalogs.Exists(x => request.Catalogs.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Catalogs.Exists(y => x.Guid == y.Guid)); + } + + if (hasDatabaseUpdates) + { + response.IsDatabaseUpdateAvailable = true; + response.UpdateDBResponse = UpdateDB(new UpdateDBRequest() { SerialNumber = request.SerialNumber }); + } + + //Compare database + if (machine.ForceVersionUpdate) { response.IsUpdateAvailable = true; -- cgit v1.3.1 From c7fa53084c674586ceee773ccbdc6b4c0a2ec7d4 Mon Sep 17 00:00:00 2001 From: Roy Ben Shabat Date: Mon, 9 Dec 2019 16:19:41 +0200 Subject: Implemented full TUP package update !!! --- .../FirmwareUpgrade/VersionFileDescriptor.proto | 1 - .../Tango.MachineStudio.MachineDesigner.csproj | 8 + .../ViewModels/MainViewVM.cs | 8 + .../ViewModels/TupViewVM.cs | 129 ++++++ .../Views/MachineDetailsView.xaml | 3 + .../Views/TupView.xaml | 60 +++ .../Views/TupView.xaml.cs | 28 ++ .../Tango.MachineStudio.Common.csproj | 17 +- .../Tup/TupFileBuilder.cs | 285 +++++++++++++ .../Tup/TupFileBuilderProgressEventArgs.cs | 16 + .../Web/DownloadLatestPPCVersionRequest.cs | 14 + .../Web/DownloadLatestPPCVersionResponse.cs | 21 + .../Web/MachineStudioWebClientBase.cs | 9 + .../Tango.MachineStudio.Common/packages.config | 1 + .../Tango.MachineStudio.UI.csproj | 6 +- .../MachineUpdate/IMachineUpdateManager.cs | 7 +- .../MachineUpdate/MachineUpdateManager.cs | 468 ++++++++++++++++++--- .../MachineUpdate/MachineUpdateResult.cs | 13 + .../MachineUpdate/UpdatePackageFile.cs | 13 - .../PPC/Tango.PPC.Common/Publish/PublishInfo.cs | 6 +- .../PPC/Tango.PPC.Common/Tango.PPC.Common.csproj | 1 - .../Tango.PPC.UI/Dialogs/UpdateFromFileView.xaml | 12 +- .../Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs | 30 +- .../PPC/Tango.PPC.UI/Views/MachineUpdateView.xaml | 5 +- Software/Visual_Studio/Tango.Core/DB/DbManager.cs | 33 +- .../FirmwareUpgrade/VersionFileDescriptor.cs | 37 +- .../ExaminerSequenceConfigurationRunner.cs | 9 + .../Tango.SQLExaminer/ExtensionMethods.cs | 21 + Software/Visual_Studio/Tango.SQLExaminer/Helper.cs | 2 +- .../Tango.SQLExaminer/Tango.SQLExaminer.csproj | 1 + .../SQLExaminer/SQLExaminer_TST.cs | 71 ++++ .../Controllers/MachineStudioController.cs | 65 +++ .../Controllers/PPCController.cs | 2 +- 33 files changed, 1257 insertions(+), 145 deletions(-) create mode 100644 Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/TupViewVM.cs create mode 100644 Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml create mode 100644 Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml.cs create mode 100644 Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilder.cs create mode 100644 Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilderProgressEventArgs.cs create mode 100644 Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionRequest.cs create mode 100644 Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionResponse.cs delete mode 100644 Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/UpdatePackageFile.cs create mode 100644 Software/Visual_Studio/Tango.SQLExaminer/ExtensionMethods.cs (limited to 'Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs') diff --git a/Software/PMR/Messages/FirmwareUpgrade/VersionFileDescriptor.proto b/Software/PMR/Messages/FirmwareUpgrade/VersionFileDescriptor.proto index ce44290a0..9e74cdee6 100644 --- a/Software/PMR/Messages/FirmwareUpgrade/VersionFileDescriptor.proto +++ b/Software/PMR/Messages/FirmwareUpgrade/VersionFileDescriptor.proto @@ -10,5 +10,4 @@ message VersionFileDescriptor string FileName = 1; string Version = 2; VersionFileDestination Destination = 3; - bytes CheckSum = 4; } \ No newline at end of file diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Tango.MachineStudio.MachineDesigner.csproj b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Tango.MachineStudio.MachineDesigner.csproj index 6225bd7ad..69cc75461 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Tango.MachineStudio.MachineDesigner.csproj +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Tango.MachineStudio.MachineDesigner.csproj @@ -93,6 +93,7 @@ + ColorCalibrationView.xaml @@ -130,6 +131,9 @@ MachineUpdatesView.xaml + + TupView.xaml + SpoolsView.xaml @@ -185,6 +189,10 @@ MSBuild:Compile Designer + + MSBuild:Compile + Designer + Designer MSBuild:Compile diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs index 820950290..768f93de1 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs @@ -140,6 +140,12 @@ namespace Tango.MachineStudio.MachineDesigner.ViewModels set { _machineUpdatesViewVM = value; RaisePropertyChangedAuto(); } } + private TupViewVM _tupViewVM; + public TupViewVM TupViewVM + { + get { return _tupViewVM; } + set { _tupViewVM = value; RaisePropertyChangedAuto(); } + } #endregion @@ -233,6 +239,7 @@ namespace Tango.MachineStudio.MachineDesigner.ViewModels ResetDeviceRegistrationCommand = new RelayCommand(ResetDeviceRegistration); MachineUpdatesViewVM = new MachineUpdatesViewVM(_notification); + TupViewVM = new TupViewVM(_notification); } #endregion @@ -478,6 +485,7 @@ namespace Tango.MachineStudio.MachineDesigner.ViewModels HardwareConfigurationViewVM.Init(ActiveMachine.Configuration); await MachineUpdatesViewVM.Init(ActiveMachine, ActiveMachineAdapter.Context); + TupViewVM.Init(ActiveMachine); ActiveMachine.Configuration.HardwareVersionChanged += Configuration_HardwareVersionChanged; diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/TupViewVM.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/TupViewVM.cs new file mode 100644 index 000000000..12ed09c75 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/TupViewVM.cs @@ -0,0 +1,129 @@ +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.BL.Entities; +using Tango.Core.Commands; +using Tango.MachineStudio.Common.Notifications; +using Tango.MachineStudio.Common.Tup; +using Tango.SharedUI; + +namespace Tango.MachineStudio.MachineDesigner.ViewModels +{ + public class TupViewVM : ViewModel + { + private INotificationProvider _notification; + + private String _latestVersion; + public String LatestVersion + { + get { return _latestVersion; } + set { _latestVersion = value; RaisePropertyChangedAuto(); } + } + + private Machine _machine; + public Machine Machine + { + get { return _machine; } + set { _machine = value; RaisePropertyChangedAuto(); } + } + + private String _filePath; + public String FilePath + { + get { return _filePath; } + set { _filePath = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } + } + + private TupFileBuilderProgressEventArgs _progress; + public TupFileBuilderProgressEventArgs Progress + { + get { return _progress; } + set { _progress = value; RaisePropertyChangedAuto(); } + } + + public RelayCommand CreateTupFileCommand { get; set; } + + public RelayCommand SelectFileCommand { get; set; } + + public TupViewVM() + { + + } + + public TupViewVM(INotificationProvider notification) : this() + { + _notification = notification; + CreateTupFileCommand = new RelayCommand(CreateTupFile, () => FilePath != null && IsFree); + SelectFileCommand = new RelayCommand(SelectFile); + } + + public void Init(Machine machine) + { + Machine = machine; + DisplayLatestPPCVersion(); + } + + private async void DisplayLatestPPCVersion() + { + TupFileBuilder builder = new TupFileBuilder(); + + try + { + LatestVersion = await builder.GetLatestPPCVersion(Machine.SerialNumber); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error retrieving latest PPC version."); + await Task.Delay(5000); + DisplayLatestPPCVersion(); + } + } + + private void SelectFile() + { + SaveFileDialog dlg = new SaveFileDialog(); + dlg.Title = "Select package location"; + dlg.Filter = "Tango Update Package Files|*.tup"; + dlg.DefaultExt = ".tup"; + dlg.FileName = LatestVersion == null ? $"{Machine.SerialNumber}_Update.tup" : $"{Machine.SerialNumber}_Update_v{LatestVersion}.tup"; + + if (dlg.ShowDialog().Value) + { + FilePath = dlg.FileName; + } + } + + private async void CreateTupFile() + { + try + { + LogManager.Log($"Generating TUP file to '{FilePath}'..."); + + IsFree = false; + TupFileBuilder builder = new TupFileBuilder(); + builder.Progress += Builder_Progress; + await builder.Build(Machine.SerialNumber, FilePath); + + LogManager.Log("TUP file generated successfully."); + _notification.ShowInfo("Tango update package created successfuly."); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error generating tup file."); + _notification.ShowError($"An error occurred while generating the .tup file.\n{ex.FlattenMessage()}"); + } + finally + { + IsFree = true; + } + } + + private void Builder_Progress(object sender, TupFileBuilderProgressEventArgs e) + { + Progress = e; + } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineDetailsView.xaml b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineDetailsView.xaml index 666a4ee4a..bcca83ca5 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineDetailsView.xaml +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineDetailsView.xaml @@ -64,6 +64,9 @@ + + + diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml new file mode 100644 index 000000000..895a26ca0 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + Create a complete update package (.tup) in order to update this machine offline using a removable storage device. + + The latest PPC version is + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml.cs b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml.cs new file mode 100644 index 000000000..fe01296d8 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/TupView.xaml.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Tango.MachineStudio.MachineDesigner.Views +{ + /// + /// Interaction logic for SpoolsView.xaml + /// + public partial class TupView : UserControl + { + public TupView() + { + InitializeComponent(); + } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tango.MachineStudio.Common.csproj b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tango.MachineStudio.Common.csproj index 7c0851d01..3ce667afe 100644 --- a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tango.MachineStudio.Common.csproj +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tango.MachineStudio.Common.csproj @@ -59,6 +59,9 @@ ..\..\Referenced Assemblies\SMO\Microsoft.SqlServer.AzureStorageEnum.dll + + ..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + @@ -83,6 +86,9 @@ + + Tup\PublishInfo.cs + GlobalVersionInfo.cs @@ -95,6 +101,10 @@ + + + + @@ -291,6 +301,10 @@ {8491d07b-c1f6-4b62-a412-41b9fd2d6538} Tango.SharedUI + + {e1e66ed9-597d-45fa-8048-de90a6930484} + Tango.SQLExaminer + {74e700b0-1156-4126-be40-ee450d3c3026} Tango.Transport @@ -387,10 +401,11 @@ + - + \ No newline at end of file diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilder.cs b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilder.cs new file mode 100644 index 000000000..6dd8b82f7 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilder.cs @@ -0,0 +1,285 @@ +using Ionic.Zip; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Tango.BL; +using Tango.Core; +using Tango.Core.DB; +using Tango.Core.DI; +using Tango.MachineStudio.Common.Web; +using Tango.SQLExaminer; +using Tango.Transport.Web; +using Tango.Core.ExtensionMethods; +using Tango.PPC.Common.Publish; +using Tango.Settings; +using Tango.Core.Components; +using System.Text.RegularExpressions; + +namespace Tango.MachineStudio.Common.Tup +{ + public class TupFileBuilder : ExtendedObject + { + public event EventHandler Progress; + + public Task Build(String serialNumber, String filePath) + { + return Task.Factory.StartNew(() => + { + String tempDbName = "Tango_TUP"; + var tempPackageFolder = TemporaryManager.CreateFolder(); + String tempBackupFolder = "C:\\MachineStudioTUP"; + String tempBackupFile = Path.Combine(tempBackupFolder, tempDbName + ".bak"); + var tempZipFile = TemporaryManager.CreateImaginaryFile(); + DbManager dbManager = null; + + LogManager.Log("Generating tup file..."); + LogManager.Log($"Tup file: '{filePath}.'"); + LogManager.Log($"Temporary db name: '{tempDbName}'."); + LogManager.Log($"Temporary package folder: '{tempPackageFolder}'."); + LogManager.Log($"Temporary db backup folder: '{tempBackupFolder}'."); + LogManager.Log($"Temporary db backup file: '{tempBackupFile}'."); + LogManager.Log($"Temporary zip file: '{tempZipFile}'."); + + try + { + LogManager.Log("Initializing..."); + + OnProgress("Initializing..."); + + Core.DataSource localDataSource = new Core.DataSource() + { + Address = "localhost\\SQLEXPRESS", + IntegratedSecurity = true, + Type = DataSourceType.SQLServer, + Catalog = null, + }; + + try + { + LogManager.Log($"Trying to connect via SQLEXPRESS:\n{localDataSource.ToJsonString()}"); + dbManager = DbManager.FromDataSource(localDataSource); + } + catch (Exception ex) + { + try + { + LogManager.Log(ex, "Could not connect using SQLEXPRESS. Trying local DB..."); + + CmdCommand command = new CmdCommand("sqllocaldb", "info \"MSSQLLocalDB\""); + var result = command.Run().Result; + + String pattern = "np:.+"; + Regex reg = new Regex(pattern); + var match = reg.Match(result.StandardOutput); + String address = match.ToString(); + if (address.Contains("np:")) + { + localDataSource.Address = address; + address = address.Trim().Replace("\r", ""); + } + else + { + throw new ArgumentException("Could not parse LocalDB address string."); + } + + LogManager.Log($"Trying to connect via LocalDB:\n{localDataSource.ToJsonString()}"); + dbManager = DbManager.FromDataSource(localDataSource); + } + catch (Exception x) + { + LogManager.Log(x, "Could not find any database service for this operation."); + throw x; + } + } + + + + OnProgress("Downloading latest PPC version..."); + + LogManager.Log("Connecting to machine service..."); + MachineStudioWebClient client = TangoIOC.Default.GetInstance(); + + LogManager.Log("Requesting latest PPC version from machine service..."); + var response = client.DownloadLatestPPCVersion(new DownloadLatestPPCVersionRequest() { SerialNumber = serialNumber }).Result; + + LogManager.Log($"Machine service response:\n{response.ToJsonString()}"); + + var remoteDataSource = response.DataSource; + + using (AutoFileDownloader downloader = new AutoFileDownloader(response.BlobAddress, response.CdnAddress, tempZipFile)) + { + downloader.Progress += (x, e) => + { + OnProgress($"Downloading latest PPC version '{response.Version}'...", false, e.Current, e.Total); + }; + + downloader.ResolveMode().GetAwaiter().GetResult(); + + LogManager.Log($"Downloading latest PPC version from: '{downloader.Address}'"); + + downloader.Download().Wait(); + } + + LogManager.Log("Extracting PPC version package..."); + + OnProgress("Extracting PPC package..."); + + using (ZipFile zip = new ZipFile(tempZipFile)) + { + int currentEntry = 0; + + zip.ExtractProgress += (x, args) => + { + if (args.EventType == ZipProgressEventType.Extracting_AfterExtractEntry) + { + OnProgress("Extracting PPC package...", false, currentEntry++, zip.Entries.Count); + } + }; + + zip.ExtractAll(tempPackageFolder); + } + + OnProgress("Extracting version information..."); + LogManager.Log("Extracting publish information..."); + PublishInfo publishInfo = PublishInfo.FromJson(File.ReadAllText(Path.Combine(tempPackageFolder, "version.json"))); + LogManager.Log($"Publish Information:\n{publishInfo}"); + + LogManager.Log("Modifying publish information to custom tup file..."); + publishInfo.IsMachineTupPackage = true; + publishInfo.MachineSerialNumber = serialNumber; + publishInfo.MachineDeploymentSlot = SettingsManager.Default.GetOrCreate().DeploymentSlot; + + OnProgress("Creating temporary database..."); + + LogManager.Log($"Creating temporary db backup directory '{tempBackupFolder}'"); + + Directory.CreateDirectory(tempBackupFolder); + + LogManager.Log($"Creating new database: '{tempDbName}'"); + + //Create temp db + dbManager.Create(tempDbName, Path.Combine(tempBackupFolder, tempDbName + ".mdf")); + + OnProgress("Generating database snapshot..."); + + LogManager.Log("Starting database synchronization..."); + + Thread.Sleep(2000); + + localDataSource.Catalog = tempDbName; + + ExaminerSequenceConfigurationRunner runner = new ExaminerSequenceConfigurationRunner( + Path.Combine(tempPackageFolder, "Provision Scripts", "config.xml"), + Path.Combine(tempPackageFolder, "Provision Scripts"), + remoteDataSource, + localDataSource, + serialNumber); + + runner.ScriptExecuting += (x, item) => + { + LogManager.Log($"Executing script '{item.FileName}'..."); + OnProgress($"{item.Name}..."); + }; + + runner.Log += (x, log) => + { + LogManager.Log(log); + }; + + runner.Run().GetAwaiter().GetResult(); + + OnProgress("Generating database snapshot..."); + + if (File.Exists(tempBackupFile)) + { + LogManager.Log($"Deleting file '{tempBackupFile}'"); + File.Delete(tempBackupFile); + } + + LogManager.Log($"Generating backup for '{tempDbName}' to '{tempBackupFile}'..."); + + dbManager.Backup(tempDbName, tempBackupFile); + + OnProgress("Injecting database snapshot to PPC package..."); + + using (ZipFile zip = new ZipFile(tempZipFile)) + { + LogManager.Log($"Injecting file '{tempBackupFile}' to original package at '{tempZipFile}'..."); + zip.AddFile(tempBackupFile, "/"); + + LogManager.Log($"Injecting modified publish information..."); + zip.UpdateEntry("version.json", publishInfo.ToJson()); + + zip.Save(); + } + + LogManager.Log($"Copying '{tempZipFile}' to '{filePath}'..."); + + File.Copy(tempZipFile, filePath, true); + + OnProgress("Completed", false, 100, 100); + + LogManager.Log("TUP file generation completed successfully."); + } + catch (Exception ex) + { + LogManager.Log(ex, "TUP file generation failed."); + OnProgress("Failed", false, 0, 100); + throw ex; + } + finally + { + LogManager.Log($"Removing '{tempZipFile}'."); + tempZipFile.Delete(); + LogManager.Log($"Removing '{tempPackageFolder}'."); + tempPackageFolder.Delete(); + + try + { + LogManager.Log($"Removing database '{tempDbName}'."); + dbManager.SetOffline(tempDbName); + dbManager.SetOnline(tempDbName); + dbManager.Delete(tempDbName); + dbManager.Dispose(); + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error removing temp database '{tempDbName}'."); + } + + try + { + LogManager.Log($"Removing '{tempBackupFolder}'."); + Directory.Delete(tempBackupFolder, true); + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error removing folder '{tempBackupFolder}'."); + } + } + }); + } + + public async Task GetLatestPPCVersion(String serialNumber) + { + MachineStudioWebClient client = TangoIOC.Default.GetInstance(); + var response = await client.DownloadLatestPPCVersion(new DownloadLatestPPCVersionRequest() { SerialNumber = serialNumber }); + return response.Version; + } + + private void OnProgress(String message, bool isIntermediate = true, double progress = 0, double total = 100) + { + Progress?.Invoke(this, new TupFileBuilderProgressEventArgs() + { + Message = message, + IsIntermediate = isIntermediate, + Progress = progress, + Total = total, + }); + } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilderProgressEventArgs.cs b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilderProgressEventArgs.cs new file mode 100644 index 000000000..ada69dd40 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Tup/TupFileBuilderProgressEventArgs.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tango.MachineStudio.Common.Tup +{ + public class TupFileBuilderProgressEventArgs + { + public double Progress { get; set; } + public double Total { get; set; } + public bool IsIntermediate { get; set; } + public String Message { get; set; } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionRequest.cs b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionRequest.cs new file mode 100644 index 000000000..24d465e69 --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionRequest.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Transport.Web; + +namespace Tango.MachineStudio.Common.Web +{ + public class DownloadLatestPPCVersionRequest : WebRequestMessage + { + public String SerialNumber { get; set; } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionResponse.cs b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionResponse.cs new file mode 100644 index 000000000..2cc6b731a --- /dev/null +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/DownloadLatestPPCVersionResponse.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.Core; +using Tango.Transport.Web; + +namespace Tango.MachineStudio.Common.Web +{ + public class DownloadLatestPPCVersionResponse : WebResponseMessage + { + public String Version { get; set; } + + public String BlobAddress { get; set; } + + public String CdnAddress { get; set; } + + public DataSource DataSource { get; set; } + } +} diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/MachineStudioWebClientBase.cs b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/MachineStudioWebClientBase.cs index 131f89515..c2d0dd3e6 100644 --- a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/MachineStudioWebClientBase.cs +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/Web/MachineStudioWebClientBase.cs @@ -94,5 +94,14 @@ namespace Tango.MachineStudio.Common.Web return Post("RefreshToken", request); } + /// + /// Executes the DownloadLatestPPCVersion action and returns Tango.MachineStudio.Common.Web.DownloadLatestPPCVersionResponse. + /// + /// + public Task DownloadLatestPPCVersion(Tango.MachineStudio.Common.Web.DownloadLatestPPCVersionRequest request) + { + return Post("DownloadLatestPPCVersion", request); + } + } } diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/packages.config b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/packages.config index f871776f5..6fd5091a8 100644 --- a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/packages.config +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.Common/packages.config @@ -9,4 +9,5 @@ + \ No newline at end of file diff --git a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Tango.MachineStudio.UI.csproj b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Tango.MachineStudio.UI.csproj index 991eb9da6..c6cf624b3 100644 --- a/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Tango.MachineStudio.UI.csproj +++ b/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Tango.MachineStudio.UI.csproj @@ -448,6 +448,10 @@ {8491d07b-c1f6-4b62-a412-41b9fd2d6538} Tango.SharedUI + + {e1e66ed9-597d-45fa-8048-de90a6930484} + Tango.SQLExaminer + {998f8471-dc1b-41b6-9d96-354e1b4e7a32} Tango.TFS @@ -661,7 +665,7 @@ if $(ConfigurationName) == Release RD /S /Q "$(TargetDir)ProtoCompilers\" - + \ No newline at end of file diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs index 3655aa462..e11eab3a5 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.PMR.Synchronization; +using Tango.PPC.Common.Publish; using Tango.PPC.Common.UpdatePackages; using Tango.PPC.Common.Web; @@ -43,14 +44,14 @@ namespace Tango.PPC.Common.MachineUpdate /// if set to true updates the embedded device firmware. /// if set to true updates the embedded device FPGA version and other parameters. /// - Task Update(String serialNumber, bool setupFirmware, bool setupFPGA); + Task Update(bool setupFirmware, bool setupFPGA); /// /// Performs a machine update using the specified software update package path. /// /// Name of the file. /// - Task UpdateFromTUP(String fileName); + Task UpdateFromTUP(String fileName, bool setupFirmware, bool setupFPGA); /// /// Checks if any update are available for the specified machine serial number. @@ -77,7 +78,7 @@ namespace Tango.PPC.Common.MachineUpdate /// /// The file path. /// - Task GetUpdatePackageFileInfo(String filePath); + Task GetUpdatePackageFileInfo(String filePath); /// /// Checks whether any post update packages needs to be installed. diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs index 5296a9f34..7e742ceb6 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs @@ -22,6 +22,7 @@ using Tango.PMR.Synchronization; using Tango.PPC.Common.Application; using Tango.PPC.Common.Connection; using Tango.PPC.Common.Navigation; +using Tango.PPC.Common.Publish; using Tango.PPC.Common.UpdatePackages; using Tango.PPC.Common.Web; using Tango.Settings; @@ -117,7 +118,10 @@ namespace Tango.PPC.Common.MachineUpdate private void LogManager_NewLog(object sender, LogItemBase e) { - _logs.Add(e); + if (_isUpdating) + { + _logs.Add(e); + } } #endregion @@ -133,37 +137,80 @@ namespace Tango.PPC.Common.MachineUpdate }); } - private async void OnFailed(Exception ex, TaskCompletionSource completionSource, DownloadUpdateResponse response, bool performDatabaseRollback, String dbBackupFile, Tango.Core.DataSource localDataSource) + private async void OnFailed(Exception ex, TaskCompletionSource completionSource, DownloadUpdateResponse response, bool performDatabaseRollback, String dbBackupFile, String backupsFolder, String tempDbName, Tango.Core.DataSource localDataSource, String tempUpdatePackageFolder = null) { LogManager.Log(ex, "An error occurred in machine update."); - if (performDatabaseRollback) + await Task.Factory.StartNew(() => { - LogManager.Log("Rolling back database changes..."); - using (DbManager db = DbManager.FromDataSource(localDataSource)) + if (performDatabaseRollback) + { + LogManager.Log("Rolling back database changes..."); + + using (DbManager db = DbManager.FromDataSource(localDataSource)) + { + try + { + UpdateProgress("Rollback", "Rolling back database changes..."); + db.Restore(localDataSource.Catalog, dbBackupFile); + LogManager.Log("Database restored successfully."); + } + catch (Exception e) + { + LogManager.Log(e, "Could not rollback the database."); + } + finally + { + try + { + File.Delete(dbBackupFile); + } + catch { } + } + } + } + + if (tempDbName != null) { try { - UpdateProgress("Rollback", "Rolling back database changes..."); - await Task.Factory.StartNew(() => db.Restore(localDataSource.Catalog, dbBackupFile)); - LogManager.Log("Database restored successfully."); + LogManager.Log($"Removing temporary database '{tempDbName}'..."); + using (DbManager dbManager = DbManager.FromDataSource(localDataSource)) + { + dbManager.SetOffline(tempDbName); + dbManager.SetOnline(tempDbName); + dbManager.Delete(tempDbName); + } } - catch (Exception e) + catch (Exception exx) { - LogManager.Log(e, "Could not rollback the database."); - throw ex; + LogManager.Log(exx, "Error removing temporary database."); } - finally + } + + try + { + Directory.Delete(backupsFolder, true); + } + catch (Exception ee) + { + LogManager.Log(ee, $"Error deleting backups folder '{backupsFolder}'."); + } + + if (tempUpdatePackageFolder != null) + { + try { - try - { - File.Delete(dbBackupFile); - } - catch { } + Directory.Delete(tempUpdatePackageFolder, true); + } + catch (Exception eee) + { + LogManager.Log(eee, "Error removing temporary package folder."); } } - } + + }); completionSource.SetException(ex); @@ -188,13 +235,50 @@ namespace Tango.PPC.Common.MachineUpdate _isUpdating = false; } - private async void OnCompleted(MachineUpdateResult result, TaskCompletionSource completionSource, DownloadUpdateResponse response, String dbBackupFile) + private async void OnCompleted(MachineUpdateResult result, TaskCompletionSource completionSource, DownloadUpdateResponse response, String tempDbName, String backupsFolder, Core.DataSource localDataSource) { - try + await Task.Factory.StartNew(() => { - File.Delete(dbBackupFile); - } - catch { } + if (tempDbName != null) + { + try + { + LogManager.Log($"Removing temporary database '{tempDbName}'..."); + using (DbManager dbManager = DbManager.FromDataSource(localDataSource)) + { + dbManager.SetOffline(tempDbName); + dbManager.SetOnline(tempDbName); + dbManager.Delete(tempDbName); + } + } + catch (Exception ex) + { + LogManager.Log(ex, "Error removing temporary database."); + } + } + + try + { + Directory.Delete(backupsFolder, true); + } + catch (Exception ex) + { + LogManager.Log(ex, $"Error deleting backups folder '{backupsFolder}'."); + } + + if (!result.RequiresBinariesUpdate) + { + try + { + Directory.Delete(result.UpdatePackagePath, true); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error removing temporary package folder."); + } + } + + }); completionSource.SetResult(result); @@ -315,7 +399,7 @@ namespace Tango.PPC.Common.MachineUpdate /// or /// /// Database tango does not exists. - public async Task Update(String serialNumber, bool setupFirmware, bool setupFPGA) + public async Task Update(bool setupFirmware, bool setupFPGA) { _logs.Clear(); @@ -325,6 +409,13 @@ namespace Tango.PPC.Common.MachineUpdate bool performDatabaseRollback = false; String dbBackupFile = null; DownloadUpdateResponse update_response = null; + String backupsFolder = "C:\\Backups"; + + //Create temporary folders for packages. + var _newPackageTempFolder = TemporaryManager.CreateFolder(); + _newPackageTempFolder.Persist = true; + + String serialNumber = _machineProvider.Machine.SerialNumber; try { @@ -371,10 +462,6 @@ namespace Tango.PPC.Common.MachineUpdate LogManager.Log($"Machine update response received: {Environment.NewLine}{update_response.ToJsonString()}"); - //Create temporary folders for packages. - var _newPackageTempFolder = TemporaryManager.CreateFolder(); - _newPackageTempFolder.Persist = true; - LogManager.Log($"Temporary package folder created: {_newPackageTempFolder}."); //Download software package. @@ -413,8 +500,12 @@ namespace Tango.PPC.Common.MachineUpdate UpdateProgress("Downloading software package", "Extracting package..."); LogManager.Log("Extracting downloaded zip file..."); - //Extract software package. - ZipFile.ExtractToDirectory(tempFile, _newPackageTempFolder); + + await Task.Factory.StartNew(() => + { + //Extract software package. + ZipFile.ExtractToDirectory(tempFile, _newPackageTempFolder); + }); LogManager.Log("Copying latest updater utility to application path..."); //Copy new updater utility to app path. @@ -464,8 +555,8 @@ namespace Tango.PPC.Common.MachineUpdate //Create Database Backup try { - Directory.CreateDirectory("C:\\Backups"); - dbBackupFile = $"C:\\Backups\\{Path.GetRandomFileName()}.bak"; + Directory.CreateDirectory(backupsFolder); + dbBackupFile = $"{backupsFolder}\\{Path.GetRandomFileName()}.bak"; LogManager.Log($"Creating database backup to '{dbBackupFile}'..."); await Task.Factory.StartNew(() => db.Backup(localDataSource.Catalog, dbBackupFile)); performDatabaseRollback = true; @@ -548,7 +639,7 @@ namespace Tango.PPC.Common.MachineUpdate handler.Failed += (_, ex) => { stream.Dispose(); - OnFailed(ex, result, update_response, performDatabaseRollback, dbBackupFile, localDataSource); + OnFailed(ex, result, update_response, performDatabaseRollback, dbBackupFile, backupsFolder, null, localDataSource, _newPackageTempFolder); }; handler.Completed += (_, __) => { @@ -557,12 +648,12 @@ namespace Tango.PPC.Common.MachineUpdate OnCompleted(new MachineUpdateResult() { UpdatePackagePath = _newPackageTempFolder, - }, result, update_response, dbBackupFile); + }, result, update_response, null, backupsFolder, localDataSource); }; handler.Canceled += (_, __) => { stream.Dispose(); - OnFailed(new Exception("The operation has been canceled."), result, update_response, performDatabaseRollback, dbBackupFile, localDataSource); + OnFailed(new Exception("The operation has been canceled."), result, update_response, performDatabaseRollback, dbBackupFile, backupsFolder, null, localDataSource, _newPackageTempFolder); }; handler.Progress += (_, e) => { @@ -574,12 +665,12 @@ namespace Tango.PPC.Common.MachineUpdate OnCompleted(new MachineUpdateResult() { UpdatePackagePath = _newPackageTempFolder, - }, result, update_response, dbBackupFile); + }, result, update_response, null, backupsFolder, localDataSource); } } catch (Exception ex) { - OnFailed(ex, result, update_response, performDatabaseRollback, dbBackupFile, localDataSource); + OnFailed(ex, result, update_response, performDatabaseRollback, dbBackupFile, backupsFolder, null, localDataSource, _newPackageTempFolder); } return await result.Task; @@ -875,31 +966,284 @@ namespace Tango.PPC.Common.MachineUpdate /// /// Name of the file. /// - public Task UpdateFromTUP(string fileName) + public async Task UpdateFromTUP(string fileName, bool setupFirmware, bool setupFPGA) { - return Task.Factory.StartNew(() => + _logs.Clear(); + + TaskCompletionSource result = new TaskCompletionSource(); + + var localDataSource = SettingsManager.Default.GetOrCreate().DataSource; + bool performDatabaseRollback = false; + String dbBackupFile = null; + String tempDbName = "Tango_TUP"; + String tempDbFileName = tempDbName + ".bak"; + String backupsFolder = "C:\\Backups"; + bool replaceBinaries = false; + + String serialNumber = _machineProvider.Machine.SerialNumber; + + //Create temporary folders for packages. + var _newPackageTempFolder = TemporaryManager.CreateFolder(); + _newPackageTempFolder.Persist = true; + + try { - LogManager.Log($"Starting machine update from update package '{fileName}'..."); + _isUpdating = true; + + LogManager.Log($"Starting machine update for serial number {serialNumber}..."); - //Create temporary folders for packages. - var _newPackageTempFolder = TemporaryManager.CreateFolder(); - _newPackageTempFolder.Persist = true; + //Connecting to machine... + LogManager.Log("Verifying machine connection and state..."); - LogManager.Log("Extracting downloaded zip file..."); - //Extract software package. - ZipFile.ExtractToDirectory(fileName, _newPackageTempFolder); + UpdateProgress("Verifying machine state", "Initializing..."); + + await Task.Delay(1000); + + IMachineOperator op = _machineProvider.MachineOperator; + + if (setupFirmware) + { + LogManager.Log("Machine is configured to update firmware..."); + + if (op.State != Transport.TransportComponentState.Connected) + { + throw LogManager.Log(new InvalidOperationException("Could not perform an update while the machine is not connected.")); + } + if (op.Status != MachineStatuses.ReadyToDye) + { + throw LogManager.Log(new InvalidOperationException($"Could not perform an update while the machine is in {op.Status} status.")); + } + } + + UpdateProgress("Exploring package", "Extracting..."); + LogManager.Log("Extracting package..."); + + LogManager.Log($"Temporary package folder created: {_newPackageTempFolder}."); + + await Task.Factory.StartNew(() => + { + //Extract software package. + ZipFile.ExtractToDirectory(fileName, _newPackageTempFolder); + }); + + //Extracting publish info + UpdateProgress("Exploring package", "Verifying..."); + PublishInfo publishInfo = PublishInfo.FromJson(File.ReadAllText(Path.Combine(_newPackageTempFolder, "version.json"))); + + if (!publishInfo.IsMachineTupPackage) + { + throw new InvalidOperationException("The specified tup file is invalid. Updating a machine from a tup file requires a custom generated package."); + } + + if (publishInfo.MachineSerialNumber != serialNumber) + { + throw new InvalidOperationException("The specified tup file is invalid. The package was generated for a different machine."); + } + + if (publishInfo.MachineDeploymentSlot != SettingsManager.Default.GetOrCreate().DeploymentSlot) + { + throw new InvalidOperationException("The specified tup file is invalid. The package was generated on a different environment."); + } + + replaceBinaries = _app_manager.Version.ToString() != publishInfo.ApplicationVersion; LogManager.Log("Copying latest updater utility to application path..."); + //Copy new updater utility to app path. File.Copy(Path.Combine(_newPackageTempFolder, "Tango.PPC.Updater.exe"), Path.Combine(PathHelper.GetStartupPath(), "Tango.PPC.Updater.exe"), true); - LogManager.Log("Update operation completed!"); + //Run pre-update packages. + try + { + UpdateProgress("Preparing", "Running update packages..."); + LogManager.Log("Running pre-update packages..."); + var packagesFolder = Path.Combine(_newPackageTempFolder, "Packages"); - return new MachineUpdateResult() + Version updateVersion = new Version(1, 0, 0, 0); + try + { + updateVersion = Version.Parse(publishInfo.ApplicationVersion); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error parsing new version string for package runner."); + } + + await _packageRunner.Run(PackageType.Pre, updateVersion, packagesFolder); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error running pre-update packages..."); + } + + //Synchronize database + UpdateProgress("Updating Database", "Initializing..."); + + UpdateProgress("Updating Database", "Connecting to local database..."); + LogManager.Log("Initializing database manager..."); + DbManager db = DbManager.FromDataSource(localDataSource); + + LogManager.Log("Checking Tango database exists on the local machine..."); + if (!db.Exists(localDataSource.Catalog)) + { + throw new InvalidProgramException("Database tango does not exists."); + } + + UpdateProgress("Updating Database", "Creating database backup..."); + + //Create Database Backup + try + { + Directory.CreateDirectory(backupsFolder); + dbBackupFile = $"{backupsFolder}\\{Path.GetRandomFileName()}.bak"; + LogManager.Log($"Creating database backup to '{dbBackupFile}'..."); + await Task.Factory.StartNew(() => db.Backup(localDataSource.Catalog, dbBackupFile)); + performDatabaseRollback = true; + LogManager.Log("Database backup created successfully."); + } + catch (Exception ex) + { + throw LogManager.Log(ex, "Update manager error while trying to create a database backup."); + } + + LogManager.Log("Extracting database file from package..."); + File.Copy(Path.Combine(_newPackageTempFolder, tempDbFileName), Path.Combine(backupsFolder, tempDbFileName)); + + LogManager.Log("Restoring package database as a new database..."); + db.RestoreAsNew(tempDbName, Path.Combine(backupsFolder, tempDbFileName), backupsFolder); + + Core.DataSource tempDbDataSource = new Core.DataSource(); + tempDbDataSource.Address = localDataSource.Address; + tempDbDataSource.IntegratedSecurity = localDataSource.IntegratedSecurity; + tempDbDataSource.Type = localDataSource.Type; + tempDbDataSource.Catalog = tempDbName; + + LogManager.Log("Disposing database manager."); + db.Dispose(); + + LogManager.Log($"Initializing {nameof(ExaminerSequenceConfigurationRunner)}..."); + + UpdateProgress("Updating Database", "Initializing update sequence..."); + + ExaminerSequenceConfigurationRunner runner = new ExaminerSequenceConfigurationRunner( + Path.Combine(_newPackageTempFolder, "Update Scripts", "config.xml"), + Path.Combine(_newPackageTempFolder, "Update Scripts"), + tempDbDataSource, + localDataSource, + serialNumber); + + runner.Log += (x, msg) => { - UpdatePackagePath = _newPackageTempFolder, + LogManager.Log(msg); + ProgressLog?.Invoke(this, msg); }; - }); + + runner.ScriptExecuting += (x, item) => + { + LogManager.Log($"Executing script {item.ToString()}..."); + UpdateProgress("Updating Database", item.Name + "..."); + }; + + LogManager.Log("Starting synchronization process..."); + + try + { + await runner.Run(); + LogManager.Log("Synchronization completed successfully!"); + UpdateProgress("Updating Database", "Database synchronization completed successfully."); + } + catch (Exception ex) + { + throw LogManager.Log(ex, "Update manager error while trying to synchronize database."); + } + + LogManager.Log("Getting setup firmware/fpga directly from db.."); + + using (var dbManager = DbManager.FromDataSource(localDataSource)) + { + try + { + String firmware = dbManager.GetValue($"SELECT TOP 1 * FROM MACHINES WHERE SERIAL_NUMBER = '{serialNumber}'", "SETUP_FIRMWARE"); + String fpga = dbManager.GetValue($"SELECT TOP 1 * FROM MACHINES WHERE SERIAL_NUMBER = '{serialNumber}'", "SETUP_FPGA"); + + setupFirmware = bool.Parse(firmware); + setupFPGA = bool.Parse(fpga); + } + catch (Exception ex) + { + LogManager.Log(ex, "Error getting new values of SETUP_FIRMWARE and SETUP_FPGA."); + } + } + + //Updating firmware + if (setupFirmware) + { + UpdateProgress("Updating Firmware", "Connecting to firmware device..."); + LogManager.Log(""); + LogManager.Log("-------------------------------------------------------------------------"); + LogManager.Log("Updating Firmware..."); + + UpdateProgress("Updating Firmware", "Loading firmware package..."); + var tfpPath = Path.Combine(_newPackageTempFolder, "firmware_package.tfp"); + var stream = new FileStream(tfpPath, FileMode.Open); + + if (!_machineProvider.Machine.IsDemo) + { + if (setupFPGA) + { + op.FirmwareUpgradeMode = FirmwareUpgradeModes.DFU | FirmwareUpgradeModes.TFP_PACKAGE; + } + else + { + op.FirmwareUpgradeMode = FirmwareUpgradeModes.DFU; + } + } + else + { + op.FirmwareUpgradeMode = FirmwareUpgradeModes.TFP_PACKAGE; + } + + var handler = await op.UpgradeFirmware(stream); + handler.Failed += (_, ex) => + { + stream.Dispose(); + OnFailed(ex, result, null, performDatabaseRollback, dbBackupFile, backupsFolder, tempDbName, localDataSource, _newPackageTempFolder); + }; + handler.Completed += (_, __) => + { + UpdateProgress("Updating Firmware", "Firmware update completed successfully."); + stream.Dispose(); + OnCompleted(new MachineUpdateResult() + { + UpdatePackagePath = _newPackageTempFolder, + RequiresBinariesUpdate = replaceBinaries, + }, result, null, tempDbName, backupsFolder, localDataSource); + }; + handler.Canceled += (_, __) => + { + stream.Dispose(); + OnFailed(new Exception("The operation has been canceled."), result, null, performDatabaseRollback, dbBackupFile, backupsFolder, tempDbName, localDataSource, _newPackageTempFolder); + }; + handler.Progress += (_, e) => + { + UpdateProgress("Updating Firmware", e.Message, false, e.Current, e.Total); + }; + } + else + { + OnCompleted(new MachineUpdateResult() + { + UpdatePackagePath = _newPackageTempFolder, + RequiresBinariesUpdate = replaceBinaries, + }, result, null, tempDbName, backupsFolder, localDataSource); + } + } + catch (Exception ex) + { + OnFailed(ex, result, null, performDatabaseRollback, dbBackupFile, backupsFolder, tempDbName, localDataSource, _newPackageTempFolder); + } + + return await result.Task; } /// @@ -907,25 +1251,23 @@ namespace Tango.PPC.Common.MachineUpdate /// /// The file path. /// - public Task GetUpdatePackageFileInfo(string filePath) + public Task GetUpdatePackageFileInfo(string filePath) { - return Task.Factory.StartNew(() => + return Task.Factory.StartNew(() => { - UpdatePackageFile file = new UpdatePackageFile(); - var tempFolder = TemporaryManager.CreateFolder(); - using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(filePath)) { - var appEntry = zip.Entries.SingleOrDefault(x => x.FileName == "Tango.PPC.UI.exe"); - appEntry.Extract(tempFolder); - } + var appEntry = zip.Entries.SingleOrDefault(x => x.FileName == "version.json"); + var reader = appEntry.OpenReader(); - FileVersionInfo info = FileVersionInfo.GetVersionInfo(Path.Combine(tempFolder, "Tango.PPC.UI.exe")); - file.Version = Version.Parse(info.ProductVersion); - - tempFolder.Delete(); + using (StreamReader stReader = new StreamReader(reader)) + { + String json = stReader.ReadToEnd(); + reader.Dispose(); - return file; + return PublishInfo.FromJson(json); + } + } }); } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateResult.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateResult.cs index 17ae394ee..85dd5b7d2 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateResult.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateResult.cs @@ -12,5 +12,18 @@ namespace Tango.PPC.Common.MachineUpdate /// Gets or sets the temporary update package path from which to get the last downloaded software version. /// public String UpdatePackagePath { get; set; } + + /// + /// Gets or sets a value indicating whether the application should replace it's binaries. + /// + public bool RequiresBinariesUpdate { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public MachineUpdateResult() + { + RequiresBinariesUpdate = true; + } } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/UpdatePackageFile.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/UpdatePackageFile.cs deleted file mode 100644 index df496c3be..000000000 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/UpdatePackageFile.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Tango.PPC.Common.MachineUpdate -{ - public class UpdatePackageFile - { - public Version Version { get; set; } - } -} diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Publish/PublishInfo.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Publish/PublishInfo.cs index 77717254e..df5690a05 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Publish/PublishInfo.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Publish/PublishInfo.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.PMR.FirmwareUpgrade; +using Tango.Web; namespace Tango.PPC.Common.Publish { @@ -13,6 +14,9 @@ namespace Tango.PPC.Common.Publish public String ApplicationVersion { get; set; } public VersionPackageDescriptor Firmware { get; set; } public String Comments { get; set; } + public bool IsMachineTupPackage { get; set; } + public String MachineSerialNumber { get; set; } + public DeploymentSlot MachineDeploymentSlot { get; set; } public PublishInfo() { @@ -24,7 +28,7 @@ namespace Tango.PPC.Common.Publish return JsonConvert.SerializeObject(this); } - public PublishInfo FromJson(String json) + public static PublishInfo FromJson(String json) { return JsonConvert.DeserializeObject(json); } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj b/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj index e3a23903e..d38b9c8e9 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Tango.PPC.Common.csproj @@ -194,7 +194,6 @@ - diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Dialogs/UpdateFromFileView.xaml b/Software/Visual_Studio/PPC/Tango.PPC.UI/Dialogs/UpdateFromFileView.xaml index 231f5dabb..a175b655e 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Dialogs/UpdateFromFileView.xaml +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Dialogs/UpdateFromFileView.xaml @@ -6,16 +6,16 @@ xmlns:local="clr-namespace:Tango.PPC.UI.Dialogs" xmlns:touch="clr-namespace:Tango.Touch.Controls;assembly=Tango.Touch" mc:Ignorable="d" - Background="{StaticResource TangoPrimaryBackgroundBrush}" d:DesignHeight="555" d:DesignWidth="560" Width="550" Height="450" d:DataContext="{d:DesignInstance Type=local:UpdateFromFileViewVM, IsDesignTimeCreatable=False}"> + Background="{StaticResource TangoPrimaryBackgroundBrush}" d:DesignHeight="555" d:DesignWidth="560" Width="570" Height="700" d:DataContext="{d:DesignInstance Type=local:UpdateFromFileViewVM, IsDesignTimeCreatable=False}"> - - CANCEL - UPDATE - + + CANCEL + UPDATE + - UPDATE PACKAGE + Tango Update Package The selected file contains a software update package. Press 'UPDATE' to start updating your system. diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs index 0371e94da..c0654f643 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs @@ -10,6 +10,7 @@ using Tango.Core.Helpers; using Tango.Explorer; using Tango.PPC.Common; using Tango.PPC.Common.MachineUpdate; +using Tango.PPC.Common.Publish; using Tango.PPC.Common.Web; using Tango.PPC.UI.Dialogs; using Tango.PPC.UI.Notifications.NotificationItems; @@ -209,7 +210,7 @@ namespace Tango.PPC.UI.ViewModels try { - _update_result = await MachineUpdateManager.Update(MachineProvider.Machine.SerialNumber, _checkUpdateResponse.SetupFirmware, _checkUpdateResponse.SetupFPGA); + _update_result = await MachineUpdateManager.Update(_checkUpdateResponse.SetupFirmware, _checkUpdateResponse.SetupFPGA); LogManager.Log("Machine update completed."); await NavigateTo(MachineUpdateView.UpdateCompletedView); } @@ -248,15 +249,15 @@ namespace Tango.PPC.UI.ViewModels { LogManager.Log("Completing machine update..."); - if (!IsDbUpdate) + if (IsDbUpdate || !_update_result.RequiresBinariesUpdate) { - String updater_exe = Path.Combine(_update_result.UpdatePackagePath, "Tango.PPC.Updater.exe"); - ApplicationManager.UpdateApplication(updater_exe, PathHelper.GetStartupPath()); + LogManager.Log("Restarting Application..."); + ApplicationManager.Restart(); } else { - LogManager.Log("Restarting Application..."); - ApplicationManager.Restart(); + String updater_exe = Path.Combine(_update_result.UpdatePackagePath, "Tango.PPC.Updater.exe"); + ApplicationManager.UpdateApplication(updater_exe, PathHelper.GetStartupPath()); } } @@ -375,7 +376,7 @@ namespace Tango.PPC.UI.ViewModels private async void HandleSoftwareUpdatePackageLoaded(ExplorerFileItem fileItem) { - UpdatePackageFile packageFile = null; + PublishInfo packageFile = null; try { @@ -383,38 +384,33 @@ namespace Tango.PPC.UI.ViewModels } catch (Exception ex) { - LogManager.Log(ex, $"Error loading update package file from {fileItem.Path}."); + LogManager.Log(ex, $"Error loading publish info from {fileItem.Path}."); await NotificationProvider.ShowError("An error occurred while trying to load the selected software update package. Please make sure the package is valid."); return; } - if (ApplicationManager.Version <= packageFile.Version) - { - await NotificationProvider.ShowError($"The selected update package (v{packageFile.Version.ToString()}) contains an older software version."); - return; - } - UpdateFromFileViewVM vm = new UpdateFromFileViewVM(); - vm.Version = packageFile.Version.ToString(); + vm.Version = packageFile.ApplicationVersion; await NotificationProvider.ShowDialog(vm); if (vm.DialogResult) { await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); - await NavigateTo(MachineUpdateView.UpdateFromPackageView); + await NavigateTo(MachineUpdateView.UpdateProgressView); LogManager.Log("Starting machine update from package..."); try { - _update_result = await MachineUpdateManager.UpdateFromTUP(fileItem.Path); + _update_result = await MachineUpdateManager.UpdateFromTUP(fileItem.Path, MachineProvider.Machine.SetupFirmware, MachineProvider.Machine.SetupFpga); LogManager.Log("Machine update from package completed."); await NavigateTo(MachineUpdateView.UpdateCompletedView); } catch (Exception ex) { LogManager.Log(ex, "Machine update from package failed."); + FailedError = ex.FlattenMessage(); await NavigateTo(MachineUpdateView.UpdateFailedFromPackageView); } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/MachineUpdateView.xaml b/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/MachineUpdateView.xaml index fba8a599d..beb09be0d 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/MachineUpdateView.xaml +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Views/MachineUpdateView.xaml @@ -194,8 +194,9 @@ CLOSE - - An error occurred while trying to update the machine. + + Update Failed + diff --git a/Software/Visual_Studio/Tango.Core/DB/DbManager.cs b/Software/Visual_Studio/Tango.Core/DB/DbManager.cs index 1d415fdb1..8601d67a0 100644 --- a/Software/Visual_Studio/Tango.Core/DB/DbManager.cs +++ b/Software/Visual_Studio/Tango.Core/DB/DbManager.cs @@ -65,9 +65,15 @@ namespace Tango.Core.DB #region Public Methods - public void Create(String name) + public void Create(String name, String filePath = null) { String command = String.Format("CREATE DATABASE {0}", name); + + if (filePath != null) + { + command = $"CREATE DATABASE {name} ON (name='{name}', filename='{filePath}')"; + } + SqlCommand cmd = new SqlCommand(command, _connection); cmd.ExecuteNonQuery(); } @@ -160,6 +166,13 @@ namespace Tango.Core.DB SetOnline(name); } + public void RestoreAsNew(String name, String file, String dbFolder) + { + String command = $"RESTORE DATABASE {name} FROM DISK='{file}' WITH MOVE '{name}' TO '{Path.Combine(dbFolder, name)}.mdf', MOVE '{name}_log' TO '{Path.Combine(dbFolder, name)}.ldf'"; + SqlCommand cmd = new SqlCommand(command, _connection); + cmd.ExecuteNonQuery(); + } + public void ClearDb() { if (!_connection.ConnectionString.ToLower().Contains("initial catalog")) @@ -265,6 +278,24 @@ EXEC sp_executesql @statement return cred; } + public String GetValue(String query, String columnName) + { + string sql = query; + var cm = new SqlCommand(sql, _connection); + var dr = cm.ExecuteReader(); + if (dr.Read()) + { + var value = dr[columnName]; + + if (value != null) + { + return value.ToString(); + } + } + + return null; + } + #endregion #region IDisposable diff --git a/Software/Visual_Studio/Tango.PMR/FirmwareUpgrade/VersionFileDescriptor.cs b/Software/Visual_Studio/Tango.PMR/FirmwareUpgrade/VersionFileDescriptor.cs index 98a6c2efc..96b0a8525 100644 --- a/Software/Visual_Studio/Tango.PMR/FirmwareUpgrade/VersionFileDescriptor.cs +++ b/Software/Visual_Studio/Tango.PMR/FirmwareUpgrade/VersionFileDescriptor.cs @@ -23,16 +23,15 @@ namespace Tango.PMR.FirmwareUpgrade { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChtWZXJzaW9uRmlsZURlc2NyaXB0b3IucHJvdG8SGVRhbmdvLlBNUi5GaXJt", - "d2FyZVVwZ3JhZGUaHFZlcnNpb25GaWxlRGVzdGluYXRpb24ucHJvdG8ilAEK", + "d2FyZVVwZ3JhZGUaHFZlcnNpb25GaWxlRGVzdGluYXRpb24ucHJvdG8iggEK", "FVZlcnNpb25GaWxlRGVzY3JpcHRvchIQCghGaWxlTmFtZRgBIAEoCRIPCgdW", "ZXJzaW9uGAIgASgJEkYKC0Rlc3RpbmF0aW9uGAMgASgOMjEuVGFuZ28uUE1S", - "LkZpcm13YXJlVXBncmFkZS5WZXJzaW9uRmlsZURlc3RpbmF0aW9uEhAKCENo", - "ZWNrU3VtGAQgASgMQiUKI2NvbS50d2luZS50YW5nby5wbXIuZmlybXdhcmV1", - "cGdyYWRlYgZwcm90bzM=")); + "LkZpcm13YXJlVXBncmFkZS5WZXJzaW9uRmlsZURlc3RpbmF0aW9uQiUKI2Nv", + "bS50d2luZS50YW5nby5wbXIuZmlybXdhcmV1cGdyYWRlYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Tango.PMR.FirmwareUpgrade.VersionFileDestinationReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { - new pbr::GeneratedClrTypeInfo(typeof(global::Tango.PMR.FirmwareUpgrade.VersionFileDescriptor), global::Tango.PMR.FirmwareUpgrade.VersionFileDescriptor.Parser, new[]{ "FileName", "Version", "Destination", "CheckSum" }, null, null, null) + new pbr::GeneratedClrTypeInfo(typeof(global::Tango.PMR.FirmwareUpgrade.VersionFileDescriptor), global::Tango.PMR.FirmwareUpgrade.VersionFileDescriptor.Parser, new[]{ "FileName", "Version", "Destination" }, null, null, null) })); } #endregion @@ -66,7 +65,6 @@ namespace Tango.PMR.FirmwareUpgrade { fileName_ = other.fileName_; version_ = other.version_; destination_ = other.destination_; - checkSum_ = other.checkSum_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] @@ -107,17 +105,6 @@ namespace Tango.PMR.FirmwareUpgrade { } } - /// Field number for the "CheckSum" field. - public const int CheckSumFieldNumber = 4; - private pb::ByteString checkSum_ = pb::ByteString.Empty; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public pb::ByteString CheckSum { - get { return checkSum_; } - set { - checkSum_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); - } - } - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as VersionFileDescriptor); @@ -134,7 +121,6 @@ namespace Tango.PMR.FirmwareUpgrade { if (FileName != other.FileName) return false; if (Version != other.Version) return false; if (Destination != other.Destination) return false; - if (CheckSum != other.CheckSum) return false; return true; } @@ -144,7 +130,6 @@ namespace Tango.PMR.FirmwareUpgrade { if (FileName.Length != 0) hash ^= FileName.GetHashCode(); if (Version.Length != 0) hash ^= Version.GetHashCode(); if (Destination != 0) hash ^= Destination.GetHashCode(); - if (CheckSum.Length != 0) hash ^= CheckSum.GetHashCode(); return hash; } @@ -167,10 +152,6 @@ namespace Tango.PMR.FirmwareUpgrade { output.WriteRawTag(24); output.WriteEnum((int) Destination); } - if (CheckSum.Length != 0) { - output.WriteRawTag(34); - output.WriteBytes(CheckSum); - } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] @@ -185,9 +166,6 @@ namespace Tango.PMR.FirmwareUpgrade { if (Destination != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Destination); } - if (CheckSum.Length != 0) { - size += 1 + pb::CodedOutputStream.ComputeBytesSize(CheckSum); - } return size; } @@ -205,9 +183,6 @@ namespace Tango.PMR.FirmwareUpgrade { if (other.Destination != 0) { Destination = other.Destination; } - if (other.CheckSum.Length != 0) { - CheckSum = other.CheckSum; - } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] @@ -230,10 +205,6 @@ namespace Tango.PMR.FirmwareUpgrade { destination_ = (global::Tango.PMR.FirmwareUpgrade.VersionFileDestination) input.ReadEnum(); break; } - case 34: { - CheckSum = input.ReadBytes(); - break; - } } } } diff --git a/Software/Visual_Studio/Tango.SQLExaminer/ExaminerSequenceConfigurationRunner.cs b/Software/Visual_Studio/Tango.SQLExaminer/ExaminerSequenceConfigurationRunner.cs index de146ead3..b9ee0cf7a 100644 --- a/Software/Visual_Studio/Tango.SQLExaminer/ExaminerSequenceConfigurationRunner.cs +++ b/Software/Visual_Studio/Tango.SQLExaminer/ExaminerSequenceConfigurationRunner.cs @@ -24,6 +24,15 @@ namespace Tango.SQLExaminer public ExaminerSequenceConfiguration Configuration { get; private set; } + public ExaminerSequenceConfigurationRunner(ExaminerSequenceConfiguration sequenceConfiguration, String scriptsFolder, Core.DataSource source, Core.DataSource target, String machineSerialNumber) + { + ScriptsFolder = scriptsFolder; + Source = source; + Target = target; + MachineSerialNumber = machineSerialNumber; + Configuration = sequenceConfiguration; + } + public ExaminerSequenceConfigurationRunner(String sequenceFile, String scriptsFolder, Core.DataSource source, Core.DataSource target, String machineSerialNumber) { SequenceFile = sequenceFile; diff --git a/Software/Visual_Studio/Tango.SQLExaminer/ExtensionMethods.cs b/Software/Visual_Studio/Tango.SQLExaminer/ExtensionMethods.cs new file mode 100644 index 000000000..09a830ab3 --- /dev/null +++ b/Software/Visual_Studio/Tango.SQLExaminer/ExtensionMethods.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.SQLExaminer; + +public static class ExtensionMethods +{ + public static String GetFilePath(this ExaminerConfigurationType type) + { + return Path.Combine(Helper.SQL_EXAMINER_CONFIG_FOLDER, type.ToString() + ".xml"); + } + + public static String GetFileName(this ExaminerConfigurationType type) + { + return type.ToString() + ".xml"; + } +} + diff --git a/Software/Visual_Studio/Tango.SQLExaminer/Helper.cs b/Software/Visual_Studio/Tango.SQLExaminer/Helper.cs index 5eb09b98c..3b4e238a7 100644 --- a/Software/Visual_Studio/Tango.SQLExaminer/Helper.cs +++ b/Software/Visual_Studio/Tango.SQLExaminer/Helper.cs @@ -8,7 +8,7 @@ using Tango.Core.Helpers; namespace Tango.SQLExaminer { - internal static class Helper + public static class Helper { public static String SQL_EXAMINER_FOLDER = Path.Combine(AssemblyHelper.GetCurrentAssemblyFolder(), "SQLExaminer"); public static String SQL_EXAMINER_CONFIG_FOLDER = Path.Combine(SQL_EXAMINER_FOLDER, "Configurations"); diff --git a/Software/Visual_Studio/Tango.SQLExaminer/Tango.SQLExaminer.csproj b/Software/Visual_Studio/Tango.SQLExaminer/Tango.SQLExaminer.csproj index b71a30dc0..17dcb1b22 100644 --- a/Software/Visual_Studio/Tango.SQLExaminer/Tango.SQLExaminer.csproj +++ b/Software/Visual_Studio/Tango.SQLExaminer/Tango.SQLExaminer.csproj @@ -69,6 +69,7 @@ + diff --git a/Software/Visual_Studio/Tango.UnitTesting/SQLExaminer/SQLExaminer_TST.cs b/Software/Visual_Studio/Tango.UnitTesting/SQLExaminer/SQLExaminer_TST.cs index 9b0385c23..e3e49ac5e 100644 --- a/Software/Visual_Studio/Tango.UnitTesting/SQLExaminer/SQLExaminer_TST.cs +++ b/Software/Visual_Studio/Tango.UnitTesting/SQLExaminer/SQLExaminer_TST.cs @@ -391,5 +391,76 @@ namespace Tango.UnitTesting.SQLExaminer //Should have no differences! Assert.IsFalse(data_report.HasDifferences); } + + [TestMethod] + public void Perform_Machine_Update_From_Backup() + { + String tempDbName = "Tango_TUP"; + + var source_db = GetSource("Tango"); + var target_db = GetSource(tempDbName); + + DbManager dbManager = DbManager.FromDataSource(source_db); + + //Create the backup for the tup file. + dbManager.Create(tempDbName); + + var configuration = GetFullConfiguration(); + + ExaminerSequenceConfigurationRunner runner = + new ExaminerSequenceConfigurationRunner( + configuration, + Tango.SQLExaminer.Helper.SQL_EXAMINER_CONFIG_FOLDER, + source_db, + target_db, + "1111"); + + runner.Run().GetAwaiter().GetResult(); + + String backupFile = "C:\\DB_Backups\\Tango_TEMP.bak"; + + dbManager.Backup(tempDbName, backupFile); + dbManager.SetOffline(tempDbName); + dbManager.SetOnline(tempDbName); + dbManager.Delete(tempDbName); + + //Now restore as different name + dbManager.RestoreAsNew(tempDbName, backupFile, "C:\\DB_Backups"); + } + + private ExaminerSequenceConfiguration GetFullConfiguration() + { + ExaminerSequenceConfiguration configuration = new ExaminerSequenceConfiguration(); + + configuration.Items.Add(new ExaminerSequenceItem() + { + Type = ExaminerSequenceItemType.Schema, + Direction = ExaminerSequenceItemDirection.SourceToTarget, + FileName = ExaminerConfigurationType.Schema.GetFileName(), + Index = 0, + Name = "Updating Schema", + }); + + configuration.Items.Add(new ExaminerSequenceItem() + { + Type = ExaminerSequenceItemType.Data, + Direction = ExaminerSequenceItemDirection.SourceToTarget, + FileName = ExaminerConfigurationType.OverrideData.GetFileName(), + Index = 1, + Name = "Updating Collections", + }); + + configuration.Items.Add(new ExaminerSequenceItem() + { + Type = ExaminerSequenceItemType.Data, + Direction = ExaminerSequenceItemDirection.SourceToTarget, + FileName = ExaminerConfigurationType.ProvisionMachine.GetFileName(), + Index = 2, + Name = "Configuring Machine", + RequiresSerialNumber = true, + }); + + return configuration; + } } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs index 2eeaa6e0e..378fc3eea 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs @@ -23,6 +23,10 @@ using Tango.Web.ActiveDirectory; using Tango.MachineService.Filters; using Tango.MachineService.Security; using Tango.Web.SQLServer; +using Tango.Core; +using Tango.Web.SMO; +using Tango.Core.DB; +using System.Threading.Tasks; namespace Tango.MachineService.Controllers { @@ -425,6 +429,67 @@ namespace Tango.MachineService.Controllers }; } + [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 } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs index 2dee09e69..0d9a2993b 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs @@ -32,7 +32,7 @@ namespace Tango.MachineService.Controllers private static List _pendingUploads; private static List _pendingUpdates; private ActiveDirectoryManager _ad_manager; - private const int SQL_TEMP_CREDENTIALS_EXP_MINUTS = 20; + public const int SQL_TEMP_CREDENTIALS_EXP_MINUTS = 20; public class TokenObject { -- cgit v1.3.1 From 51151796efb23162ca0b3d6701d90dfb6d3baeb9 Mon Sep 17 00:00:00 2001 From: Roy Ben Shabat Date: Sat, 14 Dec 2019 22:33:55 +0200 Subject: Enabled transparent color for catalogs. Added machine last update check for quick db check PPC = >Service. Implemented AutoUpdateCheck vai PPC settings. Dropped use of AutoUpdateCheck from DB. Added skipping over TFP firmware upgrade upload if no other files other than mcu were found. Added more logs to firmware upgrade. --- Software/DB/PPC/Tango.mdf | Bin 75497472 -> 75497472 bytes Software/DB/PPC/Tango_log.ldf | Bin 53673984 -> 53673984 bytes .../Views/MachineSettingsView.xaml | 4 +- .../Tango.PPC.Jobs/ViewModels/JobsViewVM.cs | 5 ++ .../PPC/Modules/Tango.PPC.Jobs/Views/JobView.xaml | 3 +- .../ViewModels/MainViewVM.cs | 10 ++++ .../Tango.PPC.MachineSettings/Views/MainView.xaml | 14 +++++ .../MachineUpdate/IMachineUpdateManager.cs | 2 +- .../MachineUpdate/MachineUpdateManager.cs | 19 ++++--- .../PPC/Tango.PPC.Common/PPCSettings.cs | 6 +++ .../Tango.PPC.Common/Web/CheckForUpdateRequest.cs | 1 + .../Printing/DefaultPrintingManager.cs | 2 +- .../Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs | 2 +- .../Tango.Integration/Operation/MachineOperator.cs | 60 +++++++++++++++++++-- .../Controllers/PPCController.cs | 7 ++- 15 files changed, 116 insertions(+), 19 deletions(-) (limited to 'Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs') diff --git a/Software/DB/PPC/Tango.mdf b/Software/DB/PPC/Tango.mdf index a204a2664..a4ca7dd67 100644 Binary files a/Software/DB/PPC/Tango.mdf and b/Software/DB/PPC/Tango.mdf differ diff --git a/Software/DB/PPC/Tango_log.ldf b/Software/DB/PPC/Tango_log.ldf index 38b8da37b..13145f312 100644 Binary files a/Software/DB/PPC/Tango_log.ldf and b/Software/DB/PPC/Tango_log.ldf differ diff --git a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineSettingsView.xaml b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineSettingsView.xaml index 0a0c1ecef..4631ac068 100644 --- a/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineSettingsView.xaml +++ b/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/Views/MachineSettingsView.xaml @@ -62,8 +62,8 @@ Auto Login - Auto Check For Updates - + Setup Activation diff --git a/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/ViewModels/JobsViewVM.cs b/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/ViewModels/JobsViewVM.cs index 798b333e7..785472d0d 100644 --- a/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/ViewModels/JobsViewVM.cs +++ b/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/ViewModels/JobsViewVM.cs @@ -414,6 +414,11 @@ namespace Tango.PPC.Jobs.ViewModels Settings.SupportedColorSpaces.Count > 0 ? Settings.SupportedColorSpaces : Enum.GetValues(typeof(ColorSpaces)).Cast().Where(x => x.IsUserSpace() || (ApplicationManager.IsInTechnicianMode && x == ColorSpaces.Volume)).ToList() ); + if (_catalogs.Count == 0) + { + vm.SupportedColorSpaces.Remove(ColorSpaces.Catalog); + } + CatalogSelectionViewVM catalogVM = new CatalogSelectionViewVM(_catalogs.ToList(), _catalogs.ToList().SingleOrDefault(x => x.Guid == settings.LastSelectedCatalogGuid)); if (settings.LastJobType != null) diff --git a/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/Views/JobView.xaml b/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/Views/JobView.xaml index 9b28d7709..97756ffd5 100644 --- a/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/Views/JobView.xaml +++ b/Software/Visual_Studio/PPC/Modules/Tango.PPC.Jobs/Views/JobView.xaml @@ -412,7 +412,6 @@ - @@ -422,7 +421,7 @@ - + diff --git a/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/ViewModels/MainViewVM.cs b/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/ViewModels/MainViewVM.cs index d12617264..5077fd884 100644 --- a/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/ViewModels/MainViewVM.cs +++ b/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/ViewModels/MainViewVM.cs @@ -144,6 +144,13 @@ namespace Tango.PPC.MachineSettings.ViewModels set { _synchronizeDiagnostics = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); } } + private bool _autoCheckForUpdates; + public bool AutoCheckForUpdates + { + get { return _autoCheckForUpdates; } + set { _autoCheckForUpdates = value; RaisePropertyChangedAuto(); } + } + #endregion #region Commands @@ -196,6 +203,7 @@ namespace Tango.PPC.MachineSettings.ViewModels Settings.DefaultSpoolTypeGuid = DefaultSpoolType?.Guid; Settings.SynchronizeJobs = SynchronizeJobs; Settings.SynchronizeDiagnostics = SynchronizeDiagnostics; + Settings.AutoCheckForUpdates = AutoCheckForUpdates; MachineDataSynchronizer.IsEnabled = SynchronizeJobs || SynchronizeDiagnostics; @@ -264,6 +272,8 @@ namespace Tango.PPC.MachineSettings.ViewModels SynchronizeJobs = Settings.SynchronizeJobs; SynchronizeDiagnostics = Settings.SynchronizeDiagnostics; + + AutoCheckForUpdates = Settings.AutoCheckForUpdates; } private async void OnEnableRemoteAssistanceChanged() diff --git a/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/Views/MainView.xaml b/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/Views/MainView.xaml index 017649f8e..4a2f1e253 100644 --- a/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/Views/MainView.xaml +++ b/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/Views/MainView.xaml @@ -199,7 +199,21 @@ + + + Auto Update Check + + + + Automatically check for software and database updates. + + + + + + + Synchronize Jobs diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs index e11eab3a5..421b4ee54 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/IMachineUpdateManager.cs @@ -20,7 +20,7 @@ namespace Tango.PPC.Common.MachineUpdate /// /// Gets or sets a value indicating whether to automatically check for new application updates. /// - bool AutoCheckForUpdates { get; set; } + bool EnableAutoCheckForUpdates { get; set; } /// /// Gets the current machine update progress status. diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs index 4c71c2a1a..088e80f61 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/MachineUpdate/MachineUpdateManager.cs @@ -41,6 +41,7 @@ namespace Tango.PPC.Common.MachineUpdate private List _logs; private System.Timers.Timer _checkForUpdateTimer; private bool _isUpdating; + private PPCSettings _settings; #region Events @@ -77,7 +78,7 @@ namespace Tango.PPC.Common.MachineUpdate /// /// Gets or sets a value indicating whether to automatically check for new application updates. /// - public bool AutoCheckForUpdates + public bool EnableAutoCheckForUpdates { get { return _autoCheckForUpdates; } set { _autoCheckForUpdates = value; RaisePropertyChangedAuto(); } @@ -105,6 +106,8 @@ namespace Tango.PPC.Common.MachineUpdate _checkForUpdateTimer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds); _checkForUpdateTimer.Elapsed += _checkForUpdateTimer_Elapsed; _checkForUpdateTimer.Start(); + + _settings = SettingsManager.Default.GetOrCreate(); } #endregion @@ -421,7 +424,7 @@ namespace Tango.PPC.Common.MachineUpdate { _isUpdating = true; - var machineServiceAddress = SettingsManager.Default.GetOrCreate().GetMachineServiceAddress(); + var machineServiceAddress = _settings.GetMachineServiceAddress(); LogManager.Log($"Starting machine update for serial number {serialNumber}..."); @@ -688,7 +691,7 @@ namespace Tango.PPC.Common.MachineUpdate { _isUpdating = true; - var machineServiceAddress = SettingsManager.Default.GetOrCreate().GetMachineServiceAddress(); + var machineServiceAddress = _settings.GetMachineServiceAddress(); LogManager.Log($"Connecting to machine service on {machineServiceAddress}..."); @@ -702,6 +705,8 @@ namespace Tango.PPC.Common.MachineUpdate try { + request.MachineLastUpdated = _machineProvider.Machine.LastUpdated; + using (ObservablesContext db = ObservablesContext.CreateDefault()) { request.Rmls = db.Rmls.ToList().Select(x => new UpdatedEntity(x)).ToList(); @@ -861,7 +866,7 @@ namespace Tango.PPC.Common.MachineUpdate { return Task.Factory.StartNew(() => { - var machineServiceAddress = SettingsManager.Default.GetOrCreate().GetMachineServiceAddress(); + var machineServiceAddress = _settings.GetMachineServiceAddress(); LogManager.Log($"Checking if database update is required for serial number {serialNumber}..."); @@ -1042,7 +1047,7 @@ namespace Tango.PPC.Common.MachineUpdate throw new InvalidOperationException("The specified tup file is invalid. The package was generated for a different machine."); } - if (publishInfo.MachineDeploymentSlot != SettingsManager.Default.GetOrCreate().DeploymentSlot) + if (publishInfo.MachineDeploymentSlot != _settings.DeploymentSlot) { throw new InvalidOperationException("The specified tup file is invalid. The package was generated on a different environment."); } @@ -1292,7 +1297,7 @@ namespace Tango.PPC.Common.MachineUpdate String packagesFolder = Path.Combine(AssemblyHelper.GetCurrentAssemblyFolder(), "packages"); Version previousVersion = null; - String str = SettingsManager.Default.GetOrCreate().PreviousApplicationVersion; + String str = _settings.PreviousApplicationVersion; if (Version.TryParse(str, out previousVersion)) { @@ -1333,7 +1338,7 @@ namespace Tango.PPC.Common.MachineUpdate private async void _checkForUpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { - if (AutoCheckForUpdates && !_isUpdating) + if (EnableAutoCheckForUpdates && _settings.AutoCheckForUpdates && !_isUpdating) { _checkForUpdateTimer.Stop(); diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/PPCSettings.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/PPCSettings.cs index acdfb6a8a..cb17f5be3 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/PPCSettings.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/PPCSettings.cs @@ -214,6 +214,11 @@ namespace Tango.PPC.Common /// public TimeSpan PowerUpScreenTimeout { get; set; } + /// + /// Gets or sets a value indicating whether to automatically check for software and database (quick) updates. + /// + public bool AutoCheckForUpdates { get; set; } + /// /// Gets the machine service address. /// @@ -255,6 +260,7 @@ namespace Tango.PPC.Common FirmwareVersion = "1.0.0.0"; DisplayPowerUpScreen = true; PowerUpScreenTimeout = TimeSpan.FromSeconds(20); + AutoCheckForUpdates = true; } } } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs index 0feb32aaf..3d606b918 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.Common/Web/CheckForUpdateRequest.cs @@ -15,6 +15,7 @@ namespace Tango.PPC.Common.Web public List Rmls { get; set; } public List HardwareVersions { get; set; } public List Catalogs { get; set; } + public DateTime MachineLastUpdated { get; set; } public CheckForUpdateRequest() { diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/Printing/DefaultPrintingManager.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/Printing/DefaultPrintingManager.cs index 56ec2fa7e..4c5a87ab4 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/Printing/DefaultPrintingManager.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/Printing/DefaultPrintingManager.cs @@ -259,7 +259,7 @@ namespace Tango.PPC.UI.Printing { throw new InvalidOperationException("Error starting job. Color is out of range."); } - if (job.Segments.SelectMany(x => x.BrushStops).Any(x => x.BrushColorSpace == ColorSpaces.Catalog && x.ColorCatalogsItem == null)) + if (job.Segments.SelectMany(x => x.BrushStops).Any(x => x.BrushColorSpace == ColorSpaces.Catalog && x.ColorCatalogsItem == null && !x.IsTransparent)) { throw new InvalidOperationException("Error starting job. Please select a catalog color."); } diff --git a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs index c0654f643..49b2aef89 100644 --- a/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs +++ b/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineUpdateViewVM.cs @@ -297,7 +297,7 @@ namespace Tango.PPC.UI.ViewModels } else { - MachineUpdateManager.AutoCheckForUpdates = MachineProvider.Machine.AutoCheckForUpdates; + MachineUpdateManager.EnableAutoCheckForUpdates = true; } } diff --git a/Software/Visual_Studio/Tango.Integration/Operation/MachineOperator.cs b/Software/Visual_Studio/Tango.Integration/Operation/MachineOperator.cs index a96693bdf..bae0ec55e 100644 --- a/Software/Visual_Studio/Tango.Integration/Operation/MachineOperator.cs +++ b/Software/Visual_Studio/Tango.Integration/Operation/MachineOperator.cs @@ -1753,10 +1753,14 @@ namespace Tango.Integration.Operation liquidVolume.Volume = stop.ColorCatalogsItem.Black; } } - else + else if (!stop.IsTransparent) { throw new InvalidOperationException($"No catalog item specified for segment color."); } + else + { + stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters); + } } else if (stop.BrushColorSpace == ColorSpaces.Volume) { @@ -2911,33 +2915,46 @@ namespace Tango.Integration.Operation try { + LogManager.Log("Starting firmware upgrade..."); + LogManager.Log($"Firmware upgrade flags: {String.Join(", ", FirmwareUpgradeMode.GetFlags().Select(x => x.ToString()))}"); + if (Status != MachineStatuses.ReadyToDye) { throw LogManager.Log(new InvalidOperationException($"Could not perform firmware upgrade while operator status is '{Status}'.")); } + LogManager.Log("Extracting tfp package..."); var package_info = await GetFirmwarePackageInfo(tfpStream); tfpStream.Position = 0; + LogManager.Log("Reading zip stream..."); zip = ZipFile.Read(tfpStream); + LogManager.Log("Creating storage manager..."); var storage = CreateStorageManager(); + LogManager.Log("Getting storage drive information..."); var drive = await storage.GetStorageDrive(); + LogManager.Log($"Storage drive info:\n{drive.ToJsonString()}"); + LogManager.Log("Getting root folder..."); var root = await storage.GetRootFolder(); + LogManager.Log($"Root folder: '{root.Path}'"); var existing_folder = root.Items.SingleOrDefault(x => x.Name == FIRMWARE_UPGRADE_FOLDER_NAME); if (existing_folder != null) { + LogManager.Log("Root folder exists. Deleting..."); await storage.DeleteItem(existing_folder); } String package_folder = Path.Combine(drive.Root, FIRMWARE_UPGRADE_FOLDER_NAME); + LogManager.Log($"Creating new folder: '{package_folder}'."); await storage.CreateFolder(package_folder); List handlers = new List(); List entries = zip.Entries.ToList(); List streams = new List(); + LogManager.Log("Disabling keep alive..."); var keepAlive = UseKeepAlive; UseKeepAlive = false; @@ -2960,7 +2977,19 @@ namespace Tango.Integration.Operation { if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.DFU)) { - var mcuEntry = zip.Entries.Single(x => x.FileName == package_info.FileDescriptors.Single(y => y.Destination == VersionFileDestination.Mcu).FileName); + LogManager.Log("DFU enabled. Starting upgrade via DFU..."); + LogManager.Log("Extracting MCU file..."); + ZipEntry mcuEntry = null; + try + { + mcuEntry = zip.Entries.Single(x => x.FileName == package_info.FileDescriptors.Single(y => y.Destination == VersionFileDestination.Mcu).FileName); + } + catch (Exception ex) + { + upgradeHandler.RaiseFailed(new IOException("Firmware upgrade via DFU is enabled but no MCU file was found in the package.", ex)); + return; + } + MemoryStream ms = new MemoryStream(); mcuEntry.Extract(ms); ms.Position = 0; @@ -2974,35 +3003,52 @@ namespace Tango.Integration.Operation upgradeHandler.RaiseProgress((long)e.Progress, FirmwareUpgradeStatus.Upgrading, e.State.ToDescription()); }; + LogManager.Log("Disconnecting adapter..."); Adapter.Disconnect().Wait(); if (MachineEventsStateProvider != null) { + LogManager.Log("Resetting active events..."); MachineEventsStateProvider.Reset(); } + LogManager.Log("Upgrading..."); upgradeManager.PerformUpgrade(data).Wait(); + LogManager.Log("Waiting for the device..."); upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Waiting for the device..."); Thread.Sleep(5000); + LogManager.Log("Reconnecting adapter..."); upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Connecting..."); Adapter.Connect().Wait(); Connect().Wait(); + LogManager.Log("Connected..."); upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Connected."); Thread.Sleep(2000); + LogManager.Log("Waiting..."); upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Waiting..."); Thread.Sleep(2000); Status = MachineStatuses.Upgrading; } + //Upload tfp package only if specified in flag && package info contains more files other than the mcu bin file. if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.TFP_PACKAGE)) { - upgradeHandler.Total = zip.Entries.Sum(x => x.UncompressedSize); - uploadNext(); + if (package_info.FileDescriptors.Where(x => x.Destination != VersionFileDestination.Mcu).Count() > 0) + { + LogManager.Log("TFP package is enabled. Starting upload..."); + upgradeHandler.Total = zip.Entries.Sum(x => x.UncompressedSize); + uploadNext(); + } + else + { + LogManager.Log("TFP package is enabled but no other files other than the MCU file were found on the package. Skipping..."); + postActivation(); + } } else { @@ -3026,6 +3072,8 @@ namespace Tango.Integration.Operation var entry = entries.First(); entries.Remove(entry); + LogManager.Log($"Uploading file '{entry.FileName}'..."); + var reader = entry.OpenReader(); streams.Add(reader); @@ -3061,6 +3109,7 @@ namespace Tango.Integration.Operation { try { + LogManager.Log("Validating version..."); streams.ForEach(x => x.Dispose()); upgradeHandler.RaiseProgress(upgradeHandler.Total, FirmwareUpgradeStatus.Validating, "Validating version..."); var validateRequest = new ValidateVersionRequest(); @@ -3078,6 +3127,7 @@ namespace Tango.Integration.Operation { try { + LogManager.Log("Activating version..."); upgradeHandler.RaiseProgress(upgradeHandler.Total, FirmwareUpgradeStatus.Activating, "Activating version..."); var activateRequest = new ActivateVersionRequest(); activateRequest.Path = package_folder; @@ -3092,8 +3142,10 @@ namespace Tango.Integration.Operation postActivation = new Action(() => { + LogManager.Log("Firmware upgrade completed."); upgradeHandler.RaiseCompleted(); Status = MachineStatuses.ReadyToDye; + LogManager.Log("Enabling keep alive..."); UseKeepAlive = keepAlive; }); diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs index b2a1da980..77b3a180f 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs @@ -322,7 +322,12 @@ namespace Tango.MachineService.Controllers bool hasDatabaseUpdates = false; - hasDatabaseUpdates = rmls.Exists(x => request.Rmls.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Rmls.Exists(y => x.Guid == y.Guid)); + hasDatabaseUpdates = machine.LastUpdated > request.MachineLastUpdated; + + if (!hasDatabaseUpdates) + { + hasDatabaseUpdates = rmls.Exists(x => request.Rmls.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Rmls.Exists(y => x.Guid == y.Guid)); + } if (!hasDatabaseUpdates) { -- cgit v1.3.1