GetText() 공개 정적인 메소드

public static GetText ( string token ) : string
token string
리턴 string
예제 #1
0
        private StartMiningReturnType StartMining(bool showWarnings)
        {
            if (textBoxBTCAddress.Text.Equals(""))
            {
                if (showWarnings)
                {
                    var result = MessageBox.Show(International.GetText("Form_Main_DemoModeMsg"),
                                                 International.GetText("Form_Main_DemoModeTitle"),
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == DialogResult.Yes)
                    {
                        _demoMode             = true;
                        labelDemoMode.Visible = true;
                        labelDemoMode.Text    = International.GetText("Form_Main_DemoModeLabel");
                    }
                    else
                    {
                        return(StartMiningReturnType.IgnoreMsg);
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }
            else if (!VerifyMiningAddress(true))
            {
                return(StartMiningReturnType.IgnoreMsg);
            }

            var hasData = NHSmaData.HasData;

            if (!showWarnings)
            {
                for (var i = 0; i < 10; i++)
                {
                    if (hasData)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    hasData = NHSmaData.HasData;
                    Helpers.ConsolePrint("NICEHASH", $"After {i}s has data: {hasData}");
                }
            }

            if (!hasData)
            {
                Helpers.ConsolePrint("NICEHASH", "No data received within timeout");
                if (showWarnings)
                {
                    MessageBox.Show(International.GetText("Form_Main_msgbox_NullNiceHashDataMsg"),
                                    International.GetText("Error_with_Exclamation"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(StartMiningReturnType.IgnoreMsg);
            }


            // Check if there are unbenchmakred algorithms
            var isBenchInit = true;

            foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
            {
                if (cdev.Enabled)
                {
                    if (cdev.GetAlgorithmSettings().Where(algo => algo.Enabled).Any(algo => algo.BenchmarkSpeed == 0))
                    {
                        isBenchInit = false;
                    }
                }
            }
            // Check if the user has run benchmark first
            if (!isBenchInit)
            {
                var result = DialogResult.No;
                if (showWarnings)
                {
                    result = MessageBox.Show(International.GetText("EnabledUnbenchmarkedAlgorithmsWarning"),
                                             International.GetText("Warning_with_Exclamation"),
                                             MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                }
                if (result == DialogResult.Yes)
                {
                    _benchmarkForm = new Form_Benchmark(
                        BenchmarkPerformanceType.Standard,
                        true);
                    SetChildFormCenter(_benchmarkForm);
                    _benchmarkForm.ShowDialog();
                    _benchmarkForm = null;
                    InitMainConfigGuiData();
                }
                else if (result == DialogResult.No)
                {
                    // check devices without benchmarks
                    foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
                    {
                        if (cdev.Enabled)
                        {
                            var enabled = cdev.GetAlgorithmSettings().Any(algo => algo.BenchmarkSpeed > 0);
                            cdev.Enabled = enabled;
                        }
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }

            textBoxBTCAddress.Enabled = false;
            textBoxWorkerName.Enabled = false;
            comboBoxLocation.Enabled  = false;
            buttonBenchmark.Enabled   = false;
            buttonStartMining.Enabled = false;
            buttonSettings.Enabled    = false;
            devicesListViewEnableControl1.IsMining = true;
            buttonStopMining.Enabled = true;

            // Disable profitable notification on start
            _isNotProfitable = false;

            ConfigManager.GeneralConfig.BitcoinAddress  = textBoxBTCAddress.Text.Trim();
            ConfigManager.GeneralConfig.WorkerName      = textBoxWorkerName.Text.Trim();
            ConfigManager.GeneralConfig.ServiceLocation = comboBoxLocation.SelectedIndex;

            InitFlowPanelStart();
            ClearRatesAll();

            var btcAdress = _demoMode ? Globals.DemoUser : textBoxBTCAddress.Text.Trim();
            var isMining  = MinersManager.StartInitialize(this, Globals.MiningLocation[comboBoxLocation.SelectedIndex],
                                                          textBoxWorkerName.Text.Trim(), btcAdress);

            if (!_demoMode)
            {
                ConfigManager.GeneralConfigFileCommit();
            }

            //_isSmaUpdated = true; // Always check profits on mining start
            //_smaMinerCheck.Interval = 100;
            //_smaMinerCheck.Start();
            _minerStatsCheck.Start();

            if (ConfigManager.GeneralConfig.RunScriptOnCUDA_GPU_Lost)
            {
                _computeDevicesCheckTimer          = new SystemTimer();
                _computeDevicesCheckTimer.Elapsed += ComputeDevicesCheckTimer_Tick;
                _computeDevicesCheckTimer.Interval = 60000;

                _computeDevicesCheckTimer.Start();
            }

            return(isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining);
        }
예제 #2
0
 protected virtual string GetFinalBenchmarkString()
 {
     return(BenchmarkSignalTimedout ? International.GetText("Benchmark_Timedout") : International.GetText("Benchmark_Terminated"));
 }
예제 #3
0
 public void SetBenchmarkPending()
 {
     IsBenchmarkPending = true;
     BenchmarkStatus    = International.GetText("Algorithm_Waiting_Benchmark");
 }
예제 #4
0
        private StartMiningReturnType StartMining(bool showWarnings)
        {
            if (textBoxBTCAddress.Text.Equals(""))
            {
                if (showWarnings)
                {
                    DialogResult result = MessageBox.Show(International.GetText("Form_Main_DemoModeMsg"),
                                                          International.GetText("Form_Main_DemoModeTitle"),
                                                          MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        DemoMode = true;
                        labelDemoMode.Visible = true;
                        labelDemoMode.Text    = International.GetText("Form_Main_DemoModeLabel");
                    }
                    else
                    {
                        return(StartMiningReturnType.IgnoreMsg);
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);;
                }
            }
            else if (!VerifyMiningAddress(true))
            {
                return(StartMiningReturnType.IgnoreMsg);
            }

            if (Globals.NiceHashData == null)
            {
                if (showWarnings)
                {
                    MessageBox.Show(International.GetText("Form_Main_msgbox_NullNiceHashDataMsg"),
                                    International.GetText("Error_with_Exclamation"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(StartMiningReturnType.IgnoreMsg);
            }


            // Check if there are unbenchmakred algorithms
            bool isBenchInit       = true;
            bool hasAnyAlgoEnabled = false;

            foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
            {
                if (cdev.Enabled)
                {
                    foreach (var algo in cdev.GetAlgorithmSettings())
                    {
                        if (algo.Enabled == true)
                        {
                            hasAnyAlgoEnabled = true;
                            if (algo.BenchmarkSpeed == 0)
                            {
                                isBenchInit = false;
                                break;
                            }
                        }
                    }
                }
            }
            // Check if the user has run benchmark first
            if (!isBenchInit)
            {
                DialogResult result = MessageBox.Show(International.GetText("EnabledUnbenchmarkedAlgorithmsWarning"),
                                                      International.GetText("Warning_with_Exclamation"),
                                                      MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    BenchmarkForm = new Form_Benchmark(
                        BenchmarkPerformanceType.Standard,
                        true);
                    SetChildFormCenter(BenchmarkForm);
                    BenchmarkForm.ShowDialog();
                    BenchmarkForm = null;
                    InitMainConfigGUIData();
                }
                else if (result == System.Windows.Forms.DialogResult.No)
                {
                    // check devices without benchmarks
                    foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
                    {
                        if (cdev.Enabled)
                        {
                            bool Enabled = false;
                            foreach (var algo in cdev.GetAlgorithmSettings())
                            {
                                if (algo.BenchmarkSpeed > 0)
                                {
                                    Enabled = true;
                                    break;
                                }
                            }
                            cdev.Enabled = Enabled;
                        }
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }

            textBoxBTCAddress.Enabled = false;
            textBoxWorkerName.Enabled = false;
            comboBoxLocation.Enabled  = false;
            buttonBenchmark.Enabled   = false;
            buttonStartMining.Enabled = false;
            buttonSettings.Enabled    = false;
            devicesListViewEnableControl1.IsMining = true;
            buttonStopMining.Enabled = true;

            ConfigManager.GeneralConfig.BitcoinAddress  = textBoxBTCAddress.Text.Trim();
            ConfigManager.GeneralConfig.WorkerName      = textBoxWorkerName.Text.Trim();
            ConfigManager.GeneralConfig.ServiceLocation = comboBoxLocation.SelectedIndex;

            InitFlowPanelStart();
            ClearRatesALL();

            var btcAdress = DemoMode ? Globals.DemoUser : textBoxBTCAddress.Text.Trim();
            var isMining  = MinersManager.StartInitialize(this, Globals.MiningLocation[comboBoxLocation.SelectedIndex], textBoxWorkerName.Text.Trim(), btcAdress);

            if (!DemoMode)
            {
                ConfigManager.GeneralConfigFileCommit();
            }

            isSMAUpdated           = true; // Always check profits on mining start
            SMAMinerCheck.Interval = 100;
            SMAMinerCheck.Start();
            MinerStatsCheck.Start();

            return(isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining);
        }
예제 #5
0
        virtual protected void BenchmarkThreadRoutine(object CommandLine)
        {
            Thread.Sleep(ConfigManager.GeneralConfig.MinerRestartDelayMS);

            BenchmarkSignalQuit      = false;
            BenchmarkSignalHanged    = false;
            BenchmarkSignalFinnished = false;
            BenchmarkException       = null;

            try {
                Helpers.ConsolePrint("BENCHMARK", "Benchmark starts");
                BenchmarkHandle = BenchmarkStartProcess((string)CommandLine);

                BenchmarkThreadRoutineStartSettup();
                // wait a little longer then the benchmark routine if exit false throw
                //var timeoutTime = BenchmarkTimeoutInSeconds(BenchmarkTimeInSeconds);
                //var exitSucces = BenchmarkHandle.WaitForExit(timeoutTime * 1000);
                // don't use wait for it breaks everything
                BenchmarkProcessStatus = BenchmarkProcessStatus.Running;
                BenchmarkHandle.WaitForExit();
                if (BenchmarkSignalTimedout)
                {
                    throw new Exception("Benchmark timedout");
                }
                if (BenchmarkException != null)
                {
                    throw BenchmarkException;
                }
                if (BenchmarkSignalQuit)
                {
                    throw new Exception("Termined by user request");
                }
                if (BenchmarkSignalHanged)
                {
                    throw new Exception("SGMiner is not responding");
                }
                if (BenchmarkSignalFinnished)
                {
                    //break;
                }
            } catch (Exception ex) {
                BenchmarkAlgorithm.BenchmarkSpeed = 0;

                Helpers.ConsolePrint(MinerTAG(), "Benchmark Exception: " + ex.Message);
                if (BenchmarkComunicator != null && !OnBenchmarkCompleteCalled)
                {
                    OnBenchmarkCompleteCalled = true;
                    BenchmarkComunicator.OnBenchmarkComplete(false, BenchmarkSignalTimedout ? International.GetText("Benchmark_Timedout") : International.GetText("Benchmark_Terminated"));
                }
            } finally {
                BenchmarkProcessStatus = BenchmarkProcessStatus.Success;
                Helpers.ConsolePrint("BENCHMARK", "Final Speed: " + Helpers.FormatSpeedOutput(BenchmarkAlgorithm.BenchmarkSpeed));
                Helpers.ConsolePrint("BENCHMARK", "Benchmark ends");
                if (BenchmarkComunicator != null && !OnBenchmarkCompleteCalled)
                {
                    OnBenchmarkCompleteCalled = true;
                    BenchmarkComunicator.OnBenchmarkComplete(true, "Success");
                }
            }
        }
예제 #6
0
        private void InitMainConfigGUIData()
        {
            if (ConfigManager.GeneralConfig.ServiceLocation >= 0 && ConfigManager.GeneralConfig.ServiceLocation < Globals.MiningLocation.Length)
            {
                comboBoxLocation.SelectedIndex = ConfigManager.GeneralConfig.ServiceLocation;
            }
            else
            {
                comboBoxLocation.SelectedIndex = 0;
            }

            textBoxBTCAddress.Text  = ConfigManager.GeneralConfig.BitcoinAddress;
            textBoxWorkerName.Text  = ConfigManager.GeneralConfig.WorkerName;
            ShowWarningNiceHashData = true;
            DemoMode = false;

            // init active display currency after config load
            ExchangeRateAPI.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

            toolStripStatusLabelBalanceDollarValue.Text = "(" + ExchangeRateAPI.ActiveDisplayCurrency + ")";
            toolStripStatusLabelBalanceText.Text        = (ExchangeRateAPI.ActiveDisplayCurrency + "/") + International.GetText("Day") + "     " + International.GetText("Form_Main_balance") + ":";
            BalanceCallback(null, null); // update currency changes

            if (_isDeviceDetectionInitialized)
            {
                devicesListViewEnableControl1.ResetComputeDevices(ComputeDeviceManager.Avaliable.AllAvaliableDevices);
            }
        }
예제 #7
0
        public void AddRateInfo(string groupName, string deviceStringInfo, APIData iAPIData, double paying, bool isApiGetException)
        {
            string ApiGetExceptionString = isApiGetException ? "**" : "";

            string speedString = Helpers.FormatDualSpeedOutput(iAPIData.Speed, iAPIData.SecondarySpeed) + iAPIData.AlgorithmName + ApiGetExceptionString;

            if (iAPIData.AlgorithmID == AlgorithmType.Equihash)
            {
                speedString = speedString.Replace("H/s", "Sols/s");
            }

            string rateBTCString      = FormatPayingOutput(paying);
            string rateCurrencyString = ExchangeRateAPI.ConvertToActiveCurrency(paying * Globals.BitcoinUSDRate).ToString("F2", CultureInfo.InvariantCulture)
                                        + String.Format(" {0}/", ExchangeRateAPI.ActiveDisplayCurrency) + International.GetText("Day");

            ((GroupProfitControl)flowLayoutPanelRates.Controls[flowLayoutPanelRatesIndex++])
            .UpdateProfitStats(groupName, deviceStringInfo, speedString, rateBTCString, rateCurrencyString);

            UpdateGlobalRate();
        }
예제 #8
0
        private void InitiateBenchmark()
        {
            int algoIndex = index;

            index++;

            if (algoIndex < mm.SupportedAlgorithms.Length)
            {
                if (!mm.SupportedAlgorithms[algoIndex].Skip)
                {
                    if (mm is cpuminer)
                    {
                        Time = Config.ConfigData.BenchmarkTimeLimitsCPU[TimeIndex];
                    }
                    else if (mm is ccminer)
                    {
                        Time = Config.ConfigData.BenchmarkTimeLimitsNVIDIA[TimeIndex];
                    }
                    else
                    {
                        Time = Config.ConfigData.BenchmarkTimeLimitsAMD[TimeIndex] / 60;

                        // add an aditional minute if second is not 0
                        if (DateTime.Now.Second != 0)
                        {
                            Time += 1;
                        }
                    }

                    CurrentAlgoName = mm.SupportedAlgorithms[algoIndex].NiceHashName;
                    UpdateProgressBar(false);
                    mm.BenchmarkStart(algoIndex, Time, BenchmarkCompleted, DevicesListView.Items[DeviceChecked_Index].Tag);
                }
                else
                {
                    UpdateProgressBar(true);
                    InitiateBenchmark();
                }
            }
            else
            {
                for (int i = 0; i < mm.SupportedAlgorithms.Length; i++)
                {
                    if (!mm.SupportedAlgorithms[i].Skip)
                    {
                        int id = mm.SupportedAlgorithms[i].NiceHashID;
                        url += "&speed" + id + "=" + (mm.SupportedAlgorithms[i].BenchmarkSpeed / div[id]).ToString("F2", System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                InBenchmark                  = false;
                DevicesListView.Enabled      = true;
                CloseBtn.Enabled             = true;
                StartStopBtn.Text            = International.GetText("SubmitResultDialog_StartBtn");
                BenchmarkProgressBar.Value   = 0;
                LabelProgressPercentage.Text = International.GetText("SubmitResultDialog_LabelProgressPercentageCompleted");

                if (mm.BenchmarkSignalQuit)
                {
                    LabelProgressPercentage.Text = International.GetText("SubmitResultDialog_LabelProgressPercentageStopped");
                    return;
                }

                url += "&nhmver=" + Application.ProductVersion.ToString(); // Add version info
                url += "&cost=1&power=1";                                  // Set default power and cost to 1
                System.Diagnostics.Process.Start(url);
            }
        }
예제 #9
0
        private void BenchmarkBtn_Click(object sender, EventArgs e)
        {
            if (InBenchmark)
            {
                mm.BenchmarkSignalQuit = true;
                InBenchmark            = false;
                index = 9999;
                return;
            }

            bool   DeviceChecked = false;
            string DeviceName    = "";

            for (int i = 0; i < DevicesListView.Items.Count; i++)
            {
                if (DevicesListView.Items[i].Selected)
                {
                    DeviceChecked = true;
                    Int32.TryParse(DevicesListView.Items[i].SubItems[2].Text, out DeviceChecked_Index);

                    mm         = DevicesListView.Items[i].Tag as Miner;
                    DeviceName = DevicesListView.Items[i].SubItems[1].Text;
                }
            }

            if (!DeviceChecked)
            {
                MessageBox.Show(International.GetText("SubmitResultDialog_NoDeviceCheckedMsg"),
                                International.GetText("SubmitResultDialog_NoDeviceCheckedTitle"),
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            InBenchmark                  = true;
            DevicesListView.Enabled      = false;
            CloseBtn.Enabled             = false;
            StartStopBtn.Text            = International.GetText("SubmitResultDialog_StopBtn");
            LabelProgressPercentage.Text = "0.00%";
            index = 0;

            Helpers.ConsolePrint("SubmitResultDialog", "Number of Devices: " + mm.CDevs.Count);
            if (mm.CDevs.Count == 1 && mm.CountBenchmarkedAlgos() != 0)
            {
                DialogResult result = MessageBox.Show(International.GetText("SubmitResultDialog_UsePreviousBenchmarkedValueMsg"),
                                                      International.GetText("SubmitResultDialog_UsePreviousBenchmarkedValueTitle"),
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    index = 9999;
                }
            }

            // Temporarily disable the other ComputeDevices in the same Group
            for (int i = 0; i < mm.CDevs.Count; i++)
            {
                if (mm.CDevs[i].ID != DeviceChecked_Index)
                {
                    mm.CDevs[i].Enabled = false;
                }
                else
                {
                    mm.CDevs[i].Enabled = true;
                }
            }

            BenchmarkProgressBar.Maximum = mm.SupportedAlgorithms.Length;

            // Parse GPU name
            Helpers.ConsolePrint("SubmitResultDialog", "Old DeviceName: " + DeviceName);
            if (DeviceName.Contains("GeForce") || DeviceName.Contains("GTX") || DeviceName.Contains("GT"))
            {
                string [] DeviceNameSplit = DeviceName.Split(' ');

                for (int i = 0; i < DeviceNameSplit.Length; i++)
                {
                    Helpers.ConsolePrint("DEBUG", "DeviceNameSplit[" + i + "]: " + DeviceNameSplit[i]);

                    if (DeviceNameSplit[i].Equals("GT") || DeviceNameSplit[i].Equals("GTX"))
                    {
                        if ((i + 2) <= DeviceNameSplit.Length)
                        {
                            DeviceName = "NVIDIA " + DeviceNameSplit[i] + DeviceNameSplit[i + 1];
                            for (int j = i + 2; j < DeviceNameSplit.Length; j++)
                            {
                                DeviceName += " " + DeviceNameSplit[j];
                            }

                            break;
                        }
                    }
                }
            }
            Helpers.ConsolePrint("SubmitResultDialog", "New DeviceName: " + DeviceName);

            url = "https://www.nicehash.com/?p=calc&name=" + DeviceName;
            InitiateBenchmark();
        }
예제 #10
0
        public MinerFileNotFoundDialog(string MinerDeviceName, string Path)
        {
            InitializeComponent();

            DisableDetection            = false;
            this.Text                   = International.GetText("MinerFileNotFoundDialog_title");
            linkLabelError.Text         = String.Format(International.GetText("MinerFileNotFoundDialog_linkLabelError"), MinerDeviceName, Path, International.GetText("MinerFileNotFoundDialog_link"));
            linkLabelError.LinkArea     = new LinkArea(this.linkLabelError.Text.IndexOf(International.GetText("MinerFileNotFoundDialog_link")), International.GetText("MinerFileNotFoundDialog_link").Length);
            chkBoxDisableDetection.Text = International.GetText("MinerFileNotFoundDialog_chkBoxDisableDetection");
            buttonOK.Text               = International.GetText("Global_OK");
        }
예제 #11
0
        static void Main(string[] argv)
        {
            // log unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionLogger);
            Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionLogger);

            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

                if (!pathSet)
                {
                    Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
                }

                /* Preset language to RU and icence aggreement */
                ConfigManager.InitializeConfig();
                ConfigManager.GeneralConfig.agreedWithTOS = Globals.CurrentTosVer;
                ConfigManager.GeneralConfig.SetDefaults();
                ConfigManager.GeneralConfigFileCommit();
                ConfigManager.HideTrayIcon         = commandLineArgs.hideTrayIcon;
                ConfigManager.HideEmail            = commandLineArgs.hideEmail;
                ConfigManager.TestDriverUpdateForm = commandLineArgs.testDriverUpdateForm;


                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }


                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                if (ConfigManager.GeneralConfig.Account == null || ConfigManager.GeneralConfig.WorkerName == "")
                {
                    Application.Run(new Form_Authorization());
                }
                else
                {
                    WebAPI.UpdateMachineInfo(ConfigManager.GeneralConfig.WorkerName);
                }

                // check WMI
                if (ConfigManager.GeneralConfig.Account != null)
                {
                    if (Helpers.IsWmiEnabled())
                    {
                        if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                        {
                            while (true)
                            {
                                Application.Run(new Form_Main());
                                if (ConfigManager.GeneralConfig.Account == null)
                                {
                                    Application.Run(new Form_Authorization());
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                        International.GetText("Program_WMI_Error_Title"),
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Вы должны сначала авторизоваться в системе!", "Ошибка",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #12
0
        ///////////////////////////////////////
        // Miner control functions
        private bool StartMining(bool showWarnings)
        {
            if (textBoxBTCAddress.Text.Equals(""))
            {
                if (showWarnings)
                {
                    DialogResult result = MessageBox.Show(International.GetText("Form_Main_DemoModeMsg"),
                                                          International.GetText("Form_Main_DemoModeTitle"),
                                                          MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        DemoMode = true;
                        labelDemoMode.Visible = true;
                        labelDemoMode.Text    = International.GetText("Form_Main_DemoModeLabel");
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else if (!VerifyMiningAddress(true))
            {
                return(false);
            }

            if (Globals.NiceHashData == null)
            {
                if (showWarnings)
                {
                    MessageBox.Show(International.GetText("Form_Main_msgbox_NullNiceHashDataMsg"),
                                    International.GetText("Error_with_Exclamation"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(false);
            }

            //// TODO
            //// first value is a boolean if initialized or not
            //var tuplePair = DeviceBenchmarkConfigManager.Instance.IsEnabledBenchmarksInitialized();
            //bool isBenchInit = tuplePair.Item1;
            //Dictionary<string, List<AlgorithmType>> nonBenchmarkedPerDevice = tuplePair.Item2;
            //// Check if the user has run benchmark first
            //if (!isBenchInit) {
            //    DialogResult result = MessageBox.Show(International.GetText("EnabledUnbenchmarkedAlgorithmsWarning"),
            //                                              International.GetText("Warning_with_Exclamation"),
            //                                              MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
            //    if (result == System.Windows.Forms.DialogResult.Yes) {
            //        List<ComputeDevice> enabledDevices = new List<ComputeDevice>();
            //        HashSet<string> deviceNames = new HashSet<string>();
            //        foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices) {
            //            if (cdev.Enabled && !deviceNames.Contains(cdev.Name)) {
            //                deviceNames.Add(cdev.Name);
            //                enabledDevices.Add(cdev);
            //            }
            //        }
            //        BenchmarkForm = new Form_Benchmark(
            //            BenchmarkPerformanceType.Standard,
            //            true);
            //        SetChildFormCenter(BenchmarkForm);
            //        BenchmarkForm.ShowDialog();
            //        BenchmarkForm = null;
            //        InitMainConfigGUIData();
            //    } else if (result == System.Windows.Forms.DialogResult.No) {
            //        // check devices without benchmarks
            //        foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices) {
            //            bool Enabled = false;
            //            foreach (var algo in cdev.AlgorithmSettings) {
            //                if (algo.Value.BenchmarkSpeed > 0) {
            //                    Enabled = true;
            //                    break;
            //                }
            //            }
            //            cdev.Enabled = Enabled;
            //        }
            //    } else {
            //        return;
            //    }
            //}

            // check if any device enabled
            // check devices without benchmarks
            bool noDeviceEnabled = true;

            foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
            {
                if (cdev.Enabled)
                {
                    noDeviceEnabled = false;
                    break;
                }
            }
            if (noDeviceEnabled)
            {
                if (showWarnings)
                {
                    DialogResult result = MessageBox.Show(International.GetText("Form_Main_No_Device_Enabled_For_Mining"),
                                                          International.GetText("Warning_with_Exclamation"),
                                                          MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                return(false);
            }

            textBoxBTCAddress.Enabled = false;
            textBoxWorkerName.Enabled = false;
            comboBoxLocation.Enabled  = false;
            buttonBenchmark.Enabled   = false;
            buttonStartMining.Enabled = false;
            buttonSettings.Enabled    = false;
            devicesListViewEnableControl1.IsMining = true;
            buttonStopMining.Enabled = true;

            ConfigManager.GeneralConfig.BitcoinAddress  = textBoxBTCAddress.Text.Trim();
            ConfigManager.GeneralConfig.WorkerName      = textBoxWorkerName.Text.Trim();
            ConfigManager.GeneralConfig.ServiceLocation = comboBoxLocation.SelectedIndex;

            InitFlowPanelStart();
            ClearRatesALL();

            var btcAdress = DemoMode ? Globals.DemoUser : textBoxBTCAddress.Text.Trim();
            var isMining  = MinersManager.Instance.StartInitialize(this, Globals.MiningLocation[comboBoxLocation.SelectedIndex], textBoxWorkerName.Text.Trim(), btcAdress);

            if (!DemoMode)
            {
                ConfigManager.GeneralConfigFileCommit();
            }

            SMAMinerCheck.Interval = 100;
            SMAMinerCheck.Start();
            MinerStatsCheck.Start();

            return(isMining);
        }
예제 #13
0
        public void AddRateInfo(string groupName, string deviceStringInfo, APIData iAPIData, double paying, List <String> devNames, bool isApiGetException)
        {
            string ApiGetExceptionString = isApiGetException ? "**" : "";

            string speedString = Helpers.FormatDualSpeedOutput(iAPIData.Speed, iAPIData.SecondarySpeed) + iAPIData.AlgorithmName + ApiGetExceptionString;

            if (iAPIData.AlgorithmID == AlgorithmType.Equihash)
            {
                speedString = speedString.Replace("H/s", "Sols/s");
            }

            string rateBTCString      = FormatPayingOutput(paying);
            string rateCurrencyString = ExchangeRateAPI.ConvertToActiveCurrency(paying * Globals.BitcoinUSDRate).ToString("F2", CultureInfo.InvariantCulture)
                                        + String.Format(" {0}/", ExchangeRateAPI.ActiveDisplayCurrency) + International.GetText("Day");

            ((GroupProfitControl)flowLayoutPanelRates.Controls[flowLayoutPanelRatesIndex++])
            .UpdateProfitStats(groupName, deviceStringInfo, speedString, rateBTCString, rateCurrencyString);

            double Balance = NiceHashStats.GetBalance(textBoxBTCAddress.Text.Trim(), textBoxBTCAddress.Text.Trim() + "." + textBoxWorkerName.Text.Trim());
            Dictionary <string, string> localDevNames = new Dictionary <string, string>();

            localDevNames              = new Dictionary <string, string>();
            localDevNames["Devices"]   = String.Join(",", devNames.ToArray());
            localDevNames["BTCExRate"] = ExchangeRateAPI.ConvertToActiveCurrency(Globals.BitcoinUSDRate).ToString("F2", CultureInfo.InvariantCulture)
                                         + " " + ExchangeRateAPI.ActiveDisplayCurrency;
            localDevNames["BTCBalance"] = (Balance * 1000).ToString("F5", CultureInfo.InvariantCulture);
            bool found = false;
            int  pos   = 0;

            foreach (Dictionary <string, string> foundData in hashData)
            {
                if (foundData.ContainsKey("Devices"))
                {
                    hashData[pos] = localDevNames;
                    found         = true;
                    break;
                }
                pos++;
            }
            if (!found)
            {
                hashData.Add(localDevNames);
            }
            string[] devicesStrings = deviceStringInfo.Trim('{', ' ').Trim(' ', '}').Split(new string[] { ", " }, StringSplitOptions.None);

            Dictionary <string, string> localData = new Dictionary <string, string>();

            localData = new Dictionary <string, string>();
            localData["DeviceInfo"]   = deviceStringInfo;
            localData["Speed"]        = speedString;
            localData["RateBTC"]      = rateBTCString;
            localData["RateCurrency"] = rateCurrencyString;
            localData["GroupName"]    = groupName;
            found = false;
            pos   = 0;
            foreach (Dictionary <string, string> foundData in hashData.ToArray())
            {
                if (foundData.ContainsKey("GroupName"))
                {
                    if (foundData["GroupName"] == groupName)
                    {
                        hashData[pos] = localData;
                        found         = true;
                        break;
                    }
                    else
                    {
                        foreach (string deviceString in devicesStrings)
                        {
                            if (foundData["DeviceInfo"].Contains(deviceString))
                            {
                                hashData.RemoveAt(pos);
                                pos--;
                                break;
                            }
                        }
                    }
                }
                pos++;
            }
            if (!found)
            {
                hashData.Add(localData);
            }

            UpdateGlobalRate();
        }
예제 #14
0
        protected void BenchmarkThreadRoutineCatch(Exception ex)
        {
            BenchmarkAlgorithm.BenchmarkSpeed = 0;

            Helpers.ConsolePrint(MinerTAG(), "Benchmark Exception: " + ex.Message);
            if (BenchmarkComunicator != null && !OnBenchmarkCompleteCalled)
            {
                OnBenchmarkCompleteCalled = true;
                BenchmarkComunicator.OnBenchmarkComplete(false, BenchmarkSignalTimedout ? International.GetText("Benchmark_Timedout") : International.GetText("Benchmark_Terminated"));
            }
        }
예제 #15
0
        // This is a single shot _benchmarkTimer
        private void StartupTimer_Tick(object sender, EventArgs e)
        {
            _startupTimer.Stop();
            _startupTimer = null;

            // Internals Init
            // TODO add loading step
            MinersSettingsManager.Init();

            if (!Helpers.Is45NetOrHigher())
            {
                MessageBox.Show(International.GetText("NET45_Not_Installed_msg"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                Close();
                return;
            }

            if (!Helpers.Is64BitOperatingSystem)
            {
                MessageBox.Show(International.GetText("Form_Main_x64_Support_Only"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                Close();
                return;
            }

            // 3rdparty miners check scope #1
            {
                // check if setting set
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET)
                {
                    // Show TOS
                    Form tos = new Form_3rdParty_TOS();
                    tos.ShowDialog(this);
                }
            }

            // Query Avaliable ComputeDevices
            ComputeDeviceManager.Query.QueryDevices(_loadingScreen);
            _isDeviceDetectionInitialized = true;

            /////////////////////////////////////////////
            /////// from here on we have our devices and Miners initialized
            ConfigManager.AfterDeviceQueryInitialization();
            _loadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SaveConfig"));

            // All devices settup should be initialized in AllDevices
            devicesListViewEnableControl1.ResetComputeDevices(ComputeDeviceManager.Avaliable.AllAvaliableDevices);
            // set properties after
            devicesListViewEnableControl1.SaveToGeneralConfig = true;

            _loadingScreen.IncreaseLoadCounterAndMessage(
                International.GetText("Form_Main_loadtext_CheckLatestVersion"));

            _minerStatsCheck          = new Timer();
            _minerStatsCheck.Tick    += MinerStatsCheck_Tick;
            _minerStatsCheck.Interval = ConfigManager.GeneralConfig.MinerAPIQueryInterval * 1000;

            //_smaMinerCheck = new Timer();
            //_smaMinerCheck.Tick += SMAMinerCheck_Tick;
            //_smaMinerCheck.Interval = ConfigManager.GeneralConfig.SwitchMinSecondsFixed * 1000 +
            //                          R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            //if (ComputeDeviceManager.Group.ContainsAmdGpus)
            //{
            //    _smaMinerCheck.Interval =
            //        (ConfigManager.GeneralConfig.SwitchMinSecondsAMD +
            //         ConfigManager.GeneralConfig.SwitchMinSecondsFixed) * 1000 +
            //        R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            //}

            _loadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetNiceHashSMA"));
            // Init ws connection
            NiceHashStats.OnBalanceUpdate         += BalanceCallback;
            NiceHashStats.OnSmaUpdate             += SmaCallback;
            NiceHashStats.OnVersionUpdate         += VersionUpdateCallback;
            NiceHashStats.OnConnectionLost        += ConnectionLostCallback;
            NiceHashStats.OnConnectionEstablished += ConnectionEstablishedCallback;
            NiceHashStats.OnVersionBurn           += VersionBurnCallback;
            NiceHashStats.OnExchangeUpdate        += ExchangeCallback;
            NiceHashStats.StartConnection(Links.NhmSocketAddress);

            // increase timeout
            if (Globals.IsFirstNetworkCheckTimeout)
            {
                while (!Helpers.WebRequestTestGoogle() && Globals.FirstNetworkCheckTimeoutTries > 0)
                {
                    --Globals.FirstNetworkCheckTimeoutTries;
                }
            }

            _loadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetBTCRate"));

            //// Don't start timer if socket is giving data
            //if (ExchangeRateApi.ExchangesFiat == null)
            //{
            //    // Wait a bit and check again
            //    Thread.Sleep(1000);
            //    if (ExchangeRateApi.ExchangesFiat == null)
            //    {
            //        Helpers.ConsolePrint("NICEHASH", "No exchange from socket yet, getting manually");
            //        _bitcoinExchangeCheck = new Timer();
            //        _bitcoinExchangeCheck.Tick += BitcoinExchangeCheck_Tick;
            //        _bitcoinExchangeCheck.Interval = 1000 * 3601; // every 1 hour and 1 second
            //        _bitcoinExchangeCheck.Start();
            //        BitcoinExchangeCheck_Tick(null, null);
            //    }
            //}

            _loadingScreen.IncreaseLoadCounterAndMessage(
                International.GetText("Form_Main_loadtext_SetEnvironmentVariable"));
            Helpers.SetDefaultEnvironmentVariables();

            _loadingScreen.IncreaseLoadCounterAndMessage(
                International.GetText("Form_Main_loadtext_SetWindowsErrorReporting"));

            Helpers.DisableWindowsErrorReporting(ConfigManager.GeneralConfig.DisableWindowsErrorReporting);

            _loadingScreen.IncreaseLoadCounter();
            if (ConfigManager.GeneralConfig.NVIDIAP0State)
            {
                _loadingScreen.SetInfoMsg(International.GetText("Form_Main_loadtext_NVIDIAP0State"));
                Helpers.SetNvidiaP0State();
            }

            _loadingScreen.FinishLoad();

            var runVCRed = !MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit;

            // standard miners check scope
            {
                // check if download needed
                if (!MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit)
                {
                    var downloadUnzipForm =
                        new Form_Loading(new MinersDownloader(MinersDownloadManager.StandardDlSetup));
                    SetChildFormCenter(downloadUnzipForm);
                    downloadUnzipForm.ShowDialog();
                }
                // check if files are mising
                if (!MinersExistanceChecker.IsMinersBinsInit())
                {
                    var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                 International.GetText("Warning_with_Exclamation"),
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        ConfigManager.GeneralConfig.DownloadInit = false;
                        ConfigManager.GeneralConfigFileCommit();
                        var pHandle = new Process
                        {
                            StartInfo =
                            {
                                FileName = Application.ExecutablePath
                            }
                        };
                        pHandle.Start();
                        Close();
                        return;
                    }
                }
                else if (!ConfigManager.GeneralConfig.DownloadInit)
                {
                    // all good
                    ConfigManager.GeneralConfig.DownloadInit = true;
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            // 3rdparty miners check scope #2
            {
                // check if download needed
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.YES)
                {
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit() &&
                        !ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        var download3rdPartyUnzipForm =
                            new Form_Loading(new MinersDownloader(MinersDownloadManager.ThirdPartyDlSetup));
                        SetChildFormCenter(download3rdPartyUnzipForm);
                        download3rdPartyUnzipForm.ShowDialog();
                    }
                    // check if files are mising
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit())
                    {
                        var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                     International.GetText("Warning_with_Exclamation"),
                                                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            ConfigManager.GeneralConfig.DownloadInit3rdParty = false;
                            ConfigManager.GeneralConfigFileCommit();
                            var pHandle = new Process
                            {
                                StartInfo =
                                {
                                    FileName = Application.ExecutablePath
                                }
                            };
                            pHandle.Start();
                            Close();
                            return;
                        }
                    }
                    else if (!ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        // all good
                        ConfigManager.GeneralConfig.DownloadInit3rdParty = true;
                        ConfigManager.GeneralConfigFileCommit();
                    }
                }
            }

            if (runVCRed)
            {
                Helpers.InstallVcRedist();
            }


            if (ConfigManager.GeneralConfig.AutoStartMining)
            {
                // well this is started manually as we want it to start at runtime
                _isManuallyStarted = true;
                if (StartMining(false) != StartMiningReturnType.StartMining)
                {
                    _isManuallyStarted = false;
                    StopMining();
                }
            }
        }
예제 #16
0
        // This is a single shot _benchmarkTimer
        private void StartupTimer_Tick(object sender, EventArgs e)
        {
            StartupTimer.Stop();
            StartupTimer = null;

            // Internals Init
            // TODO add loading step
            MinersSettingsManager.Init();

            if (!Helpers.Is45NetOrHigher())
            {
                MsgBox.Show(International.GetText("NET45_Not_Installed_msg"),
                            International.GetText("Warning_with_Exclamation"),
                            MessageBoxButtons.OK);

                this.Close();
                return;
            }

            if (!Helpers.Is64BitOperatingSystem)
            {
                MsgBox.Show(International.GetText("Form_Main_x64_Support_Only"),
                            International.GetText("Warning_with_Exclamation"),
                            MessageBoxButtons.OK);

                this.Close();
                return;
            }

            // 3rdparty miners check scope #1
            {
                // check if setting set
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET)
                {
                    // Show TOS
                    Form tos = new Form_3rdParty_TOS();
                    tos.ShowDialog(this);
                }
            }

            // Query Avaliable ComputeDevices
            ComputeDeviceManager.Query.QueryDevices(LoadingScreen);
            _isDeviceDetectionInitialized = true;

            /////////////////////////////////////////////
            /////// from here on we have our devices and Miners initialized
            ConfigManager.AfterDeviceQueryInitialization();
            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SaveConfig"));

            // All devices settup should be initialized in AllDevices
            devicesListViewEnableControl1.ResetComputeDevices(ComputeDeviceManager.Avaliable.AllAvaliableDevices);
            // set properties after
            devicesListViewEnableControl1.SaveToGeneralConfig = true;

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_CheckLatestVersion"));

            MinerStatsCheck          = new Timer();
            MinerStatsCheck.Tick    += MinerStatsCheck_Tick;
            MinerStatsCheck.Interval = ConfigManager.GeneralConfig.MinerAPIQueryInterval * 1000;

            SMAMinerCheck          = new Timer();
            SMAMinerCheck.Tick    += SMAMinerCheck_Tick;
            SMAMinerCheck.Interval = ConfigManager.GeneralConfig.SwitchMinSecondsFixed * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            if (ComputeDeviceManager.Group.ContainsAMD_GPUs)
            {
                SMAMinerCheck.Interval = (ConfigManager.GeneralConfig.SwitchMinSecondsAMD + ConfigManager.GeneralConfig.SwitchMinSecondsFixed) * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetNiceHashSMA"));
            // Init ws connection
            NiceHashStats.OnBalanceUpdate         += BalanceCallback;
            NiceHashStats.OnSMAUpdate             += SMACallback;
            NiceHashStats.OnVersionUpdate         += VersionUpdateCallback;
            NiceHashStats.OnConnectionLost        += ConnectionLostCallback;
            NiceHashStats.OnConnectionEstablished += ConnectionEstablishedCallback;
            NiceHashStats.OnVersionBurn           += VersionBurnCallback;
            NiceHashStats.StartConnection(Links.NHM_Socket_Address);

            // increase timeout
            if (Globals.IsFirstNetworkCheckTimeout)
            {
                while (!Helpers.WebRequestTestGoogle() && Globals.FirstNetworkCheckTimeoutTries > 0)
                {
                    --Globals.FirstNetworkCheckTimeoutTries;
                }
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetBTCRate"));

            BitcoinExchangeCheck          = new Timer();
            BitcoinExchangeCheck.Tick    += BitcoinExchangeCheck_Tick;
            BitcoinExchangeCheck.Interval = 1000 * 3601; // every 1 hour and 1 second
            BitcoinExchangeCheck.Start();
            BitcoinExchangeCheck_Tick(null, null);

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetEnvironmentVariable"));
            Helpers.SetDefaultEnvironmentVariables();

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetWindowsErrorReporting"));

            Helpers.DisableWindowsErrorReporting(ConfigManager.GeneralConfig.DisableWindowsErrorReporting);

            LoadingScreen.IncreaseLoadCounter();
            if (ConfigManager.GeneralConfig.NVIDIAP0State)
            {
                LoadingScreen.SetInfoMsg(International.GetText("Form_Main_loadtext_NVIDIAP0State"));
                Helpers.SetNvidiaP0State();
            }

            LoadingScreen.FinishLoad();

            bool runVCRed = !MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit;

            // standard miners check scope
            {
                // check if download needed
                if (!MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit)
                {
                    Form_Loading downloadUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.StandardDlSetup));
                    SetChildFormCenter(downloadUnzipForm);
                    downloadUnzipForm.ShowDialog();
                }
                // check if files are mising
                if (!MinersExistanceChecker.IsMinersBinsInit())
                {
                    var result = Utils.MsgBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                   International.GetText("Warning_with_Exclamation"),
                                                   MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        ConfigManager.GeneralConfig.DownloadInit = false;
                        ConfigManager.GeneralConfigFileCommit();
                        Process PHandle = new Process();
                        PHandle.StartInfo.FileName = Application.ExecutablePath;
                        PHandle.Start();
                        Close();
                        return;
                    }
                }
                else if (!ConfigManager.GeneralConfig.DownloadInit)
                {
                    // all good
                    ConfigManager.GeneralConfig.DownloadInit = true;
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            // 3rdparty miners check scope #2
            {
                // check if download needed
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.YES)
                {
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit() && !ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        Form_Loading download3rdPartyUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.ThirdPartyDlSetup));
                        SetChildFormCenter(download3rdPartyUnzipForm);
                        download3rdPartyUnzipForm.ShowDialog();
                    }
                    // check if files are mising
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit())
                    {
                        var result = Utils.MsgBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                       International.GetText("Warning_with_Exclamation"),
                                                       MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            ConfigManager.GeneralConfig.DownloadInit3rdParty = false;
                            ConfigManager.GeneralConfigFileCommit();
                            Process PHandle = new Process();
                            PHandle.StartInfo.FileName = Application.ExecutablePath;
                            PHandle.Start();
                            Close();
                            return;
                        }
                    }
                    else if (!ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        // all good
                        ConfigManager.GeneralConfig.DownloadInit3rdParty = true;
                        ConfigManager.GeneralConfigFileCommit();
                    }
                }
            }

            if (runVCRed)
            {
                Helpers.InstallVcRedist();
            }


            if (ConfigManager.GeneralConfig.AutoStartMining)
            {
                Form_AutoStartMining form_Auto = new Form_AutoStartMining();
                SetChildFormCenter(form_Auto);
                form_Auto.ShowDialog(this);
            }
        }
예제 #17
0
        private void InitLocalization()
        {
            MessageBoxManager.Unregister();
            MessageBoxManager.Yes    = International.GetText("Global_Yes");
            MessageBoxManager.No     = International.GetText("Global_No");
            MessageBoxManager.OK     = International.GetText("Global_OK");
            MessageBoxManager.Cancel = International.GetText("Global_Cancel");
            MessageBoxManager.Retry  = International.GetText("Global_Retry");
            MessageBoxManager.Register();

            labelServiceLocation.Text = International.GetText("Service_Location") + ":";
            labelBitcoinAddress.Text  = International.GetText("BitcoinAddress") + ":";
            labelWorkerName.Text      = International.GetText("WorkerName") + ":";

            linkLabelCheckStats.Text      = International.GetText("Form_Main_check_stats");
            linkLabelChooseBTCWallet.Text = International.GetText("Form_Main_choose_bitcoin_wallet");

            toolStripStatusLabelGlobalRateText.Text = International.GetText("Form_Main_global_rate") + ":";
            toolStripStatusLabelBTCDayText.Text     = "BTC/" + International.GetText("Day");
            toolStripStatusLabelBalanceText.Text    = (ExchangeRateAPI.ActiveDisplayCurrency + "/") + International.GetText("Day") + "     " + International.GetText("Form_Main_balance") + ":";

            devicesListViewEnableControl1.InitLocale();

            buttonBenchmark.Text   = International.GetText("Form_Main_benchmark");
            buttonSettings.Text    = International.GetText("Form_Main_settings");
            buttonStartMining.Text = International.GetText("Form_Main_start");
            buttonStopMining.Text  = International.GetText("Form_Main_stop");
            buttonHelp.Text        = International.GetText("Form_Main_help");

            label_NotProfitable.Text = International.GetText("Form_Main_MINING_NOT_PROFITABLE");
            groupBox1.Text           = International.GetText("Form_Main_Group_Device_Rates");
        }
예제 #18
0
        public void AddRateInfo(string groupName, string deviceStringInfo, APIData iAPIData, double paying, bool isApiGetException)
        {
            string ApiGetExceptionString = isApiGetException ? "**" : "";

            string speedString        = Helpers.FormatDualSpeedOutput(iAPIData.AlgorithmID, iAPIData.Speed, iAPIData.SecondarySpeed) + iAPIData.AlgorithmName + ApiGetExceptionString;
            string rateBTCString      = FormatPayingOutput(paying);
            string rateCurrencyString = ExchangeRateAPI.ConvertToActiveCurrency(paying * Globals.BitcoinUSDRate * factorTimeUnit).ToString("F2", CultureInfo.InvariantCulture)
                                        + String.Format(" {0}/", ExchangeRateAPI.ActiveDisplayCurrency) + International.GetText(ConfigManager.GeneralConfig.TimeUnit.ToString());

            try {  // flowLayoutPanelRatesIndex may be OOB, so catch
                ((GroupProfitControl)flowLayoutPanelRates.Controls[flowLayoutPanelRatesIndex++])
                .UpdateProfitStats(groupName, deviceStringInfo, speedString, rateBTCString, rateCurrencyString);
            } catch { }

            UpdateGlobalRate();
        }
예제 #19
0
        // This is a single shot _benchmarkTimer
        private void StartupTimer_Tick(object sender, EventArgs e)
        {
            StartupTimer.Stop();
            StartupTimer = null;

            // Internals Init
            // TODO add loading step
            MinersSettingsManager.Init();

            if (!Helpers.Is45NetOrHigher())
            {
                MessageBox.Show(International.GetText("NET45_Not_Installed_msg"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                this.Close();
                return;
            }

            if (!Helpers.Is64BitOperatingSystem)
            {
                MessageBox.Show(International.GetText("Form_Main_x64_Support_Only"),
                                International.GetText("Warning_with_Exclamation"),
                                MessageBoxButtons.OK);

                this.Close();
                return;
            }

            // 3rdparty miners check scope #1
            {
                // check if setting set
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.NOT_SET)
                {
                    // Show TOS
                    Form tos = new Form_3rdParty_TOS();
                    tos.ShowDialog(this);
                }
            }

            // Query Avaliable ComputeDevices
            ComputeDeviceManager.Query.QueryDevices(LoadingScreen);
            _isDeviceDetectionInitialized = true;

            /////////////////////////////////////////////
            /////// from here on we have our devices and Miners initialized
            ConfigManager.AfterDeviceQueryInitialization();
            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SaveConfig"));

            // All devices settup should be initialized in AllDevices
            devicesListViewEnableControl1.ResetComputeDevices(ComputeDeviceManager.Avaliable.AllAvaliableDevices);
            // set properties after
            devicesListViewEnableControl1.SaveToGeneralConfig = true;

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_CheckLatestVersion"));

            MinerStatsCheck          = new Timer();
            MinerStatsCheck.Tick    += MinerStatsCheck_Tick;
            MinerStatsCheck.Interval = ConfigManager.GeneralConfig.MinerAPIQueryInterval * 1000;

            SMAMinerCheck          = new Timer();
            SMAMinerCheck.Tick    += SMAMinerCheck_Tick;
            SMAMinerCheck.Interval = ConfigManager.GeneralConfig.SwitchMinSecondsFixed * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            if (ComputeDeviceManager.Group.ContainsAMD_GPUs)
            {
                SMAMinerCheck.Interval = (ConfigManager.GeneralConfig.SwitchMinSecondsAMD + ConfigManager.GeneralConfig.SwitchMinSecondsFixed) * 1000 + R.Next(ConfigManager.GeneralConfig.SwitchMinSecondsDynamic * 1000);
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetNiceHashSMA"));
            // Init ws connection
            NiceHashStats.OnBalanceUpdate         += BalanceCallback;
            NiceHashStats.OnSMAUpdate             += SMACallback;
            NiceHashStats.OnVersionUpdate         += VersionUpdateCallback;
            NiceHashStats.OnConnectionLost        += ConnectionLostCallback;
            NiceHashStats.OnConnectionEstablished += ConnectionEstablishedCallback;
            NiceHashStats.OnVersionBurn           += VersionBurnCallback;
            NiceHashStats.StartConnection(Links.NHM_Socket_Address);

            // increase timeout
            if (Globals.IsFirstNetworkCheckTimeout)
            {
                while (!Helpers.WebRequestTestGoogle() && Globals.FirstNetworkCheckTimeoutTries > 0)
                {
                    --Globals.FirstNetworkCheckTimeoutTries;
                }
            }

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_GetBTCRate"));

            BitcoinExchangeCheck          = new Timer();
            BitcoinExchangeCheck.Tick    += BitcoinExchangeCheck_Tick;
            BitcoinExchangeCheck.Interval = 1000 * 3601; // every 1 hour and 1 second
            BitcoinExchangeCheck.Start();
            BitcoinExchangeCheck_Tick(null, null);

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetEnvironmentVariable"));
            Helpers.SetDefaultEnvironmentVariables();

            LoadingScreen.IncreaseLoadCounterAndMessage(International.GetText("Form_Main_loadtext_SetWindowsErrorReporting"));

            Helpers.DisableWindowsErrorReporting(ConfigManager.GeneralConfig.DisableWindowsErrorReporting);

            LoadingScreen.IncreaseLoadCounter();
            if (ConfigManager.GeneralConfig.NVIDIAP0State)
            {
                LoadingScreen.SetInfoMsg(International.GetText("Form_Main_loadtext_NVIDIAP0State"));
                try {
                    ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName        = "nvidiasetp0state.exe";
                    psi.Verb            = "runas";
                    psi.UseShellExecute = true;
                    psi.CreateNoWindow  = true;
                    Process p = Process.Start(psi);
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state returned error code: " + p.ExitCode.ToString());
                    }
                    else
                    {
                        Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state all OK");
                    }
                } catch (Exception ex) {
                    Helpers.ConsolePrint("NICEHASH", "nvidiasetp0state error: " + ex.Message);
                }
            }

            LoadingScreen.FinishLoad();

            bool runVCRed = !MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit;

            // standard miners check scope
            {
                // check if download needed
                if (!MinersExistanceChecker.IsMinersBinsInit() && !ConfigManager.GeneralConfig.DownloadInit)
                {
                    Form_Loading downloadUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.StandardDlSetup));
                    SetChildFormCenter(downloadUnzipForm);
                    downloadUnzipForm.ShowDialog();
                }
                // check if files are mising
                if (!MinersExistanceChecker.IsMinersBinsInit())
                {
                    var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                 International.GetText("Warning_with_Exclamation"),
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        ConfigManager.GeneralConfig.DownloadInit = false;
                        ConfigManager.GeneralConfigFileCommit();
                        Process PHandle = new Process();
                        PHandle.StartInfo.FileName = Application.ExecutablePath;
                        PHandle.Start();
                        Close();
                        return;
                    }
                }
                else if (!ConfigManager.GeneralConfig.DownloadInit)
                {
                    // all good
                    ConfigManager.GeneralConfig.DownloadInit = true;
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            // 3rdparty miners check scope #2
            {
                // check if download needed
                if (ConfigManager.GeneralConfig.Use3rdPartyMiners == Use3rdPartyMiners.YES)
                {
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit() && !ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        Form_Loading download3rdPartyUnzipForm = new Form_Loading(new MinersDownloader(MinersDownloadManager.ThirdPartyDlSetup));
                        SetChildFormCenter(download3rdPartyUnzipForm);
                        download3rdPartyUnzipForm.ShowDialog();
                    }
                    // check if files are mising
                    if (!MinersExistanceChecker.IsMiners3rdPartyBinsInit())
                    {
                        var result = MessageBox.Show(International.GetText("Form_Main_bins_folder_files_missing"),
                                                     International.GetText("Warning_with_Exclamation"),
                                                     MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            ConfigManager.GeneralConfig.DownloadInit3rdParty = false;
                            ConfigManager.GeneralConfigFileCommit();
                            Process PHandle = new Process();
                            PHandle.StartInfo.FileName = Application.ExecutablePath;
                            PHandle.Start();
                            Close();
                            return;
                        }
                    }
                    else if (!ConfigManager.GeneralConfig.DownloadInit3rdParty)
                    {
                        // all good
                        ConfigManager.GeneralConfig.DownloadInit3rdParty = true;
                        ConfigManager.GeneralConfigFileCommit();
                    }
                }
            }

            if (runVCRed)
            {
                Helpers.InstallVcRedist();
            }

            // no bots please
            if (ConfigManager.GeneralConfigHwidLoadFromFile() && !ConfigManager.GeneralConfigHwidOK())
            {
                var result = MessageBox.Show("NiceHash Miner Legacy has detected change of hardware ID. If you did not download and install NiceHash Miner Legacy, your computer may be compromised. In that case, we suggest you to install an antivirus program or reinstall your Windows.\r\n\r\nContinue with NiceHash Miner Legacy?",
                                             //International.GetText("Form_Main_msgbox_anti_botnet_msgbox"),
                                             International.GetText("Warning_with_Exclamation"),
                                             MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == System.Windows.Forms.DialogResult.No)
                {
                    Close();
                    return;
                }
                else
                {
                    // users agrees he installed it so commit changes
                    ConfigManager.GeneralConfigFileCommit();
                }
            }
            else
            {
                if (ConfigManager.GeneralConfig.AutoStartMining)
                {
                    // well this is started manually as we want it to start at runtime
                    IsManuallyStarted = true;
                    if (StartMining(true) != StartMiningReturnType.StartMining)
                    {
                        IsManuallyStarted = false;
                        StopMining();
                    }
                }
            }
        }
예제 #20
0
        private void UpdateGlobalRate()
        {
            double TotalRate = MinersManager.GetTotalRate();

            if (ConfigManager.GeneralConfig.AutoScaleBTCValues && TotalRate < 0.1)
            {
                toolStripStatusLabelBTCDayText.Text      = "mBTC/" + International.GetText(ConfigManager.GeneralConfig.TimeUnit.ToString());
                toolStripStatusLabelGlobalRateValue.Text = (TotalRate * 1000 * factorTimeUnit).ToString("F5", CultureInfo.InvariantCulture);
            }
            else
            {
                toolStripStatusLabelBTCDayText.Text      = "BTC/" + International.GetText(ConfigManager.GeneralConfig.TimeUnit.ToString());
                toolStripStatusLabelGlobalRateValue.Text = (TotalRate * factorTimeUnit).ToString("F6", CultureInfo.InvariantCulture);
            }

            toolStripStatusLabelBTCDayValue.Text = ExchangeRateAPI.ConvertToActiveCurrency((TotalRate * factorTimeUnit * Globals.BitcoinUSDRate)).ToString("F2", CultureInfo.InvariantCulture);
            toolStripStatusLabelBalanceText.Text = (ExchangeRateAPI.ActiveDisplayCurrency + "/") + International.GetText(ConfigManager.GeneralConfig.TimeUnit.ToString()) + "     " + International.GetText("Form_Main_balance") + ":";
        }
예제 #21
0
        private string FormatPayingOutput(double paying)
        {
            string ret = "";

            if (ConfigManager.GeneralConfig.AutoScaleBTCValues && paying < 0.1)
            {
                ret = (paying * 1000).ToString("F5", CultureInfo.InvariantCulture) + " mBTC/" + International.GetText("Day");
            }
            else
            {
                ret = paying.ToString("F6", CultureInfo.InvariantCulture) + " BTC/" + International.GetText("Day");
            }

            return(ret);
        }
예제 #22
0
        private void InitiateBenchmark()
        {
            if (listView1.Items.Count > index)
            {
                ListViewItem lvi = listView1.Items[index];
                index++;

                if (!lvi.Checked)
                {
                    InitiateBenchmark();
                    return;
                }

                Miner m = lvi.Tag as Miner;
                int   i = (int)lvi.SubItems[2].Tag;
                //lvi.SubItems[3].Text = "Please wait...";
                inBenchmark           = true;
                CurrentlyBenchmarking = m;

                if (m is cpuminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsCPU[TimeIndex];
                    lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitSeconds"), Time);
                }
                else if (m is ccminer)
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsNVIDIA[TimeIndex];

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = International.GetText("form2_listView_WaitForEth");
                    }
                    else
                    {
                        lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitSeconds"), Time);
                    }
                }
                else
                {
                    Time = Config.ConfigData.BenchmarkTimeLimitsAMD[TimeIndex] / 60;

                    // add an aditional minute if second is not 0
                    if (DateTime.Now.Second != 0)
                    {
                        Time += 1;
                    }

                    if (lvi.SubItems[2].Text.Equals("daggerhashimoto"))
                    {
                        lvi.SubItems[3].Text = International.GetText("form2_listView_WaitForEth");
                    }
                    else
                    {
                        lvi.SubItems[3].Text = String.Format(International.GetText("form2_listView_WaitMinutes"), Time);
                    }
                }

                m.BenchmarkStart(i, Time, BenchmarkCompleted, lvi);
            }
            else
            {
                // average all cpu benchmarks
                if (Form1.Miners[0] is cpuminer)
                {
                    Helpers.ConsolePrint("BENCHMARK", "Calculating average CPU speeds:");

                    double[] Speeds = new double[Form1.Miners[0].SupportedAlgorithms.Length];
                    int[]    MTaken = new int[Form1.Miners[0].SupportedAlgorithms.Length];

                    foreach (ListViewItem lvi in listView1.Items)
                    {
                        if (lvi.Tag is cpuminer)
                        {
                            Miner m = lvi.Tag as Miner;
                            int   i = (int)lvi.SubItems[2].Tag;
                            if (m.SupportedAlgorithms[i].BenchmarkSpeed > 0)
                            {
                                Speeds[i] += m.SupportedAlgorithms[i].BenchmarkSpeed;
                                MTaken[i]++;
                            }
                        }
                    }

                    for (int i = 0; i < Speeds.Length; i++)
                    {
                        if (MTaken[i] > 0)
                        {
                            Speeds[i] /= MTaken[i];
                        }
                        Helpers.ConsolePrint("BENCHMARK", Form1.Miners[0].SupportedAlgorithms[i].NiceHashName + " average speed: " + Form1.Miners[0].PrintSpeed(Speeds[i]));

                        foreach (Miner m in Form1.Miners)
                        {
                            if (m is cpuminer)
                            {
                                m.SupportedAlgorithms[i].BenchmarkSpeed = Speeds[i];
                            }
                        }
                    }
                }

                foreach (ListViewItem lvi in listView1.Items)
                {
                    Miner m = lvi.Tag as Miner;
                    int   i = (int)lvi.SubItems[2].Tag;
                    lvi.SubItems[3].Text = m.PrintSpeed(m.SupportedAlgorithms[i].BenchmarkSpeed);
                }

                Config.RebuildGroups();

                buttonStartBenchmark.Enabled     = true;
                buttonStopBenchmark.Enabled      = false;
                buttonReset.Enabled              = true;
                buttonClose.Enabled              = true;
                buttonCheckProfitability.Enabled = true;
                buttonSubmitHardware.Enabled     = true;
            }
        }
예제 #23
0
        static void Main(string[] argv)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            bool startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try {
                    Process current = Process.GetCurrentProcess();
                    foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                } catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    Helpers.AllocConsole();
                }

                // init active display currency after config load
                ExchangeRateAPI.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);
                bool tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CURRENT_TOS_VER;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "No config file found. Running NiceHash Miner for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }

                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                // check WMI
                if (Helpers.IsWMIEnabled())
                {
                    if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CURRENT_TOS_VER)
                    {
                        Application.Run(new Form_Main());
                    }
                }
                else
                {
                    MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                    International.GetText("Program_WMI_Error_Title"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #24
0
        static void Main(string[] argv)
        {
            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }
                //**
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 4)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("internals\\MinerOptionPackage_glg.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_glg.json");
                    }

                    if (File.Exists("internals\\MinerOptionPackage_ClaymoreDual.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_ClaymoreDual.json");
                    }

                    if (File.Exists("bin\\ccminer_klaust\\ccminer.exe"))
                    {
                        File.Delete("bin\\ccminer_klaust\\ccminer.exe");
                    }
                    ConfigManager.GeneralConfig.ForkFixVersion = 4;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 4.1)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("internals\\MinerOptionPackage_ClaymoreDual.json"))
                    {
                        File.Delete("internals\\MinerOptionPackage_ClaymoreDual.json");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 4.1;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 5)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 5;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 6)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 6;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 7)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 7;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 8)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 8;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 8.2)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 8.2;
                }
                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.1)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.1;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.2)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.2;
                }

                if (Configs.ConfigManager.GeneralConfig.ForkFixVersion < 9.3)
                {
                    Helpers.ConsolePrint("NICEHASH", "Old version");
                    if (Directory.Exists("internals"))
                    {
                        Directory.Delete("internals", true);
                    }

                    if (File.Exists("bin\\xmrig\\xmrig.exe"))
                    {
                        File.Delete("bin\\xmrig\\xmrig.exe");
                    }

                    if (File.Exists("bin_3rdparty\\t-rex\\t-rex.exe"))
                    {
                        File.Delete("bin_3rdparty\\t-rex\\t-rex.exe");
                    }

                    ConfigManager.GeneralConfig.ForkFixVersion = 9.3;
                }

                //**

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

                if (!pathSet)
                {
                    Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
                }

                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }

                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                // check WMI
                if (Helpers.IsWmiEnabled())
                {
                    if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                    {
                        Application.Run(new Form_Main());
                    }
                }
                else
                {
                    MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                    International.GetText("Program_WMI_Error_Title"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }