コード例 #1
0
        private void BeginInstall()
        {
            int requiredValue = (pepperBox.Checked ? 1 : 0) + (netscapeBox.Checked ? 1 : 0) + (activeXBox.Checked ? 2 : 0);

            if (Environment.Is64BitOperatingSystem)
            {
                requiredValue *= 2;
            }

            requiredValue += UNINSTALL_TICKS;
            requiredValue += INSTALL_GENERAL_TICKS;

            progressBar.Value   = 0;
            progressBar.Maximum = requiredValue;

            new Task(new Action(() => {
                IntPtr redirection = RedirectionManager.DisableRedirection();

                try {
                    Uninstaller.Uninstall(this);
                    Installer.Install(this, pepperBox.Checked, netscapeBox.Checked, activeXBox.Checked);
                    Complete();
                } catch (Exception e) {
                    Failure(e);
                } finally {
                    RedirectionManager.EnableRedirection(redirection);
                }
            })).Start();
        }
コード例 #2
0
 /// <summary>
 /// Uninstalls the application based on the existing options
 /// </summary>
 private void Uninstall()
 {
     if (!Directory.Exists(InstallLocation))
     {
         ConsoleUtils.FormattedWrite("Install location does not exist");
     }
     else if (!SaveData)
     {
         Uninstaller.UninstallApp(Shortcuts, InstallLocation);
         ConsoleUtils.FormattedWrite("Application successfully uninstalled");
     }
     else if (Directory.Exists(SaveLocation) || (!Directory.Exists(SaveLocation) &&
                                                 YesChoices.Contains(ConsoleUtils.FancyGetAllowedInput(AllowedOptions, "Save Folder does not exist so installer will need to create one. Continue?"))))
     {
         Uninstaller.MoveApp(Shortcuts, InstallLocation, SaveLocation);
         ConsoleUtils.FormattedWrite("Application successfully uninstalled");
     }
     ConsoleUtils.FormattedWrite("Press any key to continue...", new FormattedWriteSettings()
     {
         NewLine = false
     });
     Console.CursorVisible = false;
     Console.ReadKey(true);
     Console.CursorVisible = true;
 }
コード例 #3
0
        public override IEnumerable <JunkNode> FindJunk()
        {
            var returnList = new List <JunkNode>();

            returnList.AddRange(ScanForJunk());

            returnList.AddRange(ScanFirewallRules());

            returnList.AddRange(ScanTracing());

            returnList.AddRange(ScanClsid());

            returnList.AddRange(ScanAudioPolicyConfig());

            returnList.AddRange(ScanUserAssist());

            returnList.AddRange(ScanAppCompatFlags());

            returnList.AddRange(ScanEventLogs());

            returnList.AddRange(ScanInstallerFolders());

            if (Uninstaller.RegKeyStillExists())
            {
                var regKeyNode = new RegistryKeyJunkNode(PathTools.GetDirectory(Uninstaller.RegistryPath),
                                                         Uninstaller.RegistryKeyName, Uninstaller.DisplayName);
                regKeyNode.Confidence.Add(ConfidencePart.IsUninstallerRegistryKey);
                returnList.Add(regKeyNode);
            }

            return(returnList);
        }
コード例 #4
0
ファイル: SpareForm.cs プロジェクト: midare160/SpARe
        private void RevertButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            var dialogResult = MessageBox.Show(
                "Do you really want to revert all changes?",
                "Are you sure?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);

            if (dialogResult != DialogResult.Yes)
            {
                return;
            }

            Cursor.Current = Cursors.WaitCursor;

            _hostsFileAccess.RemoveUrls();
            _spotifyUpdateDirectoryAccess.Allow();

            if (CleanupCheckBox.Checked)
            {
                var uninstaller = new Uninstaller(OutputTextBox);
                uninstaller.UninstallSpotify();
            }

            SetUiAndConfig(false);

            OutputTextBox.AppendText("\r\nAll changes successfully reverted!", Color.Green);
            OutputTextBox.AppendText(_textBoxSeparator);

            SystemSounds.Asterisk.Play();
        }
コード例 #5
0
        private void BeginInstall()
        {
            InstallFlags flags = new InstallFlags();

            flags.SetConditionally(pepperBox.Checked, InstallFlags.PEPPER);
            flags.SetConditionally(netscapeBox.Checked, InstallFlags.NETSCAPE);
            flags.SetConditionally(activeXBox.Checked, InstallFlags.ACTIVEX);
            flags.SetConditionally(playerBox.Checked, InstallFlags.PLAYER);
            flags.SetConditionally(playerDesktopBox.Checked, InstallFlags.PLAYER_DESKTOP);
            flags.SetConditionally(playerStartMenuBox.Checked, InstallFlags.PLAYER_START_MENU);

            progressBar.Value   = 0;
            progressBar.Maximum = flags.GetTicks();

            new Task(new Action(() => {
                IntPtr redirection = RedirectionManager.DisableRedirection();

                try {
                    Uninstaller.Uninstall(this);
                    Installer.Install(this, flags);
                    Complete();
                } catch (Exception e) {
                    Failure(e);
                } finally {
                    RedirectionManager.EnableRedirection(redirection);
                }
            })).Start();
        }
