Ejemplo n.º 1
0
        private UndoObject SaveState(string propertyName)
        {
            UndoObject undoObject = null;
            var        index      = Workers.WorkerIndex;
            int        count      = Workers.WorkerCount;

            switch (propertyName)
            {
            case "WorkersPowerCost":
                undoObject = new UndoObject(UndoOperationType.WorkersPowerCost, -1, Workers.PowerCost);
                break;

            case "WorkersCoinType":
                undoObject = new UndoObject(UndoOperationType.WorkersCoinType, -1, Workers.CoinType);
                break;

            case "WorkersDisplayCoinAs":
                undoObject = new UndoObject(UndoOperationType.WorkersDisplayCoinAs, -1, Workers.DisplayCoinAs);
                break;

            case "WorkerList":
                undoObject = new UndoObject(UndoOperationType.WorkerEdit, index, Workers.WorkerList[index].CloneNoEvents());
                break;

            case "WorkerAdd":
                undoObject = new UndoObject(UndoOperationType.WorkerAdd, -1, null);
                break;

            case "WorkerAddRange":
                undoObject = new UndoObject(UndoOperationType.WorkerAddRange, index, count);
                break;

            case "WorkerInsert":
                undoObject = new UndoObject(UndoOperationType.WorkerInsert, index, Workers.WorkerList[index].CloneNoEvents());
                break;

            case "WorkerRemove":
                undoObject = new UndoObject(UndoOperationType.WorkerRemove, index, Workers.WorkerList[index].CloneNoEvents());
                break;

            case "WorkerRemoveRange":
                var newWorkerList = new ObservableCollection <Worker>();
                for (int i = 0; i < count; i++)
                {
                    newWorkerList.Add(Workers.WorkerList[index + i + 1].CloneNoEvents());
                }
                undoObject = new UndoObject(UndoOperationType.WorkerRemoveRange, index, newWorkerList);
                break;

            case "WorkerMove":
                undoObject = new UndoObject(UndoOperationType.WorkerMove, index, Workers.WorkerNewIndex);
                break;

            case "WtmSettings":
                undoObject = new UndoObject(UndoOperationType.SettingsEdit, -1, WtmSettings.Clone());
                break;

            case "WorkersAll":
                var newAllWorkers = new ObservableCollection <Worker>();
                foreach (var worker in Workers.WorkerList)
                {
                    newAllWorkers.Add(worker.CloneNoEvents());
                }
                undoObject = new UndoObject(UndoOperationType.WorkersAll, -1, newAllWorkers);
                break;
            }
            return(undoObject);
        }
