Exemple #1
0
        private void InitElevationWarning()
        {
            var isEnabledFeature = false;

            // Enable this only for new platform
#if TESTNET || TESTNETDEV || PRODUCTION_NEW
            isEnabledFeature = true;
#endif
            if (!Helpers.IsElevated && isEnabledFeature)
            {
                errorWarningProvider2.SetError(linkLabelAdminPrivs, Tr("Disabled NVIDIA power mode settings due to insufficient permissions. If you want to use this feature you need to run as Administrator."));
                linkLabelAdminPrivs.Click += (s, e) =>
                {
                    var dialogResult = MessageBox.Show(Tr("Click yes if you with to run NiceHash Miner Legacy as Administrator."),
                                                       Tr("Run as Administrator"),
                                                       MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (dialogResult == DialogResult.Yes)
                    {
                        RunAsAdmin.SelfElevate();
                    }
                };
            }
            else
            {
                linkLabelAdminPrivs.Visible = false;
            }
        }
Exemple #2
0
 private void InitElevationWarning()
 {
     if (!Helpers.IsElevated && !ConfigManager.GeneralConfig.DisableDevicePowerModeSettings)
     {
         errorWarningProvider2.SetError(linkLabelAdminPrivs, Tr("Disabled NVIDIA power mode settings due to insufficient permissions. If you want to use this feature you need to run as Administrator."));
         linkLabelAdminPrivs.Click += (s, e) =>
         {
             var dialogResult = MessageBox.Show(Tr("Click yes if you wish to run {0} as Administrator.", NHMProductInfo.Name),
                                                Tr("Run as Administrator"),
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Information);
             if (dialogResult == DialogResult.Yes)
             {
                 RunAsAdmin.SelfElevate();
             }
         };
     }
     else
     {
         linkLabelAdminPrivs.Visible = false;
     }
 }
Exemple #3
0
        private async void App_OnStartup(object sender, StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode     = RenderMode.SoftwareOnly;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            ClearAllDoFiles();
            // Set shutdown mode back to default
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            var isUpdater = Environment.GetCommandLineArgs().Contains("-update");
            var isUpdated = Environment.GetCommandLineArgs().Contains("-updated");

            if (isUpdater)
            {
                var updatersPath = GetRootPath("updaters");
                // TODO check the latest files here
                //var updaterFile = Path.Combine(updatersPath, "nhm_windows_3.0.0.1.zip");
                var latestUpdaterFile = GetLatestUpdater();
                if (latestUpdaterFile == null)
                {
                    var restartProcessUpdatefailed = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updateFailed",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    restartProcessUpdatefailed.Start();
                    // shutdown
                    Shutdown();
                    return;
                }
                var updaterFile = GetRootPath("updaters", latestUpdaterFile);
                // TODO find latest
                var isZip = updaterFile.EndsWith(".zip");

                //await Task.Delay(5000);
                if (isZip)
                {
                    var pluginPackagesPath = GetRootPath("plugins_packages");
                    if (Directory.Exists(pluginPackagesPath))
                    {
                        Directory.Delete(pluginPackagesPath, true);
                    }

                    var progWindow = new UpdateProgress();
                    progWindow.Show();
                    var isOk = await UnzipFileAsync(updaterFile, GetRootPath(), progWindow.Progress, CancellationToken.None);

                    progWindow.Close();
                    await Task.Delay(500);

                    // TODO if something goes wrong just restore the current exe process file
                    var restartProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updated",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    restartProcess.Start();
                }
                else
                {
                    // TODO updater should start nhm
                    var startUpdater = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = updaterFile,
                            WorkingDirectory = GetRootPath(),
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    startUpdater.Start();
                    // TODO we should wait and check if we have restarted NiceHash Miner
                }

                // shutdown
                Shutdown();
                return;
            }
            if (isUpdated)
            {
                await Task.Delay(500);             // so we release the temp files
            }
            await WindowsUptimeCheck.DelayUptime();

            bool createdNew = false;

            try
            {
                string appPath = GetHashString();
                _mutex = new Mutex(true, appPath, out createdNew);
                if (!createdNew)
                {
                    //MessageBox.Show("We have detected you are already running NiceHash Miner. Only a single instance should be running at a time.", "NiceHash Miner Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    // shutdown
                    Shutdown();
                    return;
                }

                ClearAllTmpFiles();

                // TODO pass parent process PID
                var latestAppDir = GetLatestApp();
                var nhmApp       = GetRootPath(latestAppDir, "NiceHashMiner.exe");
                var args         = $"-lc -PID{Process.GetCurrentProcess().Id}";
                if (isUpdated)
                {
                    args += " -updated";
                }
                var startInfo = new ProcessStartInfo
                {
                    FileName    = nhmApp,
                    Arguments   = args,
                    WindowStyle = ProcessWindowStyle.Normal
                };
                var       run                     = true;
                const int maxRestartCount         = 3;
                int       restartCount            = 0;
                const int minRestartTimeInSeconds = 30;
                while (run)
                {
                    var startTime = DateTime.UtcNow;
                    run = false;
                    try
                    {
                        using (var niceHashMiner = new Process {
                            StartInfo = startInfo
                        })
                        {
                            var hasStarted = niceHashMiner?.Start();
                            niceHashMiner?.WaitForExit();
                            // TODO
                            Console.WriteLine(niceHashMiner.ExitCode);
                            //in case of crash try to restart the program
                            if (niceHashMiner.ExitCode != 0)
                            {
                                var endTime = DateTime.UtcNow;

                                string path = GetRootPath("logs", "watchdogLog.txt");
                                if (!File.Exists(path))
                                {
                                    using (var sw = File.CreateText(path))
                                    {
                                        sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}");
                                    }
                                }
                                else
                                {
                                    using (var sw = File.AppendText(path))
                                    {
                                        sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}");
                                    }
                                }
                                //try to re-run the NHM
                                run = true;

                                //check if too many restarts
                                var elapsedSeconds = (endTime - startTime).TotalSeconds;
                                if (elapsedSeconds < minRestartTimeInSeconds)
                                {
                                    restartCount++;
                                }
                                else
                                {
                                    restartCount = 0;
                                }
                                if (restartCount >= maxRestartCount)
                                {
                                    using (var sw = File.AppendText(path))
                                    {
                                        sw.WriteLine($"Too many restarts! Closing nhm");
                                    }
                                    MessageBox.Show("NHM experienced too many crashes recently, therefore it will close itself", "Too many restarts");
                                    run = false;
                                }
                            }
                            else
                            {
                                // if exit code is 0 then check runasadmin or restart
                                if (IsRunAsAdmin())
                                {
                                    RunAsAdmin.SelfElevate();
                                }
                                else if (IsRestart())
                                {
                                    ClearAllDoFiles();
                                    run = true;
                                }
                                else if (IsUpdate())
                                {
                                    run = true; // mark to false if updating doesn't fail
                                    ClearAllDoFiles();
                                    var exePath     = Assembly.GetExecutingAssembly().Location;
                                    var randomPart  = DateTime.UtcNow.Millisecond;
                                    var tmpLauncher = GetRootPath($"tmp.nhm_updater_{randomPart}.exe");
                                    File.Copy(exePath, tmpLauncher, true);
                                    var doUpdate = new Process
                                    {
                                        StartInfo = new ProcessStartInfo
                                        {
                                            FileName    = tmpLauncher,
                                            Arguments   = "-update",
                                            WindowStyle = ProcessWindowStyle.Normal
                                        }
                                    };
                                    var updateStarted = doUpdate.Start();
                                    run = !updateStarted; // set if we are good
                                }
                                else /*ELSE*/ } {
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            // shutdown
            Shutdown();
            return;
        }
        finally
        {
            if (createdNew)
            {
                _mutex?.ReleaseMutex();
            }
        }
    }
        private async void App_OnStartup(object sender, StartupEventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            ClearAllDoFiles();
            // Set shutdown mode back to default
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            var isUpdater = Environment.GetCommandLineArgs().Contains("-update");
            var isUpdated = Environment.GetCommandLineArgs().Contains("-updated");

            if (isUpdater)
            {
                var updatersPath = GetRootPath("updaters");
                // TODO check the latest files here
                //var updaterFile = Path.Combine(updatersPath, "nhm_windows_3.0.0.1.zip");
                var latestUpdaterFile = GetLatestUpdater();
                if (latestUpdaterFile == null)
                {
                    var restartProcessUpdatefailed = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updateFailed",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    restartProcessUpdatefailed.Start();
                    // shutdown
                    Shutdown();
                    return;
                }
                var updaterFile = GetRootPath("updaters", latestUpdaterFile);
                // TODO find latest
                var isZip = updaterFile.EndsWith(".zip");

                //await Task.Delay(5000);
                if (isZip)
                {
                    var progWindow = new UpdateProgress();
                    progWindow.Show();
                    var isOk = await UnzipFileAsync(updaterFile, GetRootPath(), progWindow.Progress, CancellationToken.None);

                    progWindow.Close();
                    await Task.Delay(500);

                    // TODO if something goes wrong just restore the current exe process file
                    var restartProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updated",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    restartProcess.Start();
                }
                else
                {
                    // TODO updater should start nhm
                    var startUpdater = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = updaterFile,
                            WorkingDirectory = GetRootPath(),
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    startUpdater.Start();
                    // TODO we should wait and check if we have restarted NiceHash Miner
                }

                // shutdown
                Shutdown();
                return;
            }
            if (isUpdated)
            {
                await Task.Delay(500);             // so we release the temp files
            }
            await WindowsUptimeCheck.DelayUptime();

            bool createdNew = false;

            try
            {
                string appPath = GetHashString();
                _mutex = new Mutex(true, appPath, out createdNew);
                if (!createdNew)
                {
                    //MessageBox.Show("We have detected you are already running NiceHash Miner. Only a single instance should be running at a time.", "NiceHash Miner Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    // shutdown
                    Shutdown();
                    return;
                }

                ClearAllTmpFiles();

                // TODO pass parent process PID
                var latestAppDir = GetLatestApp();
                var nhmApp       = GetRootPath(latestAppDir, "NiceHashMiner.exe");
                var args         = $"-lc -PID{Process.GetCurrentProcess().Id}";
                if (isUpdated)
                {
                    args += " -updated";
                }
                var startInfo = new ProcessStartInfo
                {
                    FileName    = nhmApp,
                    Arguments   = args,
                    WindowStyle = ProcessWindowStyle.Normal
                };
                var run = true;
                while (run)
                {
                    run = false;
                    try
                    {
                        using (var niceHashMiner = new Process {
                            StartInfo = startInfo
                        })
                        {
                            var hasStarted = niceHashMiner?.Start();
                            niceHashMiner?.WaitForExit();
                            // TODO
                            Console.WriteLine(niceHashMiner.ExitCode);
                            // if exit code is 0 then check runasadmin or restart
                            if (IsRunAsAdmin())
                            {
                                RunAsAdmin.SelfElevate();
                            }
                            else if (IsCreateLog())
                            {
                                try
                                {
                                    run = true;
                                    ClearAllDoFiles();

                                    var exePath      = GetRootPath("CreateLogReport.exe");
                                    var startLogInfo = new ProcessStartInfo
                                    {
                                        FileName        = exePath,
                                        WindowStyle     = ProcessWindowStyle.Minimized,
                                        UseShellExecute = true,
                                        Arguments       = latestAppDir,
                                        CreateNoWindow  = true
                                    };
                                    using (var doCreateLog = Process.Start(startLogInfo))
                                    {
                                        doCreateLog.WaitForExit(10 * 1000);
                                    }

                                    var tmpZipPath     = GetRootPath($"tmp._archive_logs.zip");
                                    var desktopZipPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "NiceHashMinerLogs.zip");
                                    File.Copy(tmpZipPath, desktopZipPath, true);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                }
                                ClearAllTmpFiles();
                            }
                            else if (IsRestart())
                            {
                                ClearAllDoFiles();
                                run = true;
                            }
                            else if (IsUpdate())
                            {
                                run = true; // mark to false if updating doesn't fail
                                ClearAllDoFiles();
                                var exePath     = Assembly.GetExecutingAssembly().Location;
                                var randomPart  = DateTime.UtcNow.Millisecond;
                                var tmpLauncher = GetRootPath($"tmp.nhm_updater_{randomPart}.exe");
                                File.Copy(exePath, tmpLauncher, true);
                                var doUpdate = new Process
                                {
                                    StartInfo = new ProcessStartInfo
                                    {
                                        FileName    = tmpLauncher,
                                        Arguments   = "-update",
                                        WindowStyle = ProcessWindowStyle.Normal
                                    }
                                };
                                var updateStarted = doUpdate.Start();
                                run = !updateStarted; // set if we are good
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                // shutdown
                Shutdown();
                return;
            }
            finally
            {
                if (createdNew)
                {
                    _mutex?.ReleaseMutex();
                }
            }
        }
Exemple #5
0
        private async void App_OnStartup(object sender, StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode     = RenderMode.SoftwareOnly;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            ClearAllDoFiles();
            // Set shutdown mode back to default
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            var isUpdater = Environment.GetCommandLineArgs().Contains("-update");
            var isUpdated = Environment.GetCommandLineArgs().Contains("-updated");

#warning TRANSITIONAL CODE, REMOVE IN FUTURE VERSIONS (registry integration)
            if (isUpdated)
            {
                const string GUID        = "8abad8e2-b957-48ed-92ba-4339c2a40e78";
                const string TOSMain     = "4";
                const string TOS3rdParty = "4";
#if DEBUG
                string generalSettingsFile = GetRootPath("app/configs/General.json");
#else
                string generalSettingsFile = GetRootPath("configs/General.json");
#endif
                try
                {
                    var generalSettingsText = System.IO.File.ReadAllLines(generalSettingsFile);
                    var agreeTOS            = generalSettingsText.Where(line => line.Contains("AgreedWithTOS")).FirstOrDefault();
                    if (agreeTOS != null)
                    {
                        agreeTOS = agreeTOS.Split(':')
                                   .Last()
                                   .Replace(",", "")
                                   .Trim();
                        if (agreeTOS == TOSMain)
                        {
                            SetSubKey("AgreedWithTOS", 4);
                        }
                    }

                    var agreeTOSMiner = generalSettingsText.Where(line => line.Contains("Use3rdPartyMinersTOS")).FirstOrDefault();
                    if (agreeTOSMiner != null)
                    {
                        agreeTOSMiner = agreeTOSMiner.Split(':')
                                        .Last()
                                        .Replace(",", "")
                                        .Trim();
                        if (agreeTOSMiner == TOS3rdParty)
                        {
                            SetSubKey("Use3rdPartyMinersTOS", 4);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Logger.Error("NHMLauncher", ex.Message);
                }
            }

            var afterUpdate = false;
            if (isUpdater)
            {
                var latestUpdaterFile = GetLatestUpdater();
                if (latestUpdaterFile == null)
                {
                    var restartProcessUpdatefailed = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updateFailed",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    restartProcessUpdatefailed.Start();
                    // shutdown
                    Shutdown();
                    return;
                }
                var updaterFile = GetRootPath("updaters", latestUpdaterFile);
                var isZip       = updaterFile.EndsWith(".zip");

                //await Task.Delay(5000);
                if (isZip)
                {
                    var pluginPackagesPath = GetRootPath("plugins_packages");
                    if (Directory.Exists(pluginPackagesPath))
                    {
                        Directory.Delete(pluginPackagesPath, true);
                    }

                    var progWindow = new UpdateProgress();
                    progWindow.Show();
                    var isOk = await UnzipFileAsync(updaterFile, GetRootPath(), progWindow.Progress, CancellationToken.None);

                    progWindow.Close();
                    await Task.Delay(500);

                    // TODO if something goes wrong just restore the current exe process file
                    var restartProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = GetRootPath("NiceHashMiner.exe"),
                            WorkingDirectory = GetRootPath(),
                            Arguments        = "-updated",
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    afterUpdate = true;
                    restartProcess.Start();
                }
                else
                {
                    var startUpdater = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName         = updaterFile,
                            WorkingDirectory = GetRootPath(),
                            WindowStyle      = ProcessWindowStyle.Normal
                        }
                    };
                    startUpdater.Start();
                    // TODO we should wait and check if we have restarted NiceHash Miner
                }

                // shutdown
                Shutdown();
                return;
            }
            if (isUpdated)
            {
                await Task.Delay(500);             // so we release the temp files
            }
            await WindowsUptimeCheck.DelayUptime();

            bool createdNew = false;
            try
            {
                string appPath = GetHashString();
                _mutex = new Mutex(true, appPath, out createdNew);
                if (!createdNew)
                {
                    //MessageBox.Show("We have detected you are already running NiceHash Miner. Only a single instance should be running at a time.", "NiceHash Miner Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    // shutdown
                    Shutdown();
                    return;
                }

                ClearAllTmpFiles();

                // TODO pass parent process PID
                var(latestAppDir, latestAppExe, version) = GetLatestApp();
#if DELETE_NON_CURRENT_APPS
#error "Comment this line if you really wish to execute apps cleanup"
                DeleteAllExceptCurrentVersion(version); // cleanup on next release
#endif
                var nhmApp = GetRootPath(latestAppDir, latestAppExe);
                var args   = $"-lc -PID{Process.GetCurrentProcess().Id}";
                if (isUpdated)
                {
                    afterUpdate = true;
                    args       += " -updated";
                }
                var startInfo = new ProcessStartInfo
                {
                    FileName    = nhmApp,
                    Arguments   = args,
                    WindowStyle = ProcessWindowStyle.Normal
                };
                var       run                     = true;
                const int maxRestartCount         = 3;
                int       restartCount            = 0;
                const int minRestartTimeInSeconds = 30;
                while (run)
                {
                    var startTime = DateTime.UtcNow;
                    run = false;
                    try
                    {
                        using (var niceHashMiner = new Process {
                            StartInfo = startInfo
                        })
                        {
                            var hasStarted = niceHashMiner?.Start();
                            niceHashMiner?.WaitForExit();
                            if (afterUpdate == true)
                            {
                                afterUpdate         = false;
                                startInfo.Arguments = startInfo.Arguments.Replace("-updated", "");
                            }


                            // TODO
                            Console.WriteLine(niceHashMiner.ExitCode);
                            //in case of crash try to restart the program
                            if (niceHashMiner.ExitCode != 0)
                            {
                                var endTime = DateTime.UtcNow;

                                string path = GetRootPath("logs", "watchdogLog.txt");
                                if (!File.Exists(path))
                                {
                                    using (var sw = File.CreateText(path))
                                    {
                                        sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}");
                                    }
                                }
                                else
                                {
                                    using (var sw = File.AppendText(path))
                                    {
                                        sw.WriteLine($"Exit code: {niceHashMiner.ExitCode} ---- {endTime}");
                                    }
                                }
                                //try to re-run the NHM
                                run = true;

                                //check if too many restarts
                                var elapsedSeconds = (endTime - startTime).TotalSeconds;
                                if (elapsedSeconds < minRestartTimeInSeconds)
                                {
                                    restartCount++;
                                }
                                else
                                {
                                    restartCount = 0;
                                }
                                if (restartCount >= maxRestartCount)
                                {
                                    using (var sw = File.AppendText(path))
                                    {
                                        sw.WriteLine($"Too many restarts! Closing nhm");
                                    }
                                    MessageBox.Show("NHM experienced too many crashes recently, therefore it will close itself", "Too many restarts");
                                    run = false;
                                }
                            }
                            else
                            {
                                // if exit code is 0 then check runasadmin or restart
                                if (IsRunAsAdmin())
                                {
                                    RunAsAdmin.SelfElevate();
                                }
                                else if (IsRestart())
                                {
                                    ClearAllDoFiles();
                                    run = true;
                                }
                                else if (IsUpdate())
                                {
                                    run = true; // mark to false if updating doesn't fail
                                    ClearAllDoFiles();
                                    var exePath     = Assembly.GetExecutingAssembly().Location;
                                    var randomPart  = DateTime.UtcNow.Millisecond;
                                    var tmpLauncher = GetRootPath($"tmp.nhm_updater_{randomPart}.exe");
                                    File.Copy(exePath, tmpLauncher, true);
                                    var doUpdate = new Process
                                    {
                                        StartInfo = new ProcessStartInfo
                                        {
                                            FileName    = tmpLauncher,
                                            Arguments   = "-update",
                                            WindowStyle = ProcessWindowStyle.Normal
                                        }
                                    };
                                    afterUpdate = true;
                                    var updateStarted = doUpdate.Start();
                                    run = !updateStarted; // set if we are good
                                }
                                else /*ELSE*/ } {
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            // shutdown
            Shutdown();
            return;
        }
        finally
        {
            if (createdNew)
            {
                _mutex?.ReleaseMutex();
            }
        }
    }