コード例 #6
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            string installPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\" + installedPathRegKeyName, "InstallPath", "") ?? "";

            state = InstallerState.Read(installPath);
            state.Update();
            if (e.Args.Length > 0 && e.Args[0] == "/uninstall")
            {
                if (MessageBox.Show("Are you sure you want to uninstall KinectToVR?", "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    if (Uninstaller.UninstallK2EX(installPath))
                    {
                        MessageBox.Show("Uninstalled successfully!");
                        if (Directory.Exists(installPath))
                        {
                            // https://stackoverflow.com/a/1305478/
                            ProcessStartInfo Info = new ProcessStartInfo();
                            Info.Arguments      = "/C choice /C Y /N /D Y /T 3 & rmdir /S /Q \"" + installPath + "\"";
                            Info.WindowStyle    = ProcessWindowStyle.Hidden;
                            Info.CreateNoWindow = true;
                            Info.FileName       = "cmd.exe";
                            Process.Start(Info);
                        }
                    }
                }
                Current.Shutdown(0);
            }
        }
コード例 #7
0
        internal DebugWindow(MainWindow reference, UninstallerListViewTools listview, Uninstaller uninstaller)
        {
            _reference   = reference;
            _listView    = listview;
            _uninstaller = uninstaller;

            InitializeComponent();

            _settings.Subscribe(TestHandler, x => x.FilterHideMicrosoft, this);
            _settings.BindControl(checkBox1, x => x.FilterHideMicrosoft, this);

            _settings.BindControl(checkBoxDebug, x => x.Debug, this);
            checkBoxDebug.Checked = Settings.Default.Debug;

            var messageboxes =
                typeof(MessageBoxes).GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

            foreach (var x in messageboxes)
            {
                var wr = new ComboBoxWrapper <MethodInfo>(x, y =>
                {
                    var name = y.ToString();
                    return(name.Substring(name.IndexOf(' ') + 1));
                });
                comboBoxMessages.Items.Add(wr);
            }

            checkBox2.Checked = Program.IsInstalled;
        }
コード例 #8
0
ファイル: MainClass.cs プロジェクト: WFIOST/H3VRModInstaller
        /// <summary>
        ///     Backend input
        /// </summary>
        /// <param name="inputargs">Input</param>
        ///
        public static void doCommand(string[] inputargs)
        {
            for (int repeat = 1; repeat < inputargs.Length; repeat++)
            {
                Console.WriteLine("doing {0} {1}", inputargs[0], inputargs[repeat]);
                switch (inputargs[0])
                {
                case "dl":
                    Downloader.DownloadModDirector(inputargs[repeat]);
                    break;

                //deletion
                case "rm":
                    Console.WriteLine($"Deleting {inputargs[repeat]}");
                    Uninstaller.DeleteMod(inputargs[repeat]);
                    break;

                case "disable":
                    Disabler.EnableDisableMod(inputargs[repeat]);
                    break;

                default:
                    Console.WriteLine("Invalid command!");
                    break;
                }
            }

            switch (inputargs[0])
            {
            case "wipe":
                File.Delete(Utilities.ModCache);
                Console.WriteLine("Wiped!");
                break;
            }
        }
コード例 #9
0
        private void buttonSort_Click(object sender, EventArgs e)
        {
            objectListView1.PrimarySortColumn = null;
            var results = Uninstaller.SortIntelligently(Entries, entry => entry.Entry);

            objectListView1.SetObjects(results.ToList());
        }
コード例 #10
0
        public void Can_Add_Section()
        {
            // delete it if it exists, before running installer
            Uninstaller.RemoveSection();

            Assert.Null(_sectionService.GetByAlias("workflow"));

            Assert.True(Installer.AddSection(ApplicationContext.Current));
        }
コード例 #11
0
        private void buttonAccept_Click(object sender, EventArgs e)
        {
            var filters = SelectedJunk.OfType <DriveJunkNode>().Select(x => x.FullName).ToArray();

            if (!Uninstaller.CheckForRunningProcesses(filters, false, this))
            {
                return;
            }

            if (SelectedJunk.Any(x => !(x is DriveJunkNode)))
            {
                switch (MessageBoxes.BackupRegistryQuestion(this))
                {
                case MessageBoxes.PressedButton.Yes:
                    if (backupDirDialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var dir = Path.Combine(backupDirDialog.SelectedPath, GetUniqueBackupName());
                    try
                    {
                        Directory.CreateDirectory(dir);
                    }
                    catch (Exception ex)
                    {
                        PremadeDialogs.GenericError(ex);
                        goto case MessageBoxes.PressedButton.Yes;
                    }

                    try
                    {
                        FilesystemTools.CompressDirectory(dir);
                    }
                    catch
                    {
                        // Ignore, not important
                    }

                    if (!RunBackup(dir))
                    {
                        return;
                    }

                    break;

                case MessageBoxes.PressedButton.No:
                    break;

                default:
                    return;
                }
            }

            DialogResult = DialogResult.OK;
            Close();
        }
コード例 #12
0
        public void Can_Add_Dashboards()
        {
            Uninstaller.RemoveSectionDashboard();
            Assert.True(Installer.AddSectionDashboard());
            Assert.True(Installer.AddContentSectionDashboard());

            // installing when dashboards exist will fail
            Assert.False(Installer.AddSectionDashboard());
            Assert.False(Installer.AddContentSectionDashboard());
        }
コード例 #13
0
        public WindowsOperationHandler()
        {
            // Have to make sure the Windows Update Agent is up to date.
            WUAUpdater.Run();

            session = new UpdateSession();
            windowsUninstaller = new Uninstaller();

            updateWorker.DoWork += new DoWorkEventHandler(DownloadAndInstallUpdates);
            updateWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DownloadAndInstallCompleted);
        }
コード例 #14
0
ファイル: MainClass.cs プロジェクト: WIS777/H3VRModInstaller
        /// <summary>
        ///     Backend input
        /// </summary>
        /// <param name="inputargs">Input</param>
        ///
        public static void doCommand(string[] inputargs)
        {
            switch (inputargs[0])
            {
            case "wipe":
                File.Delete(Utilities.ModCache);
                Console.WriteLine("Wiped!");
                break;

            case "check":

                var ml = JsonModList.GetModLists();

                for (var i = 0; i < ml.Length; i++)
                {
                    for (var x = 0; x < ml[i].Modlist.Length; x++)
                    {
                        if (ml[i].Modlist[x].ModId == inputargs[1])
                        {
                            var link = ml[i].Modlist[x].Website;
                            var psi  = new ProcessStartInfo
                            {
                                FileName        = link,
                                UseShellExecute = true
                            };
                            Process.Start(psi);
                        }
                    }
                }

                break;

            case "dl":
                Downloader.DownloadModDirector(inputargs[1]);
                break;

            case "toggledebugging":
                ModInstallerCommon.enableDebugging = !ModInstallerCommon.enableDebugging;
                Console.WriteLine("Debugging is now " + ModInstallerCommon.enableDebugging);
                break;

            //deletion
            case "rm":
                Console.WriteLine($"Deleting {inputargs[1]}");
                Uninstaller.DeleteMod(inputargs[1]);
                break;

            default:
                Console.WriteLine("Invalid command!");
                break;
            }
        }
コード例 #15
0
#pragma warning restore 1998

        public async Task Uninstall(IProgress <Tuple <int, string> > progress = null, bool dryRun = true)
        {
            // First, remove the desktop entry and "sqrl://" scheme handlers
            progress.Report(new Tuple <int, string>(0, $"Removing desktop entries and sqrl:// scheme handlers"));
            var desktopFile = Path.Combine(PathConf.ClientInstallPath, "sqrldev-sqrl.desktop");

            _shell.Term($"xdg-mime uninstall {desktopFile}", Output.Internal);
            _shell.Term($"xdg-desktop-menu uninstall sqrldev-sqrl.desktop", Output.Internal);
            _shell.Term($"update-desktop-database {SystemAndShellUtils.GetHomePath()}/.local/share/applications/", Output.Internal);

            // Run the inventory-based uninstaller
            await Uninstaller.Run(progress, dryRun);
        }
コード例 #16
0
        public async Task SetupAsync()
        {
            commandDirectoryCleanup = new CommandDirectoryCleanup();
            baseDir = commandDirectoryCleanup.CommandDirectory.BaseDir;
            var installer = new Installer(commandDirectoryCleanup.CommandDirectory);
            var installed = await installer.InstallAsync(packageName, null, force : false, includePreRelease : false);

            installed.Should().BeTrue();
            uninstaller = new Uninstaller(commandDirectoryCleanup.CommandDirectory);
            uninstalled = await uninstaller.UninstallAsync(packageName);

            uninstalled.Should().BeTrue();
        }
コード例 #17
0
        /// <summary>
        /// Uninstall Package - Before Delete (Old style events, no V6/V7 equivelant)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void InstalledPackage_BeforeDelete(InstalledPackage sender, System.EventArgs e)
        {
            //Check which package is being uninstalled
            if (sender.Data.Name != "Promote")
            {
                return;
            }

            //Start Uninstall - clean up process...
            Uninstaller.RemoveSectionDashboard();

            //Remove AppSetting key when all done
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("/");

            webConfig.AppSettings.Settings.Remove(AppSettingKey);
            webConfig.Save();
        }
コード例 #18
0
        public async Task UninstallsClickOnceApp()
        {
            var installer = new ClickOnceInstaller();
            await installer.InstallClickOnceApp(new Uri(IntegrationTestHelper.ClickOnceTestAppPath));

            UninstallInfo theApp = UninstallInfo.Find(IntegrationTestHelper.ClickOnceAppName);

            Assert.NotNull(theApp);

            var uninstaller = new Uninstaller();

            uninstaller.Uninstall(theApp);

            UninstallInfo shouldBeNull = UninstallInfo.Find(IntegrationTestHelper.ClickOnceAppName);

            Assert.Null(shouldBeNull);
        }
コード例 #19
0
        public override IEnumerable <JunkNode> FindJunk()
        {
            var output = new List <DriveJunkNode>();

            var uninLoc = Uninstaller.UninstallerLocation;

            if (uninLoc.IsNotEmpty() &&
                UninstallToolsGlobalConfig.GetAllProgramFiles().Any(
                    x => uninLoc.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)) &&
                !OtherInstallLocations.Any(x => uninLoc.StartsWith(x, StringComparison.InvariantCultureIgnoreCase) || x.StartsWith(uninLoc, StringComparison.InvariantCultureIgnoreCase)))
            {
                var resultNode = GetJunkNodeFromLocation(uninLoc);
                if (resultNode != null)
                {
                    output.Add(resultNode);
                }
            }

            if (Uninstaller.IsInstallLocationValid())
            {
                var resultNode = GetJunkNodeFromLocation(Uninstaller.InstallLocation);
                if (resultNode != null)
                {
                    output.Add(resultNode);
                }
            }

            output.AddRange(GetUninstallerJunk());

            foreach (var folder in FoldersToCheck)
            {
                output.AddRange(FindJunkRecursively(folder));
            }

            if (Uninstaller.UninstallerKind == UninstallerType.StoreApp)
            {
                foreach (var driveJunkNode in output)
                {
                    driveJunkNode.Confidence.Add(ConfidencePart.IsStoreApp);
                }
            }

            output.AddRange(SearchWerReports());

            return(RemoveDuplicates(output).Cast <JunkNode>());
        }
コード例 #20
0
        private void BeginInstall()
        {
            progressBar.Value   = 0;
            progressBar.Maximum = UNINSTALL_TICKS;

            new Task(new Action(() => {
                IntPtr redirection = RedirectionManager.DisableRedirection();

                try {
                    Uninstaller.Uninstall(this);
                    Complete();
                } catch (Exception e) {
                    Failure(e);
                } finally {
                    RedirectionManager.EnableRedirection(redirection);
                }
            })).Start();
        }
コード例 #21
0
 private void Btn_Uninstall_Click(object sender, EventArgs e)
 {
     if (!Directory.Exists(Txt_InstallLocation.Text))
     {
         MessageBox.Show("Install Location does not exist");
     }
     else if (!ChBox_SaveData.Checked)
     {
         Uninstaller.UninstallApp(Shortcuts, Txt_InstallLocation.Text);
         MessageBox.Show("Application successfully uninstalled");
     }
     else if (Directory.Exists(Txt_SaveLocation.Text) || (!Directory.Exists(Txt_SaveLocation.Text) &&
                                                          MessageBox.Show("Save Folder does not exist so installer will need to create one. Continue?", "Uninstall", MessageBoxButtons.YesNo) == DialogResult.Yes))
     {
         Uninstaller.MoveApp(Shortcuts, Txt_InstallLocation.Text, Txt_SaveLocation.Text);
         MessageBox.Show("Application successfully saved to save location");
     }
 }
コード例 #22
0
        private void FlatButtonUninstall_Click(object sender, EventArgs e)
        {
            if (!_successfulUninstall)
            {
                timerCheckRunning.Stop();

                labelProgress.Text       = "Uninstalling";
                progressBarInstall.Value = 0;
                progressBarInstall.SetState(1);
                progressBarInstall.Style = ProgressBarStyle.Marquee;

                flatButtonUninstall.Enabled = false;
                flatButtonUninstallCancel.Hide();
                borderPanelProgressInstall.Show();

                Timer t = new Timer()
                {
                    Interval = 1000
                };
                t.Tick += delegate
                {
                    _uninstaller = new Uninstaller(_config);

                    progressBarInstall.Style = ProgressBarStyle.Continuous;

                    var worker = new BackgroundWorker();
                    worker.ProgressChanged    += Worker_ProgressChanged;
                    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;

                    _uninstaller.Start(worker);

                    t.Stop();
                    t.Dispose();
                };
                t.Start();
            }
            else
            {
                RemoveArtifact();
                _navigator.CancelInstall();
            }
        }
コード例 #23
0
        public override IEnumerable <JunkNode> FindJunk()
        {
            var softwareKeys = GetSoftwareRegKeys(Uninstaller.Is64Bit);
            var returnList   = new List <RegistryJunkNode>();

            foreach (var softwareKey in softwareKeys)
            {
                FindJunkRecursively(returnList, softwareKey, 0);
            }

            if (Uninstaller.RegKeyStillExists())
            {
                var regKeyNode = new RegistryJunkNode(PathTools.GetDirectory(Uninstaller.RegistryPath),
                                                      Uninstaller.RegistryKeyName, Uninstaller.DisplayName);
                regKeyNode.Confidence.Add(ConfidencePart.IsUninstallerRegistryKey);
                returnList.Add(regKeyNode);
            }

            return(returnList.Cast <JunkNode>());
        }
コード例 #24
0
        public static IDisposable WithClickOnceApp()
        {
            string clickOnceApp = Path.Combine(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.FullName, "ClickOnceApp/ClickOnceApp.application"); // omg
            var    installer    = new ClickOnceInstaller();

            installer.InstallClickOnceApp(new Uri(clickOnceApp)).Wait();

            return(Disposable.Create(() =>
            {
                UninstallInfo theApp = UninstallInfo.Find(ClickOnceAppName);

                if (theApp == null)
                {
                    return;
                }

                var uninstaller = new Uninstaller();
                uninstaller.Uninstall(theApp);
            }));
        }
コード例 #25
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            string installPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\" + installedPathRegKeyName, "InstallPath", "") ?? "";

            // get system display language
            string displayLanguage = CultureInfo.InstalledUICulture.TwoLetterISOLanguageName;

            // import strings.json from resources and parse it into a JObject


            state = InstallerState.Read(installPath);
            state.Update();
            if (e.Args.Length > 0 && e.Args[0] == "/uninstall")
            {
                if (MessageBox.Show("Are you sure you want to uninstall KinectToVR?", "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    try {
                        if (Uninstaller.UninstallK2EX(installPath))
                        {
                            MessageBox.Show("Uninstalled successfully!");
                            if (Directory.Exists(installPath))
                            {
                                // https://stackoverflow.com/a/1305478/
                                ProcessStartInfo Info = new ProcessStartInfo();
                                Info.Arguments      = "/C choice /C Y /N /D Y /T 3 & rmdir /S /Q \"" + installPath + "\"";
                                Info.WindowStyle    = ProcessWindowStyle.Hidden;
                                Info.CreateNoWindow = true;
                                Info.FileName       = "cmd.exe";
                                Process.Start(Info);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("An error happened while trying to uninstall. Join our Discord for help on manually uninstalling.");
                        new ExceptionDialog(ex).ShowDialog();
                    }
                }
                Current.Shutdown(0);
            }
        }
コード例 #26
0
ファイル: CreateSite.cs プロジェクト: makhalaf/frapid
        public override async Task ExecuteCommandAsync()
        {
            if (!this.IsValid)
            {
                return;
            }

            ConsolePathMapper.SetPathToRoot();

            try
            {
                new ApprovedDomainSerializer().Add
                (
                    new ApprovedDomain
                {
                    DomainName                 = this.DomainName,
                    DbProvider                 = this.ProviderName,
                    Synonyms                   = new string[0],
                    BackupDirectory            = string.Empty,
                    AdminEmail                 = string.Empty,
                    EnforceSsl                 = false,
                    BackupDirectoryIsFixedPath = false,
                    CdnDomain                  = string.Empty
                });


                var installer = new Tenant.Installer(this.DomainName);
                await installer.InstallAsync().ConfigureAwait(false);
            }
            finally
            {
                if (this.CleanupWhenDone)
                {
                    var uninstaller = new Uninstaller(this.DomainName);
                    await uninstaller.UnInstallAsync().ConfigureAwait(false);
                }
            }
        }
コード例 #27
0
        public async Task UninstallsClickOnceApp()
        {
            var installer = new ClickOnceInstaller();
            await installer.InstallClickOnceApp(new Uri(IntegrationTestHelper.ClickOnceTestAppPath));

            UninstallInfo theApp = UninstallInfo.Find(IntegrationTestHelper.ClickOnceAppName);

            Assert.NotNull(theApp);

            var uninstaller = new Uninstaller();
            uninstaller.Uninstall(theApp);

            UninstallInfo shouldBeNull = UninstallInfo.Find(IntegrationTestHelper.ClickOnceAppName);

            Assert.Null(shouldBeNull);
        }
コード例 #28
0
        async Task CheckForUpdates()
        {
            try
            {
                if (Config.Default.settings.update.isDisabled)
                {
                    Trace.TraceInformation("The software update check is disabled by the user; skipping check");
                    return;
                }

                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                }

                var applicationDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "IPFilter");
                var installerDir         = new DirectoryInfo(Path.Combine(applicationDirectory, "installer"));

                // Detect the current running version. The ProductVersion contains the informational, semantic version e.g. "3.0.0-beta"
                var versionInfo    = Process.GetCurrentProcess().MainModule.FileVersionInfo;
                var currentVersion = new SemanticVersion(versionInfo.ProductVersion);

                // Remove any old installers
                try
                {
                    if (!installerDir.Exists)
                    {
                        installerDir.Create();
                    }
                    else if (!Config.Default.settings.update.isCleanupDisabled)
                    {
                        // Don't delete the MSI for the current installed version
                        var currentMsiName = "IPFilter." + currentVersion.ToNormalizedString() + ".msi";

                        // Scan the directory for all installers
                        foreach (var fileInfo in installerDir.GetFiles("IPFilter.*.msi"))
                        {
                            // Don't remove the installer for the installed version
                            if (fileInfo.Name.Equals(currentMsiName, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            Trace.TraceInformation("Removing cached installer: " + fileInfo.Name);
                            fileInfo.SafeDelete();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Couldn't clean up old installers: " + ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync(Config.Default.settings.update.isPreReleaseEnabled);

                if (result == null)
                {
                    return;
                }

                var latestVersion = new SemanticVersion(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://www.ipfilter.app/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                // Download the MSI to the installer directory
                var msiPath = Path.Combine(installerDir.FullName, "IPFilter." + Update.AvailableVersion + ".msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                var installLog = Path.Combine(applicationDirectory, "install.log");
                sb.AppendFormat(" /l*v \"{0}\"", installLog);

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
コード例 #29
0
        /// <summary>
        ///     Backend input
        /// </summary>
        /// <param name="inputargs">Input</param>
        public static void doCommand(string[] inputargs)
        {
            switch (inputargs[0])
            {
            case "reload":
                JsonModList.GetModLists(true);
                break;

            case "wipe":
                File.Delete(Directory.GetCurrentDirectory() + @"\installedmods.json");
                Console.WriteLine("Wiped!");
                break;

            case "modlists":
                listmodlists();
                break;

            case "check":

                var ml = JsonModList.GetModLists();

                for (var i = 0; i < ml.Length; i++)
                {
                    for (var x = 0; x < ml[i].Modlist.Length; x++)
                    {
                        if (ml[i].Modlist[x].ModId == inputargs[1])
                        {
                            var link = ml[i].Modlist[x].Website;
                            var psi  = new ProcessStartInfo
                            {
                                FileName        = link,
                                UseShellExecute = true
                            };
                            Process.Start(psi);
                        }
                    }
                }

                break;

            case "dl":
                Downloader.DownloadModDirector(inputargs[1]);
                break;

            case "install":
                Downloader.DownloadModDirector(inputargs[1], true);
                break;

            case "list":
                if (inputargs[1] == "installedmods")
                {
                    var mf = InstalledMods.GetInstalledMods();
                    for (var i = 0; i < mf.Length; i++)
                    {
                        Console.WriteLine(mf[i].Name);
                    }
                }
                else
                {
                    list(inputargs[1]);
                }

                break;

            case "exit":
                return;

            case "help":
                Console.WriteLine("wipe - Wipes the installed registry (DOES NOT DELETE MODS)");
                Console.WriteLine("modlists - Lists all modlists, which are lists of mods.");
                Console.WriteLine("dl [modname] - Downloads mod listed.");
                Console.WriteLine("check [modname] - Opens browser to modpage.");
                Console.WriteLine("list [modlist] - Lists all mods contained in a modlist.");
                Console.WriteLine("list installedmods - Lists all mods registered as installed.");
                Console.WriteLine("exit - Close H3VRModInstaller.");
                break;

            case "toggledebugging":
                ModInstallerCommon.enableDebugging = !ModInstallerCommon.enableDebugging;
                Console.WriteLine("Debugging is now " + ModInstallerCommon.enableDebugging);
                break;

            //deletion
            case "rm":
                Console.WriteLine($"Deleting {inputargs[1]}");
                Uninstaller.DeleteMod(inputargs[1]);
                break;

            default:
                Console.WriteLine("Invalid command!");
                break;
            }
        }
コード例 #30
0
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                            var uninstaller = new Uninstaller();
                            uninstaller.Uninstall(uninstallInfo);
                            Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);
                
                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion = latestVersion;
                    Update.IsUpdateRequired = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable ) return;
                
                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                    "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }
                
                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string) key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                    using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                            Update.IsUpdating = false;
                            return;
                        }

                        var length = response.Content.Headers.ContentLength;
                        double lengthInMb = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                        double bytesDownloaded = 0;

                        using(var stream = await response.Content.ReadAsStreamAsync())
                        using(var msi = File.Open( msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            var buffer = new byte[65535 * 4];

                            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            while (bytesRead != 0)
                            {
                                await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);
                                bytesDownloaded += bytesRead;

                                if (length.HasValue)
                                {
                                    double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                    var percent = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                    var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                    Update.IsUpdating = true;
                                    Update.DownloadPercentage = percent;
                                    progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                }

                                if (cancellationToken.IsCancellationRequested)
                                {
                                    progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                    Update.IsUpdating = false;
                                    return;
                                }

                                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            }
                        }
                    }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;
                
                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));
                
                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo startupInfo = new StartupInfo();
                SecurityAttributes processSecurity = new SecurityAttributes();
                SecurityAttributes threadSecurity = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                    threadSecurity, false, NormalPriorityClass,
                    IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                
                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
コード例 #31
0
ファイル: Installer.cs プロジェクト: sqrldev/SQRLDotNetClient
        #pragma warning restore 1998

        public async Task Uninstall(IProgress <Tuple <int, string> > progress = null, bool dryRun = true)
        {
            await Uninstaller.Run(progress, dryRun);
        }
コード例 #32
0
        public async void OnSelected()
        {
            await Task.Run(() =>
            {
                Log("K2EX Installer " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " on " + DateTime.Now.ToString());

                Log("Checking if SteamVR is open...", false);
                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == "vrmonitor")
                    {
                        Log("Closing vrmonitor...", false);
                        process.CloseMainWindow();
                        Thread.Sleep(5000);
                        if (!process.HasExited)
                        {
                            Log("Force closing...", false);

                            /* When SteamVR is open with no headset detected,
                             * CloseMainWindow will only close the "headset not found" popup
                             * so we kill it, if it's still open */
                            process.Kill();
                            Thread.Sleep(3000);
                        }
                    }
                }

                /* Apparently, SteamVR server can run without the monitor,
                 * so we close that, if it's open as well (monitor will complain if you close server first) */
                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == "vrserver")
                    {
                        Log("Closing vrserver...", false);
                        // CloseMainWindow won't work here because it doesn't have a window
                        process.Kill();
                        Thread.Sleep(5000);
                        if (!process.HasExited)
                        {
                            MessageBox.Show(Properties.Resources.install_steamvr_close_failed);
                            Cancel();
                            return;
                        }
                    }
                }
                Log("Done!");

                Log("Checking for legacy installations...", false);
                Uninstaller.UninstallK2VrLegacy(this);

                Log("Checking for other K2EX installations...", false);
                try
                {
                    if (!Uninstaller.UninstallAllK2EX(this))
                    {
                        return;
                    }
                }
                catch (Exception e)
                {
                    Dispatcher.Invoke(() =>
                    {
                        if (new ExceptionDialog(e, true).ShowDialog().Value != true)
                        {
                            Application.Current.Shutdown(1);
                        }
                    });
                }
                Log("Done!");

                Log("Checking install directory...", false);
                bool dirExists = Directory.Exists(App.state.GetFullInstallationPath());
                Log("Done!");
                Log("Creating install directory...", false);
                if (!dirExists)
                {
                    Directory.CreateDirectory(App.state.GetFullInstallationPath());
                }
                Log("Done!");

                Log("Extracting OpenVR driver...", false);
                string zipFileName = Path.Combine(App.downloadDirectory + FileDownloader.files["k2vr"].OutName);
                using (ZipArchive archive = ZipFile.OpenRead(zipFileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string newName  = entry.FullName.Substring("K2EX/".Length); // Remove the top level folder
                        string fullPath = Path.GetFullPath(Path.Combine(App.state.GetFullInstallationPath(), newName));
                        if (fullPath.EndsWith(@"\", StringComparison.Ordinal))
                        {
                            Directory.CreateDirectory(fullPath);
                            App.state.installedFolders.Add(fullPath);
                        }
                        else
                        {
                            entry.ExtractToFile(fullPath, true);
                            App.state.installedFiles.Add(fullPath);
                        }
                    }
                }
                Log("Done!");

                Log("Registering application...", false);
                App.state.Write();
                // we need to manually set file attribs before copying.
                File.SetAttributes(Path.Combine(App.state.GetFullInstallationPath(), "k2vr-installer-gui.exe"), FileAttributes.Normal);
                File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(App.state.GetFullInstallationPath(), "k2vr-installer-gui.exe"), true);
                Uninstaller.RegisterUninstaller();

                if ((App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect && !App.state.kinectV1SdkInstalled) ||
                    (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect && !App.state.kinectV2SdkInstalled))
                {
                    Log("Installing the Kinect SDK...", false);
                    string sdkInstaller         = Path.Combine(App.downloadDirectory, FileDownloader.files[(App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect) ? "kinect_v1_sdk" : "kinect_v2_sdk"].OutName);
                    Process sdkInstallerProcess = Process.Start(sdkInstaller);
                    Thread.Sleep(1000);
                    try
                    {
                        // https://stackoverflow.com/a/3734322/
                        AutomationElement element = AutomationElement.FromHandle(sdkInstallerProcess.MainWindowHandle);
                        if (element != null)
                        {
                            element.SetFocus();
                        }
                    }
                    catch (Exception) { } // Don't want the whole install to fail for something that mundane
                    sdkInstallerProcess.WaitForExit();

                    App.state.UpdateSdkInstalled();

                    if ((App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect && !App.state.kinectV1SdkInstalled) ||
                        (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect && !App.state.kinectV2SdkInstalled))
                    {
                        Log("Failed!");
                        MessageBox.Show(Properties.Resources.install_sdk_failed);
                        Cancel();
                        return;
                    }
                    Log("Done!");
                }
                else
                {
                    Log("Kinect SDK is already installed.");
                }

                Log("Installing Visual C++ Redistributable...", false);
                string vcRedistPath = Path.Combine(App.downloadDirectory, FileDownloader.files["vc_redist2019"].OutName);
                Process.Start(vcRedistPath, "/quiet /norestart").WaitForExit();
                Log("Done!");

                Log("Registering OpenVR driver...", false);
                string driverPath = Path.Combine(App.state.GetFullInstallationPath(), "KinectToVR");
                Process.Start(App.state.vrPathReg, "adddriver \"" + driverPath + "\"").WaitForExit();
                Log("Checking...", false);
                var openVrPaths = OpenVrPaths.Read();
                if (!openVrPaths.external_drivers.Contains(driverPath))
                {
                    Log("Copying...", false);
                    CopyFilesRecursively(new DirectoryInfo(driverPath), new DirectoryInfo(App.state.copiedDriverPath));
                }
                Log("Done!");

                string kinectProcessName = "KinectV" + (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect ? "2" : "1") + "Process";

                Log("Registering OpenVR overlay...", false);

                var appConfig       = AppConfig.Read();
                string manifestPath = Path.Combine(App.state.GetFullInstallationPath(), kinectProcessName + ".vrmanifest");
                if (!appConfig.manifest_paths.Contains(manifestPath))
                {
                    appConfig.manifest_paths.Add(manifestPath);
                    appConfig.Write();
                    Log("Done!");
                }
                else
                {
                    Log("Already done!");
                }

                Log("Disabling SteamVR Home, enabling advanced settings...", false);
                var steamVrSettings = JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(App.state.steamVrSettingsPath));
                try
                {
                    steamVrSettings["steamvr"]["enableHomeApp"]        = false;
                    steamVrSettings["steamvr"]["showAdvancedSettings"] = true;
                    JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' ');
                    Log("Done!");
                }
                catch (Exception)
                {
                    Log("Failed (uncritical)!");
                }
                Log("Registering tracker roles...", false);
                try
                {
                    if (steamVrSettings["trackers"] == null)
                    {
                        steamVrSettings["trackers"] = new JObject();
                    }
                    steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB11ABEC"] = "TrackerRole_Waist";
                    steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB1441A7"] = "TrackerRole_RightFoot";
                    steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB9AD1T2"] = "TrackerRole_LeftFoot";
                    JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' ');
                    Log("Done!");
                }
                catch (Exception)
                {
                    Log("Failed (uncritical)!");
                }
                Log("Enabling driver in SteamVR...", false);
                try
                {
                    if (steamVrSettings["driver_kinecttovr"] == null)
                    {
                        steamVrSettings["driver_kinecttovr"] = new JObject();
                    }
                    steamVrSettings["driver_kinecttovr"]["enable"] = true;
                    steamVrSettings["driver_kinecttovr"]["blocked_by_safe_mode"] = false;
                    JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' ');
                    Log("Done!");
                }
                catch (Exception)
                {
                    Log("Failed (uncritical)!");
                }

                Log("Creating start menu entry...", false);
                if (!Directory.Exists(App.startMenuFolder))
                {
                    Directory.CreateDirectory(App.startMenuFolder);
                }
                // https://stackoverflow.com/a/4909475/
                var shell = new IWshRuntimeLibrary.WshShell();
                string shortcutAddress    = Path.Combine(App.startMenuFolder, "KinectToVR.lnk");
                var shortcut              = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
                shortcut.Description      = "Launch KinectToVR";
                shortcut.TargetPath       = Path.Combine(App.state.GetFullInstallationPath(), kinectProcessName + ".exe");
                shortcut.IconLocation     = Path.Combine(App.state.GetFullInstallationPath(), "k2vr.ico");
                shortcut.WorkingDirectory = Path.Combine(App.state.GetFullInstallationPath());
                shortcut.Save();
                Log("Refreshing...", false);
                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == "StartMenuExperienceHost")
                    {
                        process.Kill();
                        Thread.Sleep(500);
                    }
                }
                Log("Done!");

                Log("Installation complete!");
                Log("The installation log can be found in \"" + App.downloadDirectory + "\"", false);
                Button_Complete_Install.Dispatcher.Invoke(() =>
                {
                    Button_Complete_Install.IsEnabled = true;
                });
            });
        }
