Esempio n. 1
0
        private void SaveCommand(object parameter)
        {
            Debug.WriteLine("Save button command.");

            Workers.SaveWorkers(Workers);

            ApplyWtmSettingsAndSave();
        }
Esempio n. 2
0
        private void MoveWorkerDownCommand(object parameter)
        {
            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            if (workerIndex != -1)
            {
                Workers.WorkerListMove(workerIndex, workerIndex + 1);
            }
        }
Esempio n. 3
0
        private void AddCoinsByAlgorithmCommand(object obj)
        {
            var algoSelector = new AlgorithmSelector();
            var vm           = new AlgorithmSelectorVM();

            vm.DisplayCoinAs         = Workers.DisplayCoinAs;
            algoSelector.DataContext = vm;
            var dialogResult = algoSelector.ShowDialog();

            if (dialogResult == false)
            {
                return;
            }
            var wtmDict    = WtmCoins.ToDictionary(x => x.Name, y => y.Status);
            var coinTables = new ObservableCollection <CoinTable>();

            foreach (var algo in vm.Algorithms)
            {
                foreach (var coin in algo.Coins)
                {
                    string status = null;
                    wtmDict.TryGetValue(coin.Name, out status);
                    if (coin.IsChecked && coin.Show)
                    {
                        coinTables.Add(new CoinTable(new ObservableCollection <Coin> {
                            new Coin {
                                Name = coin.Name, Symbol = coin.Symbol, Hashrate = vm.Hashrate, Algorithm = algo.Name, Status = status
                            }
                        }, 0, 0, false, string.Empty, string.Empty, string.Empty));
                    }
                }
            }
            if (coinTables.Count == 0)
            {
                return;
            }

            if (vm.Option == AlgorithmSelectorVM.WorkerOptions.AddToExisting)
            {
                var worker = Workers.WorkerList.FirstOrDefault(x => x.Name == vm.SelectedWorker);
                if (worker != null)
                {
                    worker.RaiseProperychanging("CoinList");
                    foreach (var ct in coinTables)
                    {
                        worker.CoinList.Add(ct.Clone());
                    }
                    worker.RaiseProperychanged("CoinList");
                }
            }
            if (vm.Option == AlgorithmSelectorVM.WorkerOptions.AddToNew)
            {
                var worker = new Worker("NEW WORKER", "", new ObservableCollection <string>(), new ObservableCollection <CoinTable>(coinTables));
                Workers.WorkerListAdd(worker);
            }
        }
Esempio n. 4
0
        private void AddWorkerCommand(object parameter)
        {
            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            Workers.WorkerIndex = workerIndex;
            if (workerIndex != -1)
            {
                var newWorker = Workers.WorkerList[workerIndex].Clone();
                Workers.WorkerListInsert(workerIndex, newWorker);
            }
        }
Esempio n. 5
0
        private void MassUpdateApplicationCommand(object obj)
        {
            var massUpdateWindow = new MassUpdate();
            var vm = new MassUpdateVM(Workers.GetComputers(Computer.OperationStatus.OperationInProgress));

            vm.Header       = $"Update {Constants.AppName}";
            vm.WindowTitle  = $"Mass Update";
            vm.ColumnHeader = "Version";
            vm.SubHeader    = $"{Environment.MachineName}: {Helpers.ApplicationVersion()}";
            massUpdateWindow.DataContext = vm;
            var dialogResult = massUpdateWindow.ShowDialog();
        }
Esempio n. 6
0
        private void MassUpdateWtmSettingsCommand(object obj)
        {
            var massUpdateWindow = new MassUpdate();
            var vm = new MassUpdateVM(Workers.GetComputers(Computer.OperationStatus.OperationInProgress));

            vm.Header       = $"Update Settings";
            vm.WindowTitle  = $"Mass Update";
            vm.ColumnHeader = "Settings Date";
            vm.SubHeader    = $"{Environment.MachineName}: {WtmSettingsObject.GetWtmSettingsLastUpdateTime()}";
            massUpdateWindow.DataContext = vm;
            var dialogResult = massUpdateWindow.ShowDialog();
        }
Esempio n. 7
0
        private void CopyWorkerCommand(object obj)
        {
            var itemToCopy = obj as WorkerCopy;

            if (itemToCopy != null)
            {
                var newIndex = Workers.WorkerList.IndexOf(itemToCopy.DestinationWorker);
                if (newIndex != -1)
                {
                    Workers.WorkerListInsert(newIndex, itemToCopy.SourceWorker);
                }
            }
        }
