Prechádzať zdrojové kódy

Some improvements to program startup

Kenric Nugteren 1 rok pred
rodič
commit
dc0abdf645
1 zmenil súbory, kde vykonal 127 pridanie a 59 odobranie
  1. 127 59
      prs.desktop/MainWindow.xaml.cs

+ 127 - 59
prs.desktop/MainWindow.xaml.cs

@@ -159,6 +159,7 @@ public partial class MainWindow : IPanelHostControl
         HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
         HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
 
+        Logger.Send(LogType.Information, "", "Connecting to server");
         var settings = App.DatabaseSettings;
         bool dbConnected;
         DatabaseType = settings.DatabaseType;
@@ -250,6 +251,8 @@ public partial class MainWindow : IPanelHostControl
         ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
         SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
         Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
+        
+        Logger.Send(LogType.Information, "", "Checking for updates");
         CheckForUpdates();
 
         Exception? startupException = null;
@@ -284,13 +287,16 @@ public partial class MainWindow : IPanelHostControl
 
             var tasks = new List<Task>
             {
-                Task.Run(() => CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly)),
-                Task.Run(() => CoreUtils.RegisterClasses()),
-                Task.Run(() => ComalUtils.RegisterClasses()),
-                Task.Run(() => PRSSharedUtils.RegisterClasses()),
-                Task.Run(() => ReportUtils.RegisterClasses()),
-                Task.Run(() => ConfigurationUtils.RegisterClasses()),
-                Task.Run(() => DynamicGridUtils.RegisterClasses()),
+                Task.Run(() =>
+                {
+                    CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly);
+                    CoreUtils.RegisterClasses();
+                    ComalUtils.RegisterClasses();
+                    PRSSharedUtils.RegisterClasses();
+                    ReportUtils.RegisterClasses();
+                    ConfigurationUtils.RegisterClasses();
+                    DynamicGridUtils.RegisterClasses();
+                }),
                 Task.Run(() =>
                 {
                     ScriptDocument.DefaultAssemblies.AddRange(
@@ -306,6 +312,8 @@ public partial class MainWindow : IPanelHostControl
             };
             Task.WaitAll(tasks.ToArray());
 
+            Logger.Send(LogType.Information, "", "Configuring Application");
+
             progress.Report("Configuring Application");
             RegisterModules(progress);
 
@@ -328,28 +336,45 @@ public partial class MainWindow : IPanelHostControl
                     );
                 }
             }
+
+            if (startupException is null && App.DatabaseSettings.Autologin)
+            {
+                Logger.Send(LogType.Information, "", "Logging in");
+                progress.Report("Logging in");
+                loginStatus = TryAutoLogin();
+                if(loginStatus == ValidationStatus.VALID)
+                {
+                    // Do the AfterLogin() here so that we aren't opening and closing progress windows again and again.
+                    AfterLogin(progress);
+                }
+            }
         });
 
         if (startupException != null)
-            MessageBox.Show(startupException.Message);
-
-        if (DoLogin(App.DatabaseSettings.Autologin) == ValidationStatus.VALID)
         {
-            AfterLogin();
+            MessageWindow.ShowError("Error during startup.", startupException);
+        }
+        
+        // If the login status is valid, then we've already loaded everything, so we don't here.
+        if(loginStatus != ValidationStatus.VALID)
+        {
+            Logger.Send(LogType.Information, "", "Logging in");
+            if (DoLogin() == ValidationStatus.VALID)
+            {
+                AfterLogin(null);
+            }
         }
 
         ProfileName.Content = App.Profile;
         URL.Content = GetDatabaseConnectionDescription();
 
-
-        Progress.ShowModal("Starting Up", progress =>
+        if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
         {
-            if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
+            Progress.ShowModal("Starting Scheduler", progress =>
             {
-                progress.Report("Starting Scheduler");
                 scheduler.Start();
-            }
-        });
+            });
+        }
     }
 
     #region Connection Management
@@ -622,16 +647,15 @@ public partial class MainWindow : IPanelHostControl
     }*/
 
 
-    private void ConfigureMainScreen()
+    private void ConfigureMainScreen(IProgress<string>? progress)
     {
-        SetupScreen();
-
         var bMaps = Security.CanView<Equipment>()
                     || Security.CanView<Job>()
                     || Security.CanView<TimeSheet>()
                     || Security.CanView<GPSTracker>();
 
-        Progress.ShowModal(
+        var sections = new[]
+        {
             new ProgressSection("Configuring Main Screen", SetupMainScreen),
             new ProgressSection("Configuring Quotes Screen", () => SetupQuotesTab(bMaps)),
             new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
@@ -644,7 +668,22 @@ public partial class MainWindow : IPanelHostControl
             new ProgressSection("Configuring DigitalForms", () => SetupDigitalFormsTab(bMaps)),
             new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
             new ProgressSection("Configuring System Modules", SetupSystemModules)
-        );
+        };
+
+        if(progress is not null)
+        {
+            Dispatcher.Invoke(SetupScreen);
+            foreach(var section in sections)
+            {
+                progress.Report(section.Message);
+                Dispatcher.Invoke(section.Action);
+            }
+        }
+        else
+        {
+            SetupScreen();
+            Progress.ShowModal(sections);
+        }
     }
 
     private void SetupScreen()
@@ -1196,10 +1235,9 @@ public partial class MainWindow : IPanelHostControl
 
             if (OutstandingDailyReports(false))
             {
-                MessageBox.Show("There are outstanding Daily Reports that must be filled out before continuing!" +
-                                "\n\nAccess to PRS is restricted until this is corrected.",
-                    "Outstanding Reports"
-                );
+                MessageWindow.ShowMessage("There are outstanding Daily Reports that must be filled out before continuing!"
+                    + "\n\nAccess to PRS is restricted until this is corrected.",
+                    "Outstanding Reports");
 
                 var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
                 if(dailyReportPanel is not null)
@@ -1208,7 +1246,7 @@ public partial class MainWindow : IPanelHostControl
                     {
                         if (!OutstandingDailyReports(true))
                         {
-                            ConfigureMainScreen();
+                            ConfigureMainScreen(null);
                             LoadApplicationState();
                         }
                     };
@@ -1264,8 +1302,7 @@ public partial class MainWindow : IPanelHostControl
             }
             catch (Exception e)
             {
-                CoreUtils.LogException(ClientFactory.UserID, e);
-                MessageBox.Show(string.Format("Unable to Load {0}!\n\n{1}\n{2}", app.Settings["CurrentPanel"], e.Message, e.StackTrace));
+                MessageWindow.ShowError($"Unable to load {app.Settings["CurrentPanel"]}", e);
             }
         }
     }
@@ -1478,29 +1515,31 @@ public partial class MainWindow : IPanelHostControl
 
     #region Login Management
 
-    private ValidationStatus? DoLogin(bool autoLogin)
+    private ValidationStatus? TryAutoLogin()
     {
         ValidationStatus? result = null;
-        if (autoLogin)
+        if (App.DatabaseSettings.LoginType == LoginType.UserID)
         {
-            if (App.DatabaseSettings.LoginType == LoginType.UserID)
+            try
             {
-                try
-                {
-                    result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
-                }
-                catch (Exception e)
-                {
-                    Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
-                    MessageBox.Show("Error connecting to server.\nPlease check the server URL and port number.");
-                    result = null;
-                }
-                if (result == ValidationStatus.INVALID)
-                {
-                    MessageBox.Show("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
-                }
+                result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
+            }
+            catch (Exception e)
+            {
+                MessageWindow.ShowError("Error connecting to server.\nPlease check the server URL and port number.", e);
+                result = null;
+            }
+            if (result == ValidationStatus.INVALID)
+            {
+                MessageWindow.ShowMessage("Unable to Login with User ID: " + App.DatabaseSettings.UserID, "Login failed");
             }
         }
+        return result;
+    }
+
+    private ValidationStatus? DoLogin()
+    {
+        ValidationStatus? result = null;
         if (result != ValidationStatus.VALID)
         {
             var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
@@ -1516,8 +1555,10 @@ public partial class MainWindow : IPanelHostControl
     /// <summary>
     /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
     /// </summary>
-    private void AfterLogin()
+    /// <param name="progress">If not <see langword="null"/>, then rather than opening a new progress window, just uses that.</param>
+    private void AfterLogin(IProgress<string>? progress)
     {
+        Logger.Send(LogType.Information, "", "Loading employee");
         LoadCurrentEmployee();
         if (CheckTimesheetBypass(true))
         {
@@ -1525,7 +1566,7 @@ public partial class MainWindow : IPanelHostControl
         }
         else
         {
-            MessageBox.Show("You must clock on before logging in to PRS!");
+            MessageWindow.ShowMessage("You must clock on before logging in to PRS!", "Not clocked in.");
             ClientFactory.InvalidateUser();
             App.EmployeeID = Guid.Empty;
             App.EmployeeName = "";
@@ -1533,10 +1574,38 @@ public partial class MainWindow : IPanelHostControl
             App.EmployeeEmail = "";
         }
 
-        ApplyColorScheme();
-        ConfigureMainScreen();
-        LoadApplicationState();
-        LoadSecondaryWindows();
+        Logger.Send(LogType.Information, "", "Setting colours");
+        if(progress is null)
+        {
+            ApplyColorScheme();
+        }
+        else
+        {
+            Dispatcher.Invoke(ApplyColorScheme);
+        }
+
+        Logger.Send(LogType.Information, "", "Configuring main window");
+        ConfigureMainScreen(progress);
+
+        Logger.Send(LogType.Information, "", "Loading current window");
+        if(progress is null)
+        {
+            LoadApplicationState();
+        }
+        else
+        {
+            Dispatcher.Invoke(LoadApplicationState);
+        }
+
+        Logger.Send(LogType.Information, "", "Loading secondary window");
+        if(progress is null)
+        {
+            LoadSecondaryWindows();
+        }
+        else
+        {
+            Dispatcher.Invoke(LoadSecondaryWindows);
+        }
 
         //if (_ribbon.Menu.IsVisible)
         //{
@@ -1578,7 +1647,6 @@ public partial class MainWindow : IPanelHostControl
 
     private void LoadCurrentEmployee()
     {
-
         var me = new Client<Employee>().Query(
             new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
             Columns.None<Employee>().Add(x => x.ID).Add(x => x.Email).Add(x => x.Name)
@@ -1643,17 +1711,17 @@ public partial class MainWindow : IPanelHostControl
         }
 
         ClientFactory.InvalidateUser();
-        ConfigureMainScreen();
+        ConfigureMainScreen(null);
         LoadSecondaryWindows();
 
         if (message != null)
         {
-            MessageBox.Show(message);
+            MessageWindow.ShowMessage(message, "Logged out");
         }
 
-        if (DoLogin(false) == ValidationStatus.VALID)
+        if (DoLogin() == ValidationStatus.VALID)
         {
-            AfterLogin();
+            AfterLogin(null);
         }
 
         return true;
@@ -3461,8 +3529,8 @@ public partial class MainWindow : IPanelHostControl
 
     private void LoginButton_OnClick(object sender, RoutedEventArgs e)
     {
-        if (DoLogin(false) == ValidationStatus.VALID)
-            AfterLogin();
+        if (DoLogin() == ValidationStatus.VALID)
+            AfterLogin(null);
     }
 
     private void ExitButton_OnClick(object sender, RoutedEventArgs e)