Ejemplo n.º 2
0
        private async void CalculateProfitCommand(object parameter)
        {
            CalculateProfit.SetCanExecute(false);
            LoadHistoricalCharts.SetCanExecute(false);
            SwitchManually.SetCanExecute(false);

            ProfitTablesEnabled = true;

            var coinList = Workers.GetCoins(Workers.WorkerList, true);

            if (!coinList.Contains("Bitcoin"))
            {
                coinList.Add("Bitcoin");
            }

            //Update Yahoo rates if necessary
            if (WtmSettings.UseYahooRates &&
                WtmSettings.DisplayCurrency != "USD" &&
                WtmSettings.DisplayCurrency != "BTC" &&
                WtmSettingsObject.DisplayCurrencyListDate.Date != DateTime.Today)
            {
                await WtmSettings.GetYahooRates();

                if (WtmSettings.DisplayCurrencyList.Count == 2)
                {
                    BypassUndo(() => WtmSettings.UseYahooRates = false);
                    MessageBox.Show($"{Constants.AppName} could not download the list of currencies from Yahoo. Values will be displayed in USD.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }

            // Calculate mean hashrate
            var coinHashList = GetHashrates(coinList);

            // Get WTM coin data
            Dictionary <string, WtmData> wtmDataDict = null;

            (Dictionary <string, WtmData> data, WhatToMine.GetWtmCoinDataResult)wtmDataResult = (null, WhatToMine.GetWtmCoinDataResult.Fail);
            try
            {
                wtmDataResult = await WhatToMine.GetWtmCoinData(coinHashList, true);
            }
            catch (Exception ex)
            {
            }
            wtmDataDict = wtmDataResult.data;
            if (wtmDataDict == null)
            {
                CalculateProfitCommandQuit();
                return;
            }


            var    btc = wtmDataDict["Bitcoin"];
            string keyName;

            if (WtmSettings.Average24)
            {
                keyName = "exchange_rate24";
            }
            else
            {
                keyName = "exchange_rate";
            }

            string btcValue;

            btc.Json.TryGetValue(keyName, out btcValue);
            if (btcValue != null)
            {
                WtmSettings.DisplayCurrencyList["BTC"] = Helpers.StringToDecimal(btcValue);
            }
            else
            {
                MessageBox.Show("Failed to read BTC price from whattomine.com", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            // Form profit tables from wtmDataList
            ProfitTables.Tables.Clear();
            var workersChecked = Workers.WorkerList.Where(w => w.Query).ToList();
            var profitTables   = WhatToMine.CreateProfitTables(wtmDataDict, workersChecked, (decimal)Workers.PowerCost, WtmSettings);

            foreach (var table in profitTables)
            {
                ProfitTables.Tables.Add(table);
            }

            CalculateProfitCommandQuit();

            ScanLan.RaiseCanExecuteChanged();
            ScanLanCommand(null);
        }
Ejemplo n.º 3
0
        private async void WtmSettings_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Debug.WriteLine("222 WtmSettings_PropertyChanged " + e.PropertyName + " " + WtmSettings.SwitchTimeFrom.Hour + ":" + WtmSettings.SwitchTimeFrom.Minute + " " + +WtmSettings.SwitchTimeTo.Hour + ":" + WtmSettings.SwitchTimeTo.Minute);
            Debug.WriteLine("222 SwitchTimeEdit " + WtmSettings.SwitchTimeEdit);
            if (e.PropertyName == "SwitchPeriod")
            {
                SwitchTimeIsUpdated = false;
            }
            if (e.PropertyName == "SwitchTimeEdit")
            {
                if (WtmSettings.SwitchTimeEdit && SwitchTimeIsUpdated)
                {
                    SwitchTimeIsUpdated = false;
                }

                if (WtmSettings.SwitchTimeEdit == false)
                {
                    SwitchTimeUpdateIsInProgress = false;
                    return;
                }

                if (WtmSettings.SwitchTimeEdit && SwitchTimeUpdateIsInProgress)
                {
                    return;
                }

                if (WtmSettings.SwitchTimeEdit && SwitchTimeUpdateIsInProgress == false)
                {
                    Debug.WriteLine("!!! WtmSettings_PropertyChanged SaveUndoRedo" + " " + WtmSettings.SwitchTimeEdit + " Property: " + e.PropertyName);
                    Debug.WriteLine("SwitchTimeUpdateIsInProgress: " + SwitchTimeUpdateIsInProgress + " SwitchTimeIsUpdated: " + SwitchTimeIsUpdated);
                    SaveUndoRedo("WtmSettings");
                    SwitchTimeUpdateIsInProgress = true;
                    return;
                }
            }
            if (e.PropertyName == "HistoryTimeEdit")
            {
                if (WtmSettings.HistoryTimeEdit && HistoryTimeIsUpdated)
                {
                    HistoryTimeIsUpdated = false;
                }

                if (WtmSettings.HistoryTimeEdit == false)
                {
                    HistoryTimeUpdateIsInProgress = false;
                    return;
                }

                if (WtmSettings.HistoryTimeEdit && HistoryTimeUpdateIsInProgress)
                {
                    return;
                }

                if (WtmSettings.HistoryTimeEdit && HistoryTimeUpdateIsInProgress == false)
                {
                    Debug.WriteLine("!!! WtmSettings_PropertyChanged SaveUndoRedo" + " " + WtmSettings.HistoryTimeEdit);
                    Debug.WriteLine("HistoryTimeUpdateIsInProgress: " + HistoryTimeUpdateIsInProgress + " HistoryTimeIsUpdated: " + HistoryTimeIsUpdated);
                    SaveUndoRedo("WtmSettings");
                    HistoryTimeUpdateIsInProgress = true;
                    return;
                }
            }

            if (e.PropertyName == "StartWithWindows")
            {
                if (WtmSettings.StartWithWindows)
                {
                    string path = Helpers.ApplicationPath();
                    SetRegistryKeyValue(Constants.RunRegistryKey, Constants.AppName, path);
                }
                else
                {
                    DeleteRegistryKeyValue(Constants.RunRegistryKey, Constants.AppName);
                }
            }
            if (e.PropertyName == "AutoSwitch")
            {
                if (WtmSettings.AutoSwitch == false)
                {
                    ClearJob(JobType.Switch);
                    SwitchSchedule = new DateTime();
                    UpdateNextJobStatus();
                    WtmSwitchTimeFromStored = WtmSettings.SwitchTimeFrom.Clone();
                    WtmSwitchTimeToStored   = WtmSettings.SwitchTimeTo.Clone();
                    SwitchTimeIsUpdated     = true;
                }
                else
                {
                    WtmSwitchTimeFromStored = new ScheduleTime(-1, -1);
                    WtmSwitchTimeToStored   = new ScheduleTime(-1, -1);
                    SwitchTimeIsUpdated     = true;
                }
            }
            if (e.PropertyName == "BackupHistoricalPrices")
            {
                if (WtmSettings.BackupHistoricalPrices == false)
                {
                    ClearJob(JobType.UpdatePriceHistory);
                    HistoricalPricesSchedule = new DateTime();
                    UpdateNextJobStatus();
                    WtmHistoryTimeFromStored = WtmSettings.HistoryTimeFrom.Clone();
                    WtmHistoryTimeFromStored = WtmSettings.HistoryTimeTo.Clone();
                    HistoryTimeIsUpdated     = true;
                }
                else
                {
                    WtmHistoryTimeFromStored = new ScheduleTime(-1, -1);
                    WtmHistoryTimeFromStored = new ScheduleTime(-1, -1);
                    HistoryTimeIsUpdated     = true;
                }
            }
            if (e.PropertyName == "ProxyPassword")
            {
                WtmSettings.ProxyPasswordEncrypted = WtmSettings.ProxyPassword.Encrypt();
            }
            if (e.PropertyName == "Proxy" ||
                e.PropertyName == "UseProxy" ||
                e.PropertyName == "ProxyUserName" ||
                e.PropertyName == "ProxyPassword" ||
                e.PropertyName == "AnonymousProxy")
            {
                UpdateWtmHttpClient();
            }
            if (e.PropertyName == "ApplicationMode")
            {
                TestConnection.RaiseCanExecuteChanged();
                if (WtmSettings.ApplicationMode == "Standalone")
                {
                    WtmSettings.ServerSettingsAreUpdated = true;
                    if (WtmProxyServerServiceHost != null)
                    {
                        WtmProxyServerServiceHost.Close();
                    }
                }
                ApplyWtmSettingsAndSave();
            }
            if (e.PropertyName == "WtmRequestInterval")
            {
                WhatToMine.RequestInterval = WtmSettings.WtmRequestInterval;
            }
            if (e.PropertyName == "UseYahooRates")
            {
                SaveUndoIsEnabled = false;
                if (WtmSettings.UseYahooRates)
                {
                    await WtmSettings.GetYahooRates(true);
                }
                else
                {
                    WtmSettings.DefaulDisplayCurrencyList();
                }
                SaveUndoIsEnabled = true;
            }
        }
Ejemplo n.º 4
0
 private void UnHookUpWmtSettingsPropertyChangeEvents()
 {
     WtmSettings.UnHookEvents();
     WtmSettings.PropertyChanging -= WtmSettings_PropertyChanging;
     WtmSettings.PropertyChanged  -= WtmSettings_PropertyChanged;
 }
Ejemplo n.º 5
0
 private void HookUpWmtSettingsPropertyChangeEvents()
 {
     WtmSettings.HookUpEvents();
     WtmSettings.PropertyChanging += WtmSettings_PropertyChanging;
     WtmSettings.PropertyChanged  += WtmSettings_PropertyChanged;
 }
        public async Task InitializeInterface()
        {
            // Delete registry key left-over
            var startWithWindows = GetRegistryKeyValue(Constants.RunRegistryKey, Constants.AppName);

            if (startWithWindows != null && !WtmSettings.StartWithWindows)
            {
                DeleteRegistryKeyValue(Constants.RunRegistryKey, Constants.AppName);
            }

            ApplyServerSettingsCommand(null); // Start server if app's role is 'Server'

            NetHelper.Port        = WtmSettings.TcpPort;
            AccessPoinServiceHost = new ServiceHost(typeof(Service));
            AccessPoinServiceHost.Open();

            string failedToDecrypt = "The encryption is based on machine configuration. "
                                     + "If you have copied settings to a different machine, logged on as a different user or changed your Windows password you need to re-enter ";

            ScanLanCancelSource = new System.Threading.CancellationTokenSource();
            var token = ScanLanCancelSource.Token;

            Func <Task> taskLoadWtmCoins = (async() =>
            {
                //Load Whattomine available coins
                if (WtmSettings.ProxyPasswordEncrypted != null && WtmSettings.ProxyPasswordEncrypted != string.Empty)
                {
                    try
                    {
                        BypassUndo(() => WtmSettings.ProxyPassword = WtmSettings.ProxyPasswordEncrypted.DecryptSecure());
                    }
                    catch (Exception)
                    {
                        WtmSettings.ProxyPasswordEncrypted = null;
                        string msg = "Failed to decrypt WhatToMine proxy password. " + failedToDecrypt + "the proxy password.";
                        var t = Task.Run(() => MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error));
                    }
                }
                await LoadWtmCoins(token);

                // Update coins statuses
                if (WtmCoins != null)
                {
                    UpdateCoinStatus();
                }
                IsInitializingWtm = false;
            });

            Func <Task> taskLoadYahooCurrencies = (async() =>
            {
                //Load Yahoo currencies
                SaveUndoIsEnabled = false;
                await WtmSettings.GetYahooRates();
                SaveUndoIsEnabled = true;
            });

            var tasks = new List <Task>()
            {
                taskLoadWtmCoins()
            };

            if (WtmSettings.UseYahooRates)
            {
                tasks.Add(taskLoadYahooCurrencies());
            }
            try
            {
                await Task.WhenAll(tasks).WithCancellation(token);
            }
            catch (Exception ex)
            {
                Task <MessageBoxResult> t = null;
                if (ex.Message != "The operation was canceled.")
                {
                    t = Task.Run(() => MessageBox.Show("Error while waiting for taskLoadWtmCoins or taskLoadYahooCurrencies.\n" + ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error));
                }
            }
            finally
            {
                IsInitializingWtm = false;
            }

            // Update callback
            using (RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Constants.BaseRegistryKey, true))
            {
                if (key != null)
                {
                    var callerHostName = key.GetValue("CallerHostName") as string;
                    if (callerHostName != null && callerHostName != string.Empty)
                    {
                        var address = BuildServerAddress(callerHostName, Constants.AccessPoint);
                        var channel = Service.NewChannel(address, TimeSpan.FromSeconds(60));
                        try
                        {
                            await channel.UpdateApplicationCallback(Environment.MachineName, Helpers.ApplicationVersion());
                        }
                        catch { }
                        finally
                        {
                            NetHelper.CloseChannel(channel);
                        }
                        key.DeleteValue("CallerHostName");
                    }
                }
            }

            bool workersExist  = File.Exists(Constants.WorkersFile);
            bool settingsExist = File.Exists(Constants.WtmSettingsFile);

            if (!workersExist && !settingsExist)
            {
                var t = Task.Run(() =>
                                 MessageBox.Show($"If you're running a fresh copy of {Constants.AppName} please define your workers inside 'Workers' tab and click 'Save' icon.", "Default configuration used", MessageBoxButton.OK, MessageBoxImage.Information));
            }

            else
            {
                if (DefaultWorkers)
                {
                    var t = Task.Run(() =>
                                     MessageBox.Show($"{Constants.WorkersFile} is missing or corrupt.", "", MessageBoxButton.OK, MessageBoxImage.Warning));
                }
                if (DefaultWtmSettings)
                {
                    var t = Task.Run(() =>
                                     MessageBox.Show($"{Constants.WtmSettingsFile} is missing or corrupt. Default settings are used.", "", MessageBoxButton.OK, MessageBoxImage.Warning));
                }
            }

            // Check if there are any pending jobs in registry
            bool   switchJobIsInProgress      = false;
            bool   updatePriceJobIsInProgress = false;
            string switchTime            = string.Empty;
            string switchLastTime        = string.Empty;
            string updatePriceTime       = string.Empty;
            string updatePriceLastUpdate = string.Empty;

            using (RegistryKey switchKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Constants.SwitchRegistryKey, true))
                using (RegistryKey updatePriceKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Constants.UpdatePriceHistoryRegistryKey, true))
                {
                    if ((string)switchKey.GetValue("IsInProgress") == "True")
                    {
                        switchJobIsInProgress = true;
                    }
                    switchTime = (string)switchKey.GetValue("Schedule");
                    if (switchTime != null && switchTime != string.Empty)
                    {
                        SwitchSchedule = Convert.ToDateTime(switchTime, DateTimeFormatInfo.InvariantInfo).ToLocalTime();
                    }
                    switchLastTime = (string)switchKey.GetValue("LastUpdate");
                    if (switchLastTime != null && switchLastTime != string.Empty)
                    {
                        SwitchLastTime = Convert.ToDateTime(switchLastTime, DateTimeFormatInfo.InvariantInfo).ToLocalTime();
                    }

                    if ((string)updatePriceKey.GetValue("IsInProgress") == "True")
                    {
                        updatePriceJobIsInProgress = true;
                    }
                    updatePriceTime = (string)updatePriceKey.GetValue("Schedule");
                    if (updatePriceTime != null && updatePriceTime != string.Empty)
                    {
                        HistoricalPricesSchedule = Convert.ToDateTime(updatePriceTime, DateTimeFormatInfo.InvariantInfo).ToLocalTime();
                    }
                    updatePriceLastUpdate = (string)updatePriceKey.GetValue("LastUpdate");
                    if (updatePriceLastUpdate != null && updatePriceLastUpdate != string.Empty)
                    {
                        HistoricalPricesLastTime = Convert.ToDateTime(updatePriceLastUpdate, DateTimeFormatInfo.InvariantInfo).ToLocalTime();
                    }
                }

            // Start job if one is still pending after system restart
            if (switchJobIsInProgress && workersExist)
            {
                await SwitchTaskWrapper();

                switchTime = string.Empty;
            }
            if (updatePriceJobIsInProgress && workersExist)
            {
                await UpdatePriceHistoryTaskWrapper();

                updatePriceTime = string.Empty;
            }

            // Delete Mass Update left-overs if they exist
            Helpers.DeleteUpdateLeftOvers();

            // Check if Switch job has been missed today/this hour
            if (WtmSettings.AutoSwitch)
            {
                if (switchTime != string.Empty)
                {
                    DateTime schedule   = Convert.ToDateTime(switchTime, DateTimeFormatInfo.InvariantInfo);
                    DateTime now        = DateTime.Now;
                    DateTime expiryTime = GetSwitchExpiry(schedule);
                    if (schedule < now && now < expiryTime)
                    {
                        await SwitchTaskWrapper();

                        switchTime = string.Empty;
                    }
                }
            }

            // Check if UpdateHistoricalPrices job has been missed today
            DateTime updatePriceLastUpdateTime;

            if (WtmSettings.BackupHistoricalPrices)
            {
                if (updatePriceLastUpdate != string.Empty)
                {
                    updatePriceLastUpdateTime = Convert.ToDateTime(updatePriceLastUpdate, DateTimeFormatInfo.InvariantInfo);
                    DateTime now = DateTime.Now;
                    DateTime historyBackupTime = new DateTime(now.Year, now.Month, now.Day, WtmSettings.HistoryTimeTo.Hour, WtmSettings.HistoryTimeTo.Minute, 0, DateTimeKind.Local);
                    if (now > historyBackupTime && updatePriceLastUpdateTime.Day < now.Day) // Now is past daily schedule and last update had been done before today
                    {
                        await UpdatePriceHistoryTaskWrapper();

                        updatePriceTime = string.Empty;
                    }
                }
            }

            // Schedule jobs
            JobManager.UseUtcTime();
            if (WtmSettings.AutoSwitch == true && workersExist)
            {
                Debug.WriteLine(DateTime.Now + " Scheduling a Switch task at startup.");
                if (switchTime != string.Empty)
                {
                    ResetScheduledJob(JobType.Switch, switchTime);
                }
                else
                {
                    ResetScheduledJob(JobType.Switch);
                }
            }
            if (WtmSettings.BackupHistoricalPrices == true && workersExist)
            {
                if (updatePriceTime != string.Empty)
                {
                    ResetScheduledJob(JobType.UpdatePriceHistory, updatePriceTime);
                }
                else
                {
                    ResetScheduledJob(JobType.UpdatePriceHistory);
                }
            }
            UpdateNextJobStatus();
        }