コード例 #33
0
ファイル: Maintenance.cs プロジェクト: notperry1234567890/osu
        void uninstall(object sender, DoWorkEventArgs e)
        {
            if (!OsuMain.IsElevated)
            {
                OsuMain.Elevate(@"-uninstall", false);
                return;
            }

            try
            {
                init();
                setProgress(0, OsuString.Maintenance_Bye);

                int seconds = 10;
                while (seconds > 0)
                {
                    setText(string.Format(LocalisationManager.GetString(OsuString.Maintenance_Uninstall) + '\n' +
                                          LocalisationManager.GetString(OsuString.Maintenance_Uninstall2), seconds), true);
                    Thread.Sleep(1000);
                    seconds--;

                    while (installPath == null)
                    {
                        Thread.Sleep(100);
                    }
                }

                setText(LocalisationManager.GetString(OsuString.Maintenance_Uninstalling), true);

                string[] directories = Directory.GetDirectories(Environment.CurrentDirectory);

                int totalProgressItems = directories.Length + 8;
                int currentProgress    = 0;

                //delete subdirectories
                foreach (string dir in directories)
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    try
                    {
                        Directory.Delete(dir, true);
                    }
                    catch
                    {
                    }

                    Thread.Sleep(100);
                }

                //delete main directory
                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    Directory.Delete(Environment.CurrentDirectory, true);
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    foreach (string file in Directory.GetFiles(Environment.CurrentDirectory))
                    {
                        GeneralHelper.FileDeleteOnReboot(file);
                    }
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    Directory.Delete(Environment.CurrentDirectory);
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    GeneralHelper.FileDeleteOnReboot(Environment.CurrentDirectory);
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    Uninstaller.RemoveUninstaller();
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    File.Delete(icon_path_desktop);
                    File.Delete(icon_path_startmenu);
                }
                catch
                {
                }

                try
                {
                    setProgress((int)(((float)++currentProgress / totalProgressItems) * 100));
                    GeneralHelper.RegistryDelete(@"osu!");
                    GeneralHelper.RegistryDelete(@"osu");
                }
                catch
                {
                }

                setProgress(100);
                setText(LocalisationManager.GetString(OsuString.Maintenance_Farewell), true);
                Thread.Sleep(5000);
            }
            catch { }
        }