Exemplo n.º 1
0
        protected override void InitializeShell(Window shell)
        {
            Tracer.Info($"### STARTING {ProductInformation.ApplicationName}, version {ProcessExecutable.AssemblyVersion()}, IsPortable = {SettingsClient.BaseGet<bool>("Configuration", "IsPortable")}, Windows version = {EnvironmentUtils.GetFriendlyWindowsVersion()} ({EnvironmentUtils.GetInternalWindowsVersion()}), IsWindows10 = {Core.Base.Constants.IsWindows10} ###");

            // Handler for unhandled AppDomain exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            this.InitializeWcfServices();

            Current.MainWindow = shell;

            bool showOobe = SettingsClient.Get <bool>("General", "ShowOobe");

            if (showOobe)
            {
                var oobeWin = Container.Resolve <Oobe>();

                // These 2 lines are required to set the RegionManager of the child window.
                // If we don't do this, regions on child windows are never known by the Shell
                // RegionManager and navigation doesn't work
                RegionManager.SetRegionManager(oobeWin, Container.Resolve <IRegionManager>());
                RegionManager.UpdateRegions();

                // Show the OOBE window. Don't tell the Indexer to start.
                // It will get a signal to start when the OOBE window closes.
                Tracer.Info("Showing Oobe screen");

                // Disable shutdown when the dialogs close
                Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

                // Show as a dialog. This prevents further code execution until the dialog is closed.
                oobeWin.ShowDialog();
                oobeWin.ForceActivate();
            }

            // Re-enable normal shutdown mode
            Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            // Show the main window
            Tracer.Info("Showing Main screen");
            shell.Show();

            // We're not showing the OOBE screen, tell the IndexingService to start.
            if (!showOobe)
            {
                Container.Resolve <IIndexingService>().RefreshCollectionAsync();
            }
        }