Esempio n. 8
0
 public static bool SaveWorkers(Workers workers)
 {
     try
     {
         string json          = JsonConverter.ConvertToJson(workers);
         string jsonFormatted = JsonConverter.FormatJson(json);
         Helpers.WriteToTxtFile(Constants.WorkersFile, jsonFormatted);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 9
0
        public Workers Clone()
        {
            Workers _new = new Workers(WorkerList_CollectionChanged);

            foreach (Worker w in this.WorkerList)
            {
                _new.WorkerList.Add(w.Clone());
            }

            _new.PowerCost         = this.PowerCost;
            _new.CoinType          = this.CoinType;
            _new.DisplayCoinAs     = this.DisplayCoinAs;
            _new.NetworkScanMethod = this.NetworkScanMethod;
            return(_new);
        }
        public AlgorithmSelectorVM()
        {
            Workers        = ViewModel.Instance.Workers.WorkerList.Select(x => x.Name).ToList();
            SelectedWorker = Workers.FirstOrDefault();

            Process              = new RelayCommand(ProcessCommand, Process_CanExecute);
            CoinsSelectAll       = new RelayCommand(CoinsSelectAllCommand);
            CoinsSelectNone      = new RelayCommand(CoinsSelectNoneCommand);
            AlgorithmsSelectAll  = new RelayCommand(AlgorithmsSelectAllCommand);
            AlgorithmsSelectNone = new RelayCommand(AlgorithmsSelectNoneCommand);
            Initialize           = new RelayCommand(InitializeCommand);

            ShowActiveCoinsOnly   = true;
            this.PropertyChanged += AlgorithmSelectorVM_PropertyChanged;
        }
Esempio n. 11
0
        public Workers CloneNoEvents()
        {
            Workers _new = new Workers();

            _new.WorkerList = new ObservableCollection <Worker>();

            foreach (Worker w in this.WorkerList)
            {
                _new.WorkerList.Add(w.CloneNoEvents());
            }

            _new.PowerCost         = this.PowerCost;
            _new.CoinType          = this.CoinType;
            _new.DisplayCoinAs     = this.DisplayCoinAs;
            _new.NetworkScanMethod = this.NetworkScanMethod;
            return(_new);
        }
Esempio n. 12
0
        private void NewWorkerCommand(object parameter)
        {
            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            Workers.WorkerIndex = workerIndex;
            if (workerIndex != -1)
            {
                var index = workerIndex + 1;
                if (index < Workers.WorkerList.Count)
                {
                    Workers.WorkerListInsert(index, Worker.DefaultWorker());
                }
                else
                {
                    Workers.WorkerListAdd(Worker.DefaultWorker());
                }
            }
        }
Esempio n. 13
0
        private void DeleteWorkerCommand(object parameter)
        {
            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            Workers.WorkerIndex = workerIndex;
            if (workerIndex != -1)
            {
                var name = Workers.WorkerList[workerIndex].Name;
                if (name == string.Empty)
                {
                    name = "unnamed worker";
                }
                var response = MessageBox.Show("Delete " + name + "?", "Delete worker", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (response == MessageBoxResult.Yes)
                {
                    Workers.WorkerListRemoveAt(workerIndex);
                }
            }
        }
        public async Task <HistoricalData> GetNewPriceHistoryRecord(StreamWriter logFile)
        {
            var coinList = Workers.GetCoins(Workers.WorkerList);

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

            var coinHashList = GetHashrates(coinList);

            var wtmRequestIntervalOld = WtmSettings.WtmRequestInterval;

            if (WtmSettings.SaveAllCoins)
            {
                var allCoins = await WhatToMine.GetAllWtmCoinNamesFromJson(true);

                var difference = allCoins.Except(coinList);
                foreach (var coin in difference)
                {
                    coinHashList[coin] = 1000;
                }
            }

            // Get WTM coin data
            var wtmDataResult = await WhatToMine.GetWtmCoinData(coinHashList, false, logFile).ConfigureAwait(false);

            if (wtmDataResult.result == WhatToMine.GetWtmCoinDataResult.CoinNotFound)
            {
                return(null);
            }
            var wtmDataDict = wtmDataResult.data;

            if (wtmDataDict != null)
            {
                return(new HistoricalData(DateTime.Now, wtmDataDict));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 15
0
        //public static List<AlgoCoin> GetCoins(IList<Worker> workerList, bool checkForQuery = false, bool checkForSwitch = false)
        //{
        //    var coinList = new List<AlgoCoin>();
        //    foreach (Worker w in workerList)
        //    {
        //        if (checkForQuery && !w.Query)
        //            continue;

        //        foreach (CoinTable ct in w.CoinList)
        //        {
        //            if (checkForSwitch && !ct.Switch)
        //                continue;
        //            foreach (Coin c in ct.Coins)
        //                coinList.Add(new AlgoCoin(c.Name, c.Symbol, c.Algorithm));
        //        }
        //    }
        //    return coinList;
        //}

        public static Workers ReadWorkers(bool showError = true)
        {
            string  workersContent   = null;
            Workers convertedWorkers = null;

            try { workersContent = System.IO.File.ReadAllText(Constants.WorkersFile); }
            catch { return(null); }
            convertedWorkers = JsonConverter.ConvertFromJson <Workers>(workersContent, showError);
            if (convertedWorkers != null)
            {
                return(new Workers(
                           convertedWorkers.WorkerList,
                           convertedWorkers.PowerCost,
                           convertedWorkers.CoinType,
                           convertedWorkers.DisplayCoinAs,
                           convertedWorkers.NetworkScanMethod));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 16
0
        public async Task ScanLan()
        {
            ScanIsInProgress = true;

            UpdateCancelSource = new CancellationTokenSource();
            var token = UpdateCancelSource.Token;
            var tasks = new List <Task>();

            var appVersion      = new Version(Helpers.ApplicationVersion());
            var workersDate     = Workers.GetWorkersLastUpdateTime();
            var wtmSettingsDate = WtmSettingsObject.GetWtmSettingsLastUpdateTime();

            foreach (var pc in Computers)
            {
                Task task = null;
                switch (ColumnHeader)
                {
                case "Version":
                    task = Task.Run(async() => await QueryRemoteVersion(pc, token, appVersion));
                    break;

                case "Workers Date":
                    task = Task.Run(async() => await QueryRemoteWorkersDate(pc, token, workersDate));
                    break;

                case "Settings Date":
                    task = Task.Run(async() => await QueryRemoteWtmSettingsDate(pc, token, wtmSettingsDate));
                    break;
                }
                tasks.Add(task);
            }

            await Task.WhenAll(tasks);

            ScanIsInProgress = false;
        }
Esempio n. 17
0
        private async Task UpdateWorkersFromServer(StreamWriter logFile)
        {
            bool addressOk = ValidateServerAddress(logFile);

            if (!addressOk)
            {
                return;
            }

            var serverAddress = BuildServerAddress(WtmSettings.ServerName, Constants.AccessPoint);
            var channel       = Service.NewChannel(serverAddress);

            DateTime remoteWorkersDate = default(DateTime);
            string   errorMessage      = "Failed to update Workers from local server.";

            try
            {
                remoteWorkersDate = await channel.GetWorkersDateAsync();
            }
            catch (Exception ex)
            {
                logFile?.WriteLine(errorMessage + " " + ex.Message);
                NetHelper.CloseChannel(channel);
                return;
            }

            if (remoteWorkersDate == default(DateTime))
            {
                NetHelper.CloseChannel(channel);
                logFile?.WriteLine(errorMessage);
                return;
            }

            var localWorkersDate = Workers.GetWorkersLastUpdateTime();

            if (localWorkersDate >= remoteWorkersDate)
            {
                logFile?.WriteLine($"{Constants.WorkersFile} is up to date.");
                NetHelper.CloseChannel(channel);
                return;
            }

            NetHelper.CloseChannel(channel);

            // Open stream channel for workers download
            serverAddress = BuildServerAddress(WtmSettings.ServerName, Constants.StreamServer);
            var streamChannel = Service.NewStreamChannel(serverAddress);

            Workers workers = null;

            try
            {
                var response = await streamChannel.GetWorkersAsync().ConfigureAwait(false);

                if (response != null)
                {
                    var memoryStream = new MemoryStream();
                    await response.Stream.CopyToAsync(memoryStream);

                    workers = NetHelper.DeserializeFromStream <Workers>(memoryStream);
                }

                if (workers == null)
                {
                    throw new NullReferenceException("The received data are null.");
                }
            }
            catch (Exception ex)
            {
                logFile?.WriteLine(errorMessage + " " + ex.Message);
                NetHelper.CloseChannel(streamChannel);
                return;
            }

            bool wResult = Workers.SaveWorkers(workers);

            if (!wResult)
            {
                logFile?.WriteLine("Workers have been received from local server but could not be saved.");
                NetHelper.CloseChannel(streamChannel);
                return;
            }

            IsInitializingWtm = true;

            Workers.PropertyChanging -= Workers_PropertyChanging;
            Workers.PropertyChanged  -= Workers_PropertyChanged;

            Workers = new Workers(workers.WorkerList, workers.PowerCost, workers.CoinType, workers.DisplayCoinAs, workers.NetworkScanMethod);

            Workers.PropertyChanging += Workers_PropertyChanging;
            Workers.PropertyChanged  += Workers_PropertyChanged;

            IsInitializingWtm = false;

            logFile?.WriteLine("Workers have been received from local server and successfully updated.");
            NetHelper.CloseChannel(streamChannel);
        }
Esempio n. 18
0
        public async Task <SwitchResult> SwitchStandalone()
        {
            var streamServerAddress = BuildServerAddress(WtmSettings.ServerName, Constants.StreamServer);

            using (var logFile = new StreamWriter(Constants.SwitchLog, true))
            {
                if (new FileInfo(Constants.SwitchLog).Length > 0)
                {
                    logFile.WriteLine(string.Empty);
                }
                logFile.WriteLine(DateTime.Now);

                // Respect the DelayNextSwitchTime setting
                if (WtmSettings.DelayNextSwitchTime != 0)
                {
                    var    lastTime    = new DateTime();
                    var    lastTimeObj = GetRegistryKeyValue(Constants.SwitchRegistryKey, "LastSuccess");
                    string lastTimeStr = lastTimeObj as string;
                    if (lastTimeStr != null && lastTimeStr != string.Empty)
                    {
                        lastTime = Convert.ToDateTime(lastTimeStr, DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
                        var now = DateTime.UtcNow;
                        var lastTimePlusDelay = lastTime.AddHours(WtmSettings.DelayNextSwitchTime);
                        if (now < lastTimePlusDelay)
                        {
                            logFile.WriteLine($"Because of the Delay option checked Auto Switch can proceed only after {lastTimePlusDelay.ToLocalTime()}.");
                            return(SwitchResult.DelayIsNotOver);
                        }
                    }
                }

                // Update Workers from server
                if (WtmSettings.ApplicationMode == "Client" && WtmSettings.UpdateWorkersFromServer)
                {
                    await UpdateWorkersFromServer(logFile);
                }

                //Find localhost name in Workers list (used in Standalone and Client modes )
                var    thisPcName = Environment.MachineName;
                Worker thisWorker = GetWorkerByPCName(thisPcName);
                if (thisWorker == null && WtmSettings.ApplicationMode != "Server")
                {
                    string msg = $"{thisPcName} was not found in any worker.";
                    logFile.WriteLine(msg);
                    return(SwitchResult.ThisPcIsNotListed);
                }

                // Get coin names from worker description
                var    coinList      = new List <string>();
                var    allCoinList   = new List <string>();
                var    workersList   = new List <Worker>();
                string noCoinChecked = string.Empty;
                if (thisWorker != null)
                {
                    noCoinChecked = $"No coin is checked as switchable in {thisWorker.Name}.";
                }
                else
                {
                    noCoinChecked = "No coin is checked as switchable.";
                }
                if (WtmSettings.ApplicationMode != "Server") // Standalone or Client mode - just the worker that contains localhost name
                {
                    workersList = new List <Worker> {
                        thisWorker
                    };
                }
                else // Server mode - all workers, all coins
                {
                    foreach (var w in Workers.WorkerList)
                    {
                        workersList.Add(w.Clone());
                    }
                    allCoinList = Workers.GetCoins(workersList, false, false);
                    if (allCoinList == null || allCoinList.Count == 0)
                    {
                        logFile.WriteLine(noCoinChecked);
                        return(SwitchResult.NothingToDo);
                    }
                    if (!allCoinList.Contains("Bitcoin"))
                    {
                        allCoinList.Add("Bitcoin");
                    }
                }
                coinList = Workers.GetCoins(workersList, false, true); // Only coins with Switch checked
                if (coinList == null || coinList.Count == 0)
                {
                    logFile.WriteLine(noCoinChecked);
                    return(SwitchResult.NothingToDo);
                }
                if (!coinList.Contains("Bitcoin"))
                {
                    coinList.Add("Bitcoin");
                }


                // Get WTM coins JSON data
                Dictionary <string, WtmData> wtmDataDict = new Dictionary <string, WtmData>();
                // Attempt to download data from local server
                HistoricalData localDataCopy = null;
                if (WtmSettings.ApplicationMode == "Client")
                {
                    var channel = Service.NewStreamChannel(streamServerAddress, TimeSpan.FromSeconds(60));
                    try
                    {
                        var response = await channel.GetWtmLocalDataAsync();

                        if (response != null)
                        {
                            var memoryStream = new MemoryStream();
                            await response.Stream.CopyToAsync(memoryStream);

                            localDataCopy = NetHelper.DeserializeFromStream <HistoricalData>(memoryStream);
                        }

                        if (localDataCopy == null)
                        {
                            throw new NullReferenceException("Local data from server are null.");
                        }
                    }
                    catch (Exception ex)
                    {
                        logFile.WriteLine($"Failed to download proxy data from local server {WtmSettings.ServerName}. " + ex.Message);
                        if (!WtmSettings.QueryWtmOnLocalServerFail)
                        {
                            return(SwitchResult.NoWtmData);
                        }
                    }
                    finally
                    {
                        NetHelper.CloseChannel(channel);
                    }

                    // Check if the received data are up to date
                    if (localDataCopy != null)
                    {
                        bool dataTimestampGood = EvaluateWtmDataTimeRange(localDataCopy.Date);
                        if (!dataTimestampGood && !WtmSettings.QueryWtmOnLocalServerFail)
                        {
                            logFile.WriteLine("The server cache data is expired."
                                              + " Make sure that AutoSwitch on the client launches later than on the server."
                                              + " For example, if AutoSwitch runs on a daily basis schedule AutoSwitch on the server to run at 9:00 and on the client machines at anyting between 10:00-23:59."
                                              + " This way the cache data obtained in the morning is valid for the rest of the day.");
                            return(SwitchResult.Terminate);
                        }
                        if (dataTimestampGood)
                        {
                            // Filter out coins downloded from server that are not checked for AutoSwitch locally
                            wtmDataDict = localDataCopy.PriceData.Where(x => coinList.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
                        }
                    }
                }
                // Download data from WhatToMine (Standalone or Server)
                if (wtmDataDict.Count == 0)
                {
                    StatusBarText = "Downloading coin definitions from whattomine.com...";
                    (Dictionary <string, WtmData> data, WhatToMine.GetWtmCoinDataResult result)wtmDataResult = (null, WhatToMine.GetWtmCoinDataResult.OK);
                    if (WtmSettings.ApplicationMode == "Server")
                    {
                        var allCoinHashList = GetHashrates(allCoinList);
                        wtmDataResult = await WhatToMine.GetWtmCoinData(allCoinHashList, false, logFile).ConfigureAwait(false);
                    }
                    else
                    {
                        var coinHashList = GetHashrates(coinList);
                        wtmDataResult = await WhatToMine.GetWtmCoinData(coinHashList, false, logFile).ConfigureAwait(false);
                    }
                    if (wtmDataResult.result == WhatToMine.GetWtmCoinDataResult.CoinNotFound)
                    {
                        return(SwitchResult.CoinNotFound);
                    }
                    wtmDataDict = wtmDataResult.data;
                    if (wtmDataDict == null)
                    {
                        return(SwitchResult.CoinNotFound);
                    }
                }

                // Update WTM coin data with historical averages from local database if opted to
                var  historicalDataList     = new List <HistoricalData>();
                bool historicalDataUpToDate = false;
                if (WtmSettings.UseHistoricalAverage)
                {
                    if (WtmSettings.ApplicationMode == "Client")
                    {
                        //Needs longer timeout for the server might be downloading all coins from whattomine.com
                        var channel = Service.NewStreamChannel(streamServerAddress, TimeSpan.FromSeconds(180));

                        try
                        {
                            var response = await channel.GetPriceHistoryAsync(new StreamDownloadRequest { Period = WtmSettings.HistoricalAveragePeriod }).ConfigureAwait(false);

                            if (response != null)
                            {
                                var memoryStream = new MemoryStream();
                                await response.Stream.CopyToAsync(memoryStream);

                                historicalDataList     = NetHelper.DeserializeFromStream <List <HistoricalData> >(memoryStream);
                                historicalDataUpToDate = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            logFile.WriteLine($"Failed to obtain historical prices from local server {WtmSettings.ServerName}. " + ex.Message);
                            return(SwitchResult.Error);
                        }
                        finally
                        {
                            NetHelper.CloseChannel(channel);
                        }
                    }
                    else
                    {
                        var result = await UpdatePriceHistory();

                        if (result == UpdatePriceHistoryResult.Success || result == UpdatePriceHistoryResult.AlreadyUpToDate)
                        {
                            historicalDataList     = ReadHistoricalData(WtmSettings.HistoricalAveragePeriod);
                            historicalDataUpToDate = true;
                        }
                    }
                    // Calculate historical prices for wtmDataList
                    if (historicalDataUpToDate)
                    {
                        GetHistoricalAverages(wtmDataDict, historicalDataList);
                    }
                }

                // Update WtmLocalData if in server mode
                if (WtmSettings.ApplicationMode == "Server")
                {
                    if (wtmDataDict != null && wtmDataDict.Count != 0)
                    {
                        using (var db = new LiteDatabase(Constants.DataBase))
                        {
                            var collection = db.GetCollection <HistoricalData>(Constants.LightDB_WtmCacheCollection);
                            collection.Delete(LiteDB.Query.All());
                            collection.Insert(new HistoricalData(DateTime.Now, wtmDataDict));
                        }
                    }
                }

                // Abandon if in server mode and DontSwitchServer is checked
                if (WtmSettings.ApplicationMode == "Server" && WtmSettings.DontSwitchServer)
                {
                    return(SwitchResult.NoNeedToSwitch);
                }
                if (WtmSettings.ApplicationMode == "Server" && !WtmSettings.DontSwitchServer && thisWorker == null)
                {
                    logFile.WriteLine("The server cannot switch because it is not listed in any worker table.");
                    return(SwitchResult.ThisPcIsNotListed);
                }

                // Calculate profit table for this PC and analize it
                var            profitTables = WhatToMine.CreateProfitTables(wtmDataDict, workersList, (decimal)Workers.PowerCost, WtmSettings, true);
                var            profitTable = profitTables.First();
                var            currentCoinShortcut = Shortcut.GetCurrentCoin(); // Get current coin from Startup folder .lnk
                ProfitTableRow maxCoinRow = null; decimal maxProfit = 0; decimal currentProfit = 0;
                bool           nothingChecked = false;
                WhatToMine.GetProfit(profitTable, currentCoinShortcut, out maxCoinRow, out maxProfit, out currentProfit, out nothingChecked);
                if (nothingChecked)
                {
                    string msg = "Nothing to do. Make sure there are actual switchable coins defined in worker.";
                    logFile.WriteLine(msg);
                    return(SwitchResult.NothingToDo);
                }
                if (maxProfit == 0)
                {
                    string msg = $"There is no coin with profit above 0 for {thisPcName}.";
                    logFile.WriteLine(msg);
                    return(SwitchResult.NothingToDo);
                }

                //Check profitability and price margin
                bool currentCoinMatch             = currentCoinShortcut?.GetName() == maxCoinRow.Name;
                bool currentCoinPathMatch         = currentCoinShortcut?.Path == maxCoinRow.Path;
                bool currentPforitIsHigherOrEqual = maxProfit <= currentProfit;
                bool currentProfitIsWithinMargin  = false;
                if (WtmSettings.PriceMargin > 0)
                {
                    currentProfitIsWithinMargin = maxProfit <= (currentProfit + (currentProfit * WtmSettings.PriceMargin / 100));
                }

                if (currentPforitIsHigherOrEqual)
                {
                    string msg;
                    msg = $"No need to switch. {thisPcName} is already set to mine the most profitable coin {currentCoinShortcut?.GetNameAndSymbol()}.";
                    logFile.WriteLine(msg);
                    return(SwitchResult.NoNeedToSwitch);
                }
                if (currentProfitIsWithinMargin)
                {
                    string msg;
                    if (currentCoinMatch && !currentCoinPathMatch)
                    {
                        msg = $"No need to switch. {thisPcName} is set to mine {currentCoinShortcut?.GetNameAndSymbol()} started by \"{currentCoinShortcut?.Path}\". It is less profitable than {maxCoinRow.NameAndSymbol} started by \"{maxCoinRow.Path}\" but the difference is within price margin.";
                    }
                    else
                    {
                        msg = $"No need to switch. {thisPcName} is set to mine {currentCoinShortcut?.GetNameAndSymbol()}. It is less profitable than {maxCoinRow.NameAndSymbol} but the difference is within price margin.";
                    }
                    logFile.WriteLine(msg);
                    return(SwitchResult.NoNeedToSwitch);
                }

                // Check if executable path exists
                if (!File.Exists(maxCoinRow.Path))
                {
                    logFile.WriteLine($"{maxCoinRow.Path} - file does not exist on {thisPcName}.");
                    return(SwitchResult.CoinNotFound);
                }

                bool startOk = false; // Start miner process flag
                try
                {
                    Shortcut.CreateCoinShortcut(maxCoinRow.Name, maxCoinRow.Symbol, maxCoinRow.Algorithm, maxCoinRow.Path, maxCoinRow.Arguments);
                    if (WtmSettings.RestartComputer)
                    {
                        RestartComputerPending = true;
                    }
                    if (WtmSettings.RestartMiner)
                    {
                        // Kill processes from KillList
                        var killResponse = KillProcesses(WtmSettings.KillList);
                        if (!killResponse.success && killResponse.failList != null)
                        {
                            string errorMessage = $"Startup shortcut to mine {maxCoinRow.NameAndSymbol} has been created but some processes could not be killed:";
                            logFile.WriteLine(errorMessage);
                            foreach (var entry in killResponse.failList)
                            {
                                if (entry != string.Empty)
                                {
                                    logFile.WriteLine(entry);
                                }
                            }
                            logFile.WriteLine($"{Environment.MachineName} will restart.");
                            RestartComputerPending = true;
                            SetRegistryKeyValue(Constants.SwitchRegistryKey, "LastSuccess", DateTime.UtcNow.ToString("o"));
                            return(SwitchResult.SwitchedSuccessfully);
                        }

                        if (!System.IO.File.Exists(maxCoinRow.Path))
                        {
                            logFile.WriteLine($"ERROR: File not found. {maxCoinRow.Path}");
                            return(SwitchResult.Error);
                        }

                        // Start miner process
                        var     startInfo = new ProcessStartInfo(maxCoinRow.Path, maxCoinRow.Arguments);
                        Process process   = new Process();
                        process.StartInfo = startInfo;
                        startOk           = process.Start();
                        if (!startOk)
                        {
                            throw new Exception($"\"{Path.GetFileName(maxCoinRow.Path)}\" failed to start.");
                        }
                    }
                    SetRegistryKeyValue(Constants.SwitchRegistryKey, "LastSuccess", DateTime.UtcNow.ToString("o"));
                    logFile.WriteLine($"Switched to {maxCoinRow.NameAndSymbol} successfully.");
                    return(SwitchResult.SwitchedSuccessfully);
                }
                catch (Exception ex)
                {
                    logFile.WriteLine($"Failed to switch to {maxCoinRow.NameAndSymbol}: {ex.Message}");
                    if (WtmSettings.RestartMiner && !startOk)
                    {
                        RestartComputerPending = true;
                        logFile.WriteLine($"{Environment.MachineName} will restart.");
                    }
                    return(SwitchResult.Error);
                }
            }
        }
Esempio n. 19
0
        // ViewModel constructor
        public ViewModel()
        {
            TestProperty = "TEST";

            IsInitializingWtm = true;

            ProfitTables = new ProfitTables {
                Tables = new ObservableCollection <ProfitTable>()
            };
            ProfitTables.Tables.CollectionChanged += ProfitTables_CollectionChanged;

            HistoricalCharts = new ObservableCollection <HistoricalChart>();

            // Read workers from file or create default
            Workers = Workers.ReadWorkers(false);
            if (Workers == null)
            {
                Workers        = new Workers(true).Clone();
                DefaultWorkers = true;
            }

            WorkersPropertyEventsAdd();

            // Read Wtm settings from file or create default settings
            WtmSettings = WtmSettingsObject.ReadWtmSettings(false);
            if (WtmSettings == null)
            {
                WtmSettings        = new WtmSettingsObject();
                DefaultWtmSettings = true;
            }

            WhatToMine.RequestInterval           = WtmSettings.WtmRequestInterval;
            WtmSettings.ServerSettingsAreUpdated = true;
            UpdateWtmHttpClient();

            WtmSwitchTimeFromStored          = WtmSettings.SwitchTimeFrom.Clone();
            WtmSwitchTimeToStored            = WtmSettings.SwitchTimeTo.Clone();
            WtmHistoricalAveragePeriodStored = WtmSettings.HistoricalAveragePeriod;
            WtmHistoryTimeFromStored         = WtmSettings.HistoryTimeFrom.Clone();
            WtmHistoryTimeToStored           = WtmSettings.HistoryTimeTo.Clone();

            HookUpWmtSettingsPropertyChangeEvents();

            SwitchTimeIsUpdated  = true;
            HistoryTimeIsUpdated = true;

            History = new History();

            ProfitTablesEnabled = true;

            Initialize            = new RelayCommandLight(InitializeCommand);
            AddWorker             = new RelayCommandLight(AddWorkerCommand);
            DeleteWorker          = new RelayCommandLight(DeleteWorkerCommand);
            NewWorker             = new RelayCommandLight(NewWorkerCommand);
            ExportWorkers         = new RelayCommandLight(ExportWorkersCommand);
            ImportWorkers         = new RelayCommandLight(ImportWorkersCommand);
            MultiplyHashrate      = new RelayCommandLight(MultiplyHashrateCommand);
            MoveWorker            = new RelayCommandLight(MoveWorkerCommand);
            CopyWorker            = new RelayCommandLight(CopyWorkerCommand);
            MoveWorkerDown        = new RelayCommandLight(MoveWorkerDownCommand);
            MoveWorkerUp          = new RelayCommandLight(MoveWorkerUpCommand);
            AddCoinTable          = new RelayCommandLight(AddCoinTableCommand);
            DeleteCoinTable       = new RelayCommandLight(DeleteCoinTableCommand);
            MoveCoinTable         = new RelayCommandLight(MoveCoinTableCommand);
            CopyCoinTable         = new RelayCommandLight(CopyCoinTableCommand);
            AddCoin               = new RelayCommandLight(AddCoinCommand);
            DeleteCoin            = new RelayCommandLight(DeleteCoinCommand);
            Save                  = new RelayCommandLight(SaveCommand);
            Undo                  = new RelayCommandLight(UndoCommand);
            Redo                  = new RelayCommandLight(RedoCommand);
            CalculateProfit       = new RelayCommandLight(CalculateProfitCommand, CalculateProfit_CanExecute);
            Export                = new RelayCommandLight(ExportCommand, Export_CanExecute);
            SwitchManually        = new RelayCommandLight(SwitchManuallyCommand, SwitchManually_CanExecute);
            ApplyAutoSwitch       = new RelayCommandLight(ApplyAutoSwitchCommand);
            ApplyHistoryBackup    = new RelayCommandLight(ApplyHistoryBackupCommand);
            EditKillList          = new RelayCommandLight(EditKillListCommand);
            GenerateRandomPort    = new RelayCommandLight(GenerateRandomPortCommand);
            ApplyServerSettings   = new RelayCommandLight(ApplyServerSettingsCommand);
            TestConnection        = new RelayCommandLight(TestConnectionCommand, TestConnection_CanExecute);
            LoadHistoricalCharts  = new RelayCommandLight(LoadHistoricalChartsCommand, CalculateProfit_CanExecute);
            LineSeriesSelectAll   = new RelayCommandLight(LineSeriesSelectAllCommand);
            LineSeriesSelectNone  = new RelayCommandLight(LineSeriesSelectNoneCommand);
            ScanLan               = new RelayCommandLight(ScanLanCommand);
            ScanLanStop           = new RelayCommandLight(ScanLanStopCommand);
            ClearProfitTables     = new RelayCommandLight(ClearProfitTablesCommand);
            MassUpdateApplication = new RelayCommandLight(MassUpdateApplicationCommand);
            MassUpdateWorkers     = new RelayCommandLight(MassUpdateWorkersCommand);
            MassUpdateWtmSettings = new RelayCommandLight(MassUpdateWtmSettingsCommand);
            AddCoinsByAlgorithm   = new RelayCommandLight(AddCoinsByAlgorithmCommand);
            UpdateCoins           = new RelayCommandLight(UpdateCoinsCommand);
            AddComputers          = new RelayCommandLight(AddComputersCommand);
            CancelWaiting         = new RelayCommandLight(CancelWaitingCommand);
            EditPath              = new RelayCommandLight(EditPathCommand);
            OpenInExplorer        = new RelayCommandLight(OpenInExplorerCommand);
            SortBy                = new RelayCommandLight(SortByCommand);

            WorkersExpandAll   = new RelayCommandLight(WorkersExpandAllCommand);
            WorkersCollapseAll = new RelayCommandLight(WorkersCollapseAllCommand);
            WorkerSelectAll    = new RelayCommandLight(WorkerSelectAllCommand);
            WorkerSelectNone   = new RelayCommandLight(WorkerSelectNoneCommand);
            WorkerQueryAll     = new RelayCommandLight(WorkerQueryAllCommand);
            WorkerQueryNone    = new RelayCommandLight(WorkerQueryNoneCommand);

            About = new RelayCommandLight(AboutCommand);
            Exit  = new RelayCommandLight(ExitCommand);
            Test  = new RelayCommandLight(TestCommand);

            Instance = this;
        } // end ViewModel constructor
Esempio n. 20
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);
        }
Esempio n. 21
0
        private void RestoreState(UndoObject undoObject)
        {
            switch (undoObject.OperationType)
            {
            case UndoOperationType.WorkerEdit:
                Workers.WorkerListReplaceItem(undoObject.Index, ((Worker)undoObject.Data).Clone());
                break;

            case UndoOperationType.WorkersPowerCost:
                Workers.PowerCost = (double)undoObject.Data;
                break;

            case UndoOperationType.WorkersCoinType:
                Workers.CoinType = (string)undoObject.Data;
                break;

            case UndoOperationType.WorkersDisplayCoinAs:
                Workers.DisplayCoinAs = (string)undoObject.Data;
                break;

            case UndoOperationType.WorkerAdd:
                Workers.WorkerListRemoveAt(Workers.WorkerList.Count - 1);
                break;

            case UndoOperationType.WorkerAddRange:
                Workers.WorkerListRemoveRangeAt(undoObject.Index, (int)undoObject.Data);
                break;

            case UndoOperationType.WorkerInsert:
                Workers.WorkerListRemoveAt(undoObject.Index);
                break;

            case UndoOperationType.WorkerRemove:
                Workers.WorkerListInsert(undoObject.Index, ((Worker)undoObject.Data).Clone());
                break;

            case UndoOperationType.WorkerRemoveRange:
                Workers.WorkerListAddRangeAt((ObservableCollection <Worker>)undoObject.Data, undoObject.Index);
                break;

            case UndoOperationType.WorkerMove:
                Workers.WorkerListMove((int)undoObject.Data, undoObject.Index);
                break;

            case UndoOperationType.SettingsEdit:
                UnHookUpWmtSettingsPropertyChangeEvents();
                SaveUndoRedo("WtmSettings");
                var  wtms = ((WtmSettingsObject)undoObject.Data).Clone();
                bool switchTimeFromEqual    = WtmSwitchTimeFromStored.Equals(wtms.SwitchTimeFrom);
                bool switchTimeToEqual      = WtmSwitchTimeToStored.Equals(wtms.SwitchTimeTo);
                bool historicalAverageEqual = WtmHistoricalAveragePeriodStored == wtms.HistoricalAveragePeriod;
                bool historyTimeFromEqual   = WtmHistoryTimeFromStored.Equals(wtms.HistoryTimeFrom);
                bool historyTimeToEqual     = WtmHistoryTimeToStored.Equals(wtms.HistoryTimeTo);
                WtmSettings = wtms;
                HookUpWmtSettingsPropertyChangeEvents();
                if (WtmSettings.AutoSwitch)
                {
                    SwitchTimeIsUpdated = false;
                }
                if (WtmSettings.BackupHistoricalPrices)
                {
                    HistoryTimeIsUpdated = false;
                }
                WtmSettings.ServerSettingsAreUpdated = true;
                break;

            case UndoOperationType.WorkersAll:
                SaveUndoRedo("WorkersAll");
                var allWorkers = undoObject.Data as ObservableCollection <Worker>;
                Workers.WorkerList.Clear();
                foreach (var worker in allWorkers)
                {
                    Workers.WorkerList.Add(worker.Clone());
                }
                break;
            }
        }
Esempio n. 22
0
        private bool Ok_CanExecute(object obj)
        {
            var firstCheck = Workers.FirstOrDefault(x => x.Query);

            return(firstCheck != null ? true : false);
        }
Esempio n. 23
0
        private async void ImportWorkersCommand(object parameter)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "JSON file|*.json";
            var openFileDialogResult = openFileDialog.ShowDialog();

            if (openFileDialogResult == false || string.IsNullOrEmpty(openFileDialog.FileName))
            {
                return;
            }

            string workersContent = null;
            ObservableCollection <Worker> convertedWorkers = null;

            try { workersContent = System.IO.File.ReadAllText(openFileDialog.FileName); }
            catch
            {
                await Task.Delay(100);

                MessageBox.Show($"There was an error while reading from \"{openFileDialog.FileName}\"", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            convertedWorkers = JsonConverter.ConvertFromJson <ObservableCollection <Worker> >(workersContent, false);
            if (convertedWorkers == null || convertedWorkers.Count == 0)
            {
                await Task.Delay(100);

                Helpers.ShowErrorMessage($"Failed to intepret JSON information from \"{openFileDialog.FileName}\"", "Error");
                return;
            }

            var window = new SelectWorkers();

            window.SizeToContent = SizeToContent.WidthAndHeight;
            var vm = new SelectWorkersVM();

            vm.Workers = convertedWorkers;
            foreach (var worker in vm.Workers)
            {
                worker.Query = true;
            }
            window.DataContext = vm;
            vm.Title           = "Import Workers";
            vm.ButtonTitle     = "Import";
            var dialogResult = window.ShowDialog();

            if (dialogResult == false)
            {
                return;
            }

            var selectedWorkers = vm.Workers.Where(x => x.Query).ToList();

            if (selectedWorkers == null || selectedWorkers.Count == 0)
            {
                return;
            }

            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            Workers.WorkerListAddRangeAt(selectedWorkers, workerIndex);
        }
Esempio n. 24
0
        private async void UpdateCommand(object obj)
        {
            UpdateIsInProgress = true;

            var workersDate     = Workers.GetWorkersLastUpdateTime();
            var wtmSettingsDate = WtmSettingsObject.GetWtmSettingsLastUpdateTime();

            UpdateCancelSource = new CancellationTokenSource();
            var token = UpdateCancelSource.Token;

            var          taskList   = new List <Task>();
            var          failList   = new List <ProfitTable>();
            FlowDocument report     = new FlowDocument();
            int          errorCount = 0;

            string appVersion = Helpers.ApplicationVersion();

            var jobCount = Computers.Count;

            ReportTitle = $"Progress: 0 of {jobCount}.";
            for (int i = 0; i < jobCount; i++)
            {
                var pc = Computers[i];
                if (!pc.Switch)
                {
                    continue;
                }
                Task task = null;
                switch (ColumnHeader)
                {
                case "Version":
                    task = Task.Run(async() => { errorCount = await UpdateVersion(pc, token, errorCount, i, jobCount, appVersion); });
                    break;

                case "Workers Date":
                    task = Task.Run(async() => { errorCount = await UpdateWorkers(pc, token, errorCount, i, jobCount, workersDate); });
                    break;

                case "Settings Date":
                    task = Task.Run(async() => { errorCount = await UpdateWtmSettings(pc, token, errorCount, i, jobCount, wtmSettingsDate); });
                    break;
                }
                taskList.Add(task);
            }

            await Task.WhenAll(taskList);

            if (errorCount == 0)
            {
                ReportTitle = "Report:";
                var paragraph = new Paragraph();
                paragraph.Inlines.Add(new Run("Operation has finished successfully."));
                NewParagraph = paragraph;
            }
            else
            {
                ReportTitle = "Error report:";
            }

            UpdateIsInProgress = false;
            UpdateIsFinished   = true;
        }
Esempio n. 25
0
        public Task <DateTime> GetWorkersDateAsync()
        {
            DateTime updateTime = Workers.GetWorkersLastUpdateTime();

            return(Task.FromResult(updateTime));
        }