Exemplo n.º 2
0
        private async Task PerformClosingTasksAsync()
        {
            LogClient.Info("Performing closing tasks");
            this.ShowClosingAnimation();

            // Write the settings
            // ------------------
            LogClient.Info("Writing settings");
            SettingsClient.Write();

            // Save queued tracks
            // ------------------
            LogClient.Info("Saving queued tracks");
            if (this.playbackService.IsSavingQueuedTracks)
            {
                while (this.playbackService.IsSavingQueuedTracks)
                {
                    await Task.Delay(50);
                }
            }
            else
            {
                await this.playbackService.SaveQueuedTracksAsync();
            }

            // Stop playing
            // ------------
            LogClient.Info("Stopping playback");
            this.playbackService.Stop();

            // Update file metadata
            // --------------------
            LogClient.Info("Updating file metadata");
            await this.metadataService.SafeUpdateFileMetadataAsync();

            // Save track statistics
            // ---------------------
            LogClient.Info("Saving playback counters");
            if (this.playbackService.IsSavingPlaybackCounters)
            {
                while (this.playbackService.IsSavingPlaybackCounters)
                {
                    await Task.Delay(50);
                }
            }
            else
            {
                await this.playbackService.SavePlaybackCountersAsync();
            }

            LogClient.Info("### STOPPING {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion().ToString());

            this.mustPerformClosingTasks = false;
            this.Close();
        }
Exemplo n.º 3
0
        protected override void OnStartup(StartupEventArgs e)
        {
            // Create a jump-list and assign it to the current application
            JumpList.SetJumpList(Current, new JumpList());

            // Check that there is only one instance of the application running
            this.instanceMutex = new Mutex(true, $"{ProductInformation.ApplicationGuid}-{ProcessExecutable.AssemblyVersion()}", out bool isNewInstance);

            // Process the command-line arguments
            this.ProcessCommandLineArguments(isNewInstance);

            if (isNewInstance)
            {
                this.instanceMutex.ReleaseMutex();
                this.LaunchInitializer();
                base.OnStartup(e);
            }
            else
            {
                // HACK: because shutdown is too fast, some logging might be missing in the log file.
                LogClient.Warning("{0} is already running. Shutting down.", ProductInformation.ApplicationName);
                this.Shutdown();
            }
        }
Exemplo n.º 4
0
        private void ExecuteEmergencyStop(Exception ex)
        {
            LogClient.Error("Unhandled Exception. {0}", LogClient.GetAllExceptions(ex));

            // Close the application to prevent further problems
            LogClient.Info("### FORCED STOP of {0}, version {1} ###", ProcessExecutable.Name(), ProcessExecutable.AssemblyVersion().ToString());

            // Emergency save of the settings
            SettingsClient.Write();

            Application.Current.Shutdown();
        }
Exemplo n.º 5
0
        private void ExecuteStartup()
        {
            LogClient.Info("### STARTING {0}, version {1}, IsPortable = {2}, Windows version = {3} ({4}) ###", ProcessExecutable.Name(), ProcessExecutable.AssemblyVersion().ToString(), SettingsClient.BaseGet <bool>("Configuration", "IsPortable").ToString(), EnvironmentUtils.GetFriendlyWindowsVersion(), EnvironmentUtils.GetInternalWindowsVersion());

            // Handler for unhandled AppDomain exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


            // Create a jumplist and assign it to the current application
            JumpList jl = new JumpList();

            JumpList.SetJumpList(Application.Current, jl);

            // Show the Splash Window
            Window splashWin = new Splash();

            splashWin.Show();
        }
Exemplo n.º 6
0
        private void ExecuteEmergencyStop(Exception ex)
        {
            // This is a workaround for a bug in the .Net framework, which randomly causes a System.ArgumentNullException when
            // scrolling through a Virtualizing StackPanel. Scroll to playing song sometimes triggers this bug. We catch the
            // Exception here, and do nothing with it. The application can just proceed. This prevents a complete crash.
            // This might be fixed in .Net 4.5.2. See here: https://connect.microsoft.com/VisualStudio/feedback/details/789438/scrolling-in-virtualized-wpf-treeview-is-very-unstable
            if (ex.GetType().ToString().Equals("System.ArgumentNullException") & ex.Source.ToString().Equals("PresentationCore"))
            {
                LogClient.Warning("Avoided Unhandled Exception: {0}", ex.Message);
                return;
            }

            LogClient.Error("Unhandled Exception. {0}", LogClient.GetAllExceptions(ex));

            // Close the application to prevent further problems
            LogClient.Info("### FORCED STOP of {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion());

            // Stop playing (This avoids remaining processes in Task Manager)
            var playbackService = ServiceLocator.Current.GetInstance <IPlaybackService>();

            playbackService.Stop();

            // Emergency save of the settings
            SettingsClient.Write();

            Application.Current.Shutdown();
        }
Exemplo n.º 7
0
        private void ExecuteStartup()
        {
            LogClient.Info($"### STARTING {ProductInformation.ApplicationName}, version {ProcessExecutable.AssemblyVersion()}, IsPortable = {SettingsClient.BaseGet<bool>("Configuration", "IsPortable")}, Windows version = {EnvironmentUtils.GetFriendlyWindowsVersion()} ({EnvironmentUtils.GetInternalWindowsVersion()}), IsWindows10 = {Constants.IsWindows10} ###");

            // Handler for unhandled AppDomain exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            if (this.IsUpdateNeeded())
            {
                // Show the Update Window
                BorderlessWindows10Window initWin = new Initialize();
                initWin.Show();
                initWin.ForceActivate();
            }
            else
            {
                // Start the bootstrapper
                Bootstrapper bootstrapper = new Bootstrapper();
                bootstrapper.Run();
            }
        }
Exemplo n.º 8
0
        private void Shell_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            LogClient.Info("### STOPPING {0}, version {1} ###", ProductInformation.ApplicationDisplayName, ProcessExecutable.AssemblyVersion().ToString());

            // Prevent saving the size when the window is minimized.
            // When minimized, the actual size is not detected correctly,
            // which causes a too small size to be saved.

            if (!(this.WindowState == WindowState.Minimized))
            {
                if (this.WindowState == WindowState.Maximized)
                {
                    SettingsClient.Set <bool>("General", "IsMaximized", true);
                }
                else
                {
                    SettingsClient.Set <bool>("General", "IsMaximized", false);

                    // TODO: make tis better. Workaround for bug "MainWindow opens with size 0 px"
                    if (this.ActualWidth > 50 & this.ActualHeight > 50)
                    {
                        SettingsClient.Set <int>("General", "Width", (int)this.ActualWidth);
                        SettingsClient.Set <int>("General", "Height", (int)this.ActualHeight);
                    }
                    else
                    {
                        SettingsClient.Set <int>("General", "Width", Defaults.DefaultMainWindowWidth);
                        SettingsClient.Set <int>("General", "Height", Defaults.DefaultMainWindowHeight);
                    }

                    SettingsClient.Set <int>("General", "Top", (int)this.Top);
                    SettingsClient.Set <int>("General", "Left", (int)this.Left);
                }

                // Save the settings immediately
                SettingsClient.Write();
            }

            this.noteService.CloseAllNoteWindows();
        }
Exemplo n.º 9
0
        private void ShowErrorDetails()
        {
            DateTime currentTime       = DateTime.Now;
            string   currentTimeString = currentTime.Year.ToString() + currentTime.Month.ToString() + currentTime.Day.ToString() + currentTime.Hour.ToString() + currentTime.Minute.ToString() + currentTime.Second.ToString() + currentTime.Millisecond.ToString();

            string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ProcessExecutable.Name() + "_" + currentTimeString + ".txt");

            System.IO.File.WriteAllText(path, this.errorMessage);
            System.Diagnostics.Process.Start(path);
        }
Exemplo n.º 10
0
        private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SettingsClient.Get <bool>("Behaviour", "ShowTrayIcon") &
                SettingsClient.Get <bool>("Behaviour", "CloseToTray") &
                !this.isShuttingDown)
            {
                e.Cancel = true;

                // Minimize first, then hide from Taskbar. Otherwise a small window
                // remains visible in the lower left corner of the screen.
                this.WindowState = WindowState.Minimized;

                // When closing to tray, hide this window from Taskbar and ALT-TAB menu.
                this.ShowInTaskbar = false;

                try
                {
                    WindowUtils.HideWindowFromAltTab(this);
                }
                catch (Exception ex)
                {
                    LogClient.Error("Could not hide main window from ALT-TAB menu. Exception: {0}", ex.Message);
                }
            }
            else
            {
                LogClient.Info("### STOPPING {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion().ToString());

                if (this.lifetimeService.MustPerformClosingTasks)
                {
                    e.Cancel = true;
                    await this.lifetimeService.PerformClosingTasksAsync();

                    this.Close();
                }
            }
        }
Exemplo n.º 11
0
        private void Window_Closed(object sender, System.EventArgs e)
        {
            // Stop monitoring tablet mode
            this.windowsIntegrationService.StopMonitoringTabletMode();

            // Make sure the Tray icon is removed from the tray
            this.trayIcon.Visible = false;

            // Stop listening to keyboard outside the application
            this.win32InputService.UnhookKeyboard();

            // This makes sure the application doesn't keep running when the main window is closed.
            // Extra windows created by the main window can keep a WPF application running even when
            // the main window is closed, because the default ShutDownMode of a WPF application is
            // OnLastWindowClose. This was happening here because of the Mini Player Playlist.
            Application.Current.Shutdown();

            LogClient.Info("### STOPPED {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion().ToString());
        }
Exemplo n.º 12
0
        private void ExecuteStartup()
        {
            LogClient.Info("### STARTING {0}, version {1}, IsPortable = {2}, Windows version = {3} ({4}) ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion(), SettingsClient.BaseGet <bool>("Configuration", "IsPortable"), EnvironmentUtils.GetFriendlyWindowsVersion(), EnvironmentUtils.GetInternalWindowsVersion());

            // Handler for unhandled AppDomain exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Show the Splash Window
            Window splashWin = new Splash();

            splashWin.Show();
        }
Exemplo n.º 13
0
        protected override void InitializeShell(Window shell)
        {
            LogClient.Info($"### STARTING {ProductInformation.ApplicationName}, version {ProcessExecutable.AssemblyVersion()}, IsPortable = {SettingsClient.BaseGet<bool>("Configuration", "IsPortable")}, Windows version = {EnvironmentUtils.GetFriendlyWindowsVersion()} ({EnvironmentUtils.GetInternalWindowsVersion()}), IsWindows10 = {Core.Base.Constants.IsWindows10} ###");

            // Handler for unhandled AppDomain exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var initializer = new Initializer();

            if (initializer.IsMigrationNeeded())
            {
                // Show the Update Window
                var initWin = new Initialize();
                initWin.ShowDialog();
                initWin.ForceActivate();
            }

            this.InitializeWcfServices();

            Application.Current.MainWindow = shell;

            if (SettingsClient.Get <bool>("General", "ShowOobe"))
            {
                var oobeWin = Container.Resolve <Oobe>();

                // These 2 lines are required to set the RegionManager of the child window.
                // If we don't do this, regions on child windows are never known by the Shell
                // RegionManager and navigation doesn't work
                RegionManager.SetRegionManager(oobeWin, Container.Resolve <IRegionManager>());
                RegionManager.UpdateRegions();

                // Show the OOBE window. Don't tell the Indexer to start.
                // It will get a signal to start when the OOBE window closes.
                LogClient.Info("Showing Oobe screen");
                oobeWin.ShowDialog();
                oobeWin.ForceActivate();
            }

            LogClient.Info("Showing Main screen");
            Application.Current.MainWindow.Show();

            // We're not showing the OOBE screen, tell the IndexingService to start.
            Container.Resolve <IIndexingService>().RefreshCollectionAsync();
        }
Exemplo n.º 14
0
 private void TrayIconContextMenuExit_Click(object sender, RoutedEventArgs e)
 {
     LogClient.Info("### STOPPING {0}, version {1} ###", ProductInformation.ApplicationDisplayName, ProcessExecutable.AssemblyVersion().ToString());
     this.isShuttingDown = true;
     this.Close();
 }
Exemplo n.º 15
0
        private void ExecuteEmergencyStop(Exception ex)
        {
            // This is a workaround for a bug in the .Net framework, which randomly causes a System.ArgumentNullException when
            // scrolling through a Virtualizing StackPanel. Scroll to playing song sometimes triggers this bug. We catch the
            // Exception here, and do nothing with it. The application can just proceed. This prevents a complete crash.
            // This might be fixed in .Net 4.5.2. See here: https://connect.microsoft.com/VisualStudio/feedback/details/789438/scrolling-in-virtualized-wpf-treeview-is-very-unstable
            if (ex.GetType().ToString().Equals("System.ArgumentNullException") & ex.Source.ToString().Equals("PresentationCore"))
            {
                if (this.CanLogUnhandledException())
                {
                    Tracer.Warn($"Ignored Unhandled Exception: {ex.Message}");
                }

                return;
            }

            // This is a workaround for an inexplicable issue which occurs on 1 user's computer (as far as I know).
            // Exception "System.ComponentModel.Win32Exception (0x80004005): Access is denied" is thrown when performing
            // function "MS.Win32.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)"
            if (ex.GetType().ToString().Equals("System.ComponentModel.Win32Exception") & ex.Source.ToString().Equals("WindowsBase"))
            {
                if (this.CanLogUnhandledException())
                {
                    Tracer.Warn($"Ignored Unhandled Exception: {ex.Message}");
                }

                return;
            }

            // This is a workaround for an exception which occurs when using Dopamine together with WinDock (https://www.ivanyu.ca/windock)
            // Unhandled Exception. Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
            // at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest(WM uMsg, IntPtr wParam, IntPtr lParam, Boolean & handled)
            // at System.Windows.Shell.WindowChromeWorker._WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean & handled)
            if (ex.GetType().ToString().Equals("System.OverflowException") & ex.Source.ToString().Equals("PresentationFramework"))
            {
                if (this.CanLogUnhandledException())
                {
                    Tracer.Warn($"Ignored Unhandled Exception: {ex.Message}");
                }

                return;
            }

            // Tracer.Warn($"Ignored Unhandled Exception: Message=<<<<{ex.Message}>>>>");
            // Tracer.Warn($"Ignored Unhandled Exception: Type=<<<<{ex.GetType().ToString()}>>>>");
            // Tracer.Warn($"Ignored Unhandled Exception: Source=<<<<{ex.Source.ToString()}>>>>");
            // return;

//L            Tracer.Error("Unhandled Exception. {0}", LogClient.GetAllExceptions(ex));

            // Close the application to prevent further problems
            Tracer.Info("### FORCED STOP of {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion());

            // Stop playing (This avoids remaining processes in Task Manager)
            var playbackService = ServiceLocator.Current.GetInstance <IPlaybackService>();

            playbackService.Stop();

            // Emergency save of the settings
            SettingsClient.Write();

            Current.Shutdown();
        }
Exemplo n.º 16
0
        private async Task CheckForUpdatesAsync()
        {
            // Indicate for the rest of the class that we are checking for updates
            // -------------------------------------------------------------------
            this.checkingForUpdates = true;

            // We start checking for updates: stop the timer
            // ---------------------------------------------
            this.checkNewVersionTimer.Stop();

            // Get the current version
            // -----------------------
            var currentVersion = this.CreateDummyPackage(ProcessExecutable.AssemblyVersion());

            LogClient.Info("Update check: current version = {0}", currentVersion.Version.ToString());

            // Get the latest version online
            // -----------------------------
            if (!this.canCheckForUpdates)
            {
                return;                           // Stop here if the update check was disabled while we were running
            }
            Package latestOnlineVersion = await this.GetLatestOnlineVersionAsync();

            LogClient.Info("Update check: latest online version = {0}.{1}.{2}.{3}", latestOnlineVersion.Version.Major.ToString(), latestOnlineVersion.Version.Minor.ToString(), latestOnlineVersion.Version.Build.ToString(), latestOnlineVersion.Version.Revision.ToString());

            // Compare the versions
            // --------------------
            if (currentVersion.IsOlder(latestOnlineVersion))
            {
                if (this.automaticDownload)
                {
                    // Automatic download is enabled
                    // -----------------------------

                    // Define the name of the file to which we will download the update
                    string updatePackageExtractedDirectoryFullPath = Path.Combine(this.updatesSubDirectory, latestOnlineVersion.Filename);
                    string updatePackageDownloadedFileFullPath     = Path.Combine(this.updatesSubDirectory, latestOnlineVersion.Filename + latestOnlineVersion.UpdateFileExtension);

                    // Check if there is a directory with the name of the update package:
                    // that means the file was already downloaded and extracted.
                    if (Directory.Exists(updatePackageExtractedDirectoryFullPath))
                    {
                        // The folder exists, that means that the new version was already extracted previously.
                        // Raise an event that a new version is available for installation.
                        if (this.canCheckForUpdates)
                        {
                            this.NewDownloadedVersionAvailable(latestOnlineVersion, updatePackageExtractedDirectoryFullPath);
                        }
                    }
                    else
                    {
                        // Check if there is a package with the name of the update package: that would mean the update was already downloaded.
                        if (!this.IsDownloadedPackageAvailable(updatePackageDownloadedFileFullPath))
                        {
                            // No package available yet: download it.
                            OperationResult downloadResult = await this.DownloadAsync(latestOnlineVersion, updatePackageDownloadedFileFullPath);

                            if (downloadResult.Result)
                            {
                                OperationResult processResult = await this.ProcessDownloadedPackageAsync();

                                if (processResult.Result)
                                {
                                    // Processing the downloaded file was successful. Raise an event that a new version is available for installation.
                                    if (this.canCheckForUpdates)
                                    {
                                        this.NewDownloadedVersionAvailable(latestOnlineVersion, updatePackageExtractedDirectoryFullPath);
                                    }
                                }
                                else
                                {
                                    // Processing the downloaded file failed. Log the failure reason.
                                    LogClient.Error("Update check: could not process downloaded files. User is notified that there is a new version online. Exception: {0}", processResult.GetFirstMessage());

                                    // Raise an event that there is a new version available online.
                                    if (this.canCheckForUpdates)
                                    {
                                        this.NewOnlineVersionAvailable(latestOnlineVersion);
                                    }
                                }
                            }
                            else
                            {
                                // Downloading failed: log the failure reason.
                                LogClient.Error("Update check: could not download the file. Exception: {0}", downloadResult.GetFirstMessage());
                            }
                        }
                        else
                        {
                            OperationResult extractResult = this.ExtractDownloadedPackage(updatePackageDownloadedFileFullPath);

                            if (extractResult.Result)
                            {
                                // Extracting was successful. Raise an event that a new version is available for installation.
                                if (this.canCheckForUpdates)
                                {
                                    this.NewDownloadedVersionAvailable(latestOnlineVersion, updatePackageExtractedDirectoryFullPath);
                                }
                            }
                            else
                            {
                                // Extracting failed: log the failure reason.
                                LogClient.Error("Update check: could not extract the package. Exception: {0}", extractResult.GetFirstMessage());
                            }
                        }
                    }
                }
                else
                {
                    // Automatic download is not enabled
                    // ---------------------------------

                    // Raise an event that a New version Is available for download
                    if (this.canCheckForUpdates)
                    {
                        this.NewOnlineVersionAvailable(latestOnlineVersion);
                    }
                }
            }
            else
            {
                this.NoNewVersionAvailable(latestOnlineVersion);
                LogClient.Info("Update check: no newer version was found.");
            }

            // Indicate for the rest of the class that we have finished checking for updates
            // -----------------------------------------------------------------------------
            this.checkingForUpdates = false;

            // We're finished checking for updates: start the timer
            // ----------------------------------------------------
            this.checkNewVersionTimer.Start();
        }
Exemplo n.º 17
0
        protected override void OnStartup(StartupEventArgs e)
        {
            Tracer.Info2(InfraColor.White, InfraColor.DarkBlue, "**** Starting App ******");

            // Create a jump-list and assign it to the current application
            JumpList.SetJumpList(Current, new JumpList());

            // Check that there is only one instance of the application running
            this.instanceMutex = new Mutex(true, $"{ProductInformation.ApplicationGuid}-{ProcessExecutable.AssemblyVersion()}", out bool isNewInstance);

            // Process the command-line arguments
            this.ProcessCommandLineArguments(isNewInstance);

            if (isNewInstance)
            {
                this.instanceMutex.ReleaseMutex();
                this.LaunchInitializer();
                base.OnStartup(e);

                TheProgram.Program.SetPlaybackService(Container.Resolve <IPlaybackService>());
            }
            else
            {
                // HACK: because shutdown is too fast, some logging might be missing in the log file.
                Tracer.Warn("{0} is already running. Shutting down.", ProductInformation.ApplicationName);
                this.Shutdown();
            }
        }
Exemplo n.º 18
0
        private async void CheckNow()
        {
            if (this.isDismissed)
            {
                return;
            }

            LogClient.Info("Checking for updates");
            this.canCheck = true;

            // Get the current version
            var currentVersion = this.CreateDummyPackage(ProcessExecutable.AssemblyVersion());

            LogClient.Info("Update check: current version = {0}", currentVersion.Version);

            // Get a new version online
            if (!this.canCheck)
            {
                return; // Stop here if the update check was disabled
            }

            Package newOnlineVersion = await this.GetNewVersionAsync(currentVersion);

            LogClient.Info("Update check: new online version = {0}.{1}.{2}.{3}", newOnlineVersion.UnformattedVersion);

            // Check if the online version is valid
            if (this.IsValidVersion(newOnlineVersion.Version))
            {
                bool automaticDownload = SettingsClient.Get <bool>("Updates", "AutomaticDownload") & !SettingsClient.Get <bool>("Configuration", "IsPortable");

                if (automaticDownload) // Automatic download is enabled
                {
                    // Define the name of the file to which we will download the update
                    string updatePackageExtractedDirectoryFullPath = Path.Combine(this.updatesSubDirectory, newOnlineVersion.Filename);
                    string updatePackageDownloadedFileFullPath     = Path.Combine(this.updatesSubDirectory, newOnlineVersion.Filename + newOnlineVersion.UpdateFileExtension);

                    // Check if there is a directory with the name of the update package:
                    // that means the file was already downloaded and extracted.
                    if (Directory.Exists(updatePackageExtractedDirectoryFullPath))
                    {
                        // The folder exists, that means that the new version was already extracted previously.
                        if (this.canCheck)
                        {
                            // Raise an event that a new version is available for installation.
                            this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                            {
                                UpdatePackage         = newOnlineVersion,
                                UpdatePackageLocation = updatePackageExtractedDirectoryFullPath
                            });
                        }
                    }
                    else
                    {
                        // Check if there is a package with the name of the update package: that would mean the update was already downloaded.
                        if (!this.IsDownloadedPackageAvailable(updatePackageDownloadedFileFullPath))
                        {
                            // No package available yet: download it.
                            OperationResult downloadResult = await this.DownloadAsync(newOnlineVersion, updatePackageDownloadedFileFullPath);

                            if (downloadResult.Result)
                            {
                                OperationResult processResult = await this.ProcessDownloadedPackageAsync();

                                if (processResult.Result)
                                {
                                    // Processing the downloaded file was successful. Raise an event that a new version is available for installation.
                                    if (this.canCheck)
                                    {
                                        this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                                        {
                                            UpdatePackage         = newOnlineVersion,
                                            UpdatePackageLocation = updatePackageExtractedDirectoryFullPath
                                        });
                                    }
                                }
                                else
                                {
                                    // Processing the downloaded file failed. Log the failure reason.
                                    LogClient.Error("Update check: could not process downloaded files. User is notified that there is a new version online. Exception: {0}", processResult.GetFirstMessage());

                                    // Raise an event that there is a new version available online.
                                    if (this.canCheck)
                                    {
                                        this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                                        {
                                            UpdatePackage         = newOnlineVersion,
                                            UpdatePackageLocation = updatePackageExtractedDirectoryFullPath
                                        });
                                    }
                                }
                            }
                            else
                            {
                                // Downloading failed: log the failure reason.
                                LogClient.Error("Update check: could not download the file. Exception: {0}", downloadResult.GetFirstMessage());

                                // Downloading failed, but we want the user to know that there is a new version.
                                if (this.canCheck)
                                {
                                    this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                                    {
                                        UpdatePackage = newOnlineVersion
                                    });
                                }
                            }
                        }
                        else
                        {
                            OperationResult extractResult = this.ExtractDownloadedPackage(updatePackageDownloadedFileFullPath);

                            if (extractResult.Result)
                            {
                                // Extracting was successful. Raise an event that a new version is available for installation.
                                if (this.canCheck)
                                {
                                    this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                                    {
                                        UpdatePackage         = newOnlineVersion,
                                        UpdatePackageLocation = updatePackageExtractedDirectoryFullPath
                                    });
                                }
                            }
                            else
                            {
                                // Extracting failed: log the failure reason.
                                LogClient.Error("Update check: could not extract the package. Exception: {0}", extractResult.GetFirstMessage());
                            }
                        }
                    }
                }
                else // Automatic download is not enabled
                {
                    // Raise an event that a new version Is available for download
                    if (this.canCheck)
                    {
                        this.NewVersionAvailable(this, new UpdateAvailableEventArgs()
                        {
                            UpdatePackage = newOnlineVersion
                        });
                    }
                }
            }
            else
            {
                this.NoNewVersionAvailable(this, new EventArgs());
                LogClient.Info("No new version was found");
            }

            if (SettingsClient.Get <bool>("Updates", "CheckPeriodically"))
            {
                this.EnablePeriodicCheck();
            }
        }
Exemplo n.º 19
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Create a jump-list and assign it to the current application
            JumpList.SetJumpList(Application.Current, new JumpList());

            // Check that there is only one instance of the application running
            bool isNewInstance = false;

            instanceMutex = new Mutex(true, string.Format("{0}-{1}", ProductInformation.ApplicationGuid, ProcessExecutable.AssemblyVersion()), out isNewInstance);

            // Process the command-line arguments
            this.ProcessCommandLineArguments(isNewInstance);

            if (isNewInstance)
            {
                instanceMutex.ReleaseMutex();
                this.ExecuteStartup();
            }
            else
            {
                LogClient.Warning("{0} is already running. Shutting down.", ProductInformation.ApplicationName);
                this.Shutdown();
            }
        }
Exemplo n.º 20
0
        private void ExecuteEmergencyStop(Exception ex)
        {
            // This is a workaround for a bug in the .Net framework, which randomly causes a System.ArgumentNullException when
            // scrolling through a Virtualizing StackPanel. Scroll to playing song sometimes triggers this bug. We catch the
            // Exception here, and do nothing with it. The application can just proceed. This prevents a complete crash.
            // This might be fixed in .Net 4.5.2. See here: https://connect.microsoft.com/VisualStudio/feedback/details/789438/scrolling-in-virtualized-wpf-treeview-is-very-unstable
            if (ex.GetType().ToString().Equals("System.ArgumentNullException") & ex.Source.ToString().Equals("PresentationCore"))
            {
                LogClient.Warning($"Ignored Unhandled Exception: {ex.Message}");
                return;
            }

            // This is a workaround for an exception which is thrown on a select number of systems.
            // This is the exception: System.ComponentModel.Win32Exception (0x80004005): Access is denied
            // at MS.Win32.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)
            // The cause of the exception is unknown. Most likely this is due to an external factor.
            if (ex.GetType().ToString().Equals("System.ComponentModel.Win32Exception") & ex.Message.Contains("MS.Win32.UnsafeNativeMethods.GetWindowText"))
            {
                LogClient.Warning($"Ignored Unhandled Exception: {ex.Message}");
                return;
            }

            LogClient.Error("Unhandled Exception. {0}", LogClient.GetAllExceptions(ex));

            // Close the application to prevent further problems
            LogClient.Info("### FORCED STOP of {0}, version {1} ###", ProductInformation.ApplicationName, ProcessExecutable.AssemblyVersion());

            // Stop playing (This avoids remaining processes in Task Manager)
            var playbackService = ServiceLocator.Current.GetInstance <IPlaybackService>();

            playbackService.Stop();

            // Emergency save of the settings
            SettingsClient.Write();

            Current.Shutdown();
        }