public string ProcessLink(string link, int recursionLevel, string startingUrl, object storageLock)
        {
            Uri    uri          = new Uri(startingUrl);
            string completeLink = uri.Scheme + @":\\" + new Uri(startingUrl).Authority + @"/" + link;
            bool   isNewValue   = false;

            lock (storageLock)
            {
                if (!storageProvider.Contains(completeLink))
                {
                    outputProvider.WriteLine(completeLink + " " + (recursionLevel + 1).ToString());
                    storageProvider.TryAdd(completeLink, recursionLevel + 1);
                    isNewValue = true;
                }
            }

            if (isNewValue)
            {
                return(completeLink);
            }
            else
            {
                return(null);
            }
        }
示例#2
0
        /// <summary>
        /// Method returns a list of blocks since a specified datetime.
        /// </summary>
        /// <param name="datapath">Path to blockchain files.</param>
        /// <param name="fromDate">Date used to filter blocks.</param>
        /// <param name="outputProvider">Output handler type - CSV file or console.</param>
        public void GetBlocks(string datapath, DateTime fromDate, IOutputProvider outputProvider)
        {
            ConcurrentDictionary <uint256, bool> check = new ConcurrentDictionary <uint256, bool>();

            Action <StoredBlock, Transaction> callback = (block, transaction) => {
                if (!check.ContainsKey(block.Item.GetHash()) && block.Item.Header.BlockTime.DateTime.Date >= fromDate.Date)
                {
                    check[block.Item.GetHash()] = true;

                    string[] message = new string[4];
                    message[0] = "";
                    message[1] = block.Item.GetHash().ToString();
                    message[2] = String.Format("{0} {1}", block.Item.Header.BlockTime.DateTime.ToShortDateString(), block.Item.Header.BlockTime.DateTime.ToShortTimeString());
                    message[3] = block.Item.Transactions.Count.ToString();
                    outputProvider.WriteLine(message);
                }
            };
            Thread queueThread = new Thread(() => {
                WatchQueue();
            });
            Thread runnerThread = new Thread(() =>
            {
                Runner(datapath, callback);
            });

            runnerThread.Start();
            queueThread.Start();
            runnerThread.Join();
            queueThread.Join();
        }
        void GetStartingUrl()
        {
            string inputString = string.Empty;
            bool   inputCheck  = true;
            Uri    uriResult;

            outputProvider.WriteLine("Please enter URL");
            do
            {
                inputString = inputProvider.ReadLine();
                inputCheck  = Uri.TryCreate(inputString, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

                if (inputCheck == false)
                {
                    outputProvider.WriteLine("Incorrect URL format");
                    outputProvider.WriteLine("Please enter avsolute URL");
                }
            }while (inputCheck == false);

            startingUrl = inputString;
        }
示例#4
0
        /// <summary>
        /// Method returns a list of transactions (including unconfirmed transactions) of a specified address.
        /// </summary>
        /// <param name="datapath">Path to blockchain files.</param>
        /// <param name="address">Hex string of address used as filter. </param>
        /// <param name="outputProvider">Output handler type - CSV file or console.</param>
        public void GetAddressTransactions(string datapath, string address, IOutputProvider outputProvider)
        {
            ConcurrentDictionary <uint256, bool> transactions = new ConcurrentDictionary <uint256, bool>();
            Action <StoredBlock, Transaction>    callback     = (block, transaction) => {
                if (transaction.Inputs.Exists(i => String.Format("{0}", i.ScriptSig.GetDestinationAddress(Network.Main)) == address))
                {
                    transactions[transaction.Inputs.Where(i => String.Format("{0}", i.ScriptSig.GetDestinationAddress(Network.Main)) == address).Select(i => i.PrevOut.Hash).First()] = true;
                }
                if (transaction.Outputs.Exists(o => String.Format("{0}", o.ScriptPubKey.GetDestinationAddress(Network.Main)) == address))
                {
                    transactions[transaction.GetHash()] = true;
                }
            };

            Thread queueThread = new Thread(() => {
                WatchQueue();
            });
            Thread runnerThread = new Thread(() =>
            {
                Runner(datapath, callback);
            });
            Thread indexerThread = new Thread(() =>
            {
                PrepareIndex(datapath);
            });

            indexerThread.Start();
            runnerThread.Start();
            queueThread.Start();
            runnerThread.Join();
            queueThread.Join();
            indexerThread.Join();

            var dbPath    = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "bcquery");
            var dbOptions = new Options();

            dbOptions.CreateIfMissing = true;
            dbOptions.Compression     = CompressionType.SnappyCompression;

            using (DB storage = DB.Open(dbPath, dbOptions))
            {
                foreach (var txhash in transactions.Keys)
                {
                    var blockhash   = new uint256(storage.Get(ReadOptions.Default, txhash.ToBytes()).ToArray());
                    var transaction = index.Get(blockhash).Transactions.Where(tx => tx.GetHash() == txhash).Select(tx => tx).First();
                    foreach (var input in transaction.Inputs)
                    {
                        if (input.PrevOut.Hash != uint256.Zero)
                        {
                            Block    tempBlock = index.Get(new uint256(storage.Get(ReadOptions.Default, input.PrevOut.Hash.ToBytes()).ToArray()));
                            Money    btcAmount = tempBlock.Transactions.Where(tx => tx.GetHash() == input.PrevOut.Hash).SelectMany(tx => tx.Outputs).ToArray()[input.PrevOut.N].Value;
                            string[] message   = new string[6];
                            message[0] = transaction.GetHash().ToString();
                            message[1] = System.Text.Encoding.UTF8.GetString(storage.Get(ReadOptions.Default, tempBlock.GetHash().ToBytes()).ToArray());
                            message[2] = "INPUT";
                            message[3] = String.Format("{0}", input.ScriptSig.GetDestinationAddress(Network.Main));
                            message[3] = message[3].Trim().Length == 0 ? "<NOT IDENTIFIED>" : message[3];
                            message[4] = input.PrevOut.Hash.ToString();
                            message[5] = btcAmount.ToString();
                            outputProvider.WriteLine(message);
                        }
                    }
                    foreach (var output in transaction.Outputs)
                    {
                        string[] message = new string[6];
                        message[0] = transaction.GetHash().ToString();
                        message[1] = System.Text.Encoding.UTF8.GetString(storage.Get(ReadOptions.Default, blockhash.ToBytes()).ToArray());
                        message[2] = "OUTPUT";
                        message[3] = String.Format("{0}", output.ScriptPubKey.GetDestinationAddress(Network.Main));
                        message[3] = message[3].Trim().Length == 0 ? "<NOT IDENTIFIED>" : message[3];
                        message[4] = transaction.GetHash().ToString();
                        message[5] = output.Value.ToString();
                        outputProvider.WriteLine(message);
                    }
                }
            }
        }
示例#5
0
        public void StartGame(Snake snake, Board board)
        {
            // Customize Snake
            snake = CustomizeSnake();

            // set the snake in the middle of the board
            snake.XPosition = board.Boardwidth / 2;
            snake.YPosition = board.Boardheight / 2;

            // set defaults
            //game is in play, no history of moves, snake length is 1 and game speed is 75
            IsGameOver = false;
            DidHitWall = false;
            Eaten      = new Dictionary <string, bool>();
            int GameSpeed = 75;

            snake.Length = 1;

            //do not show the cursor and initialize a variable for key input
            Console.CursorVisible = false;
            ConsoleKeyInfo command;

            while (!IsGameOver)
            {
                // clear the console, set the title bar, and draw the board
                outputProvider.Clear();
                outputProvider.CreateTitle(Message.Instructions);
                board.DrawBoard();

                //clear move history, and add current position, then draw the snake
                Eaten.Clear();
                Eaten.Add(snake.XPosition.ToString() + snake.YPosition.ToString(), true);
                snake.DrawSnake();

                //wait for the player to move
                WaitForMove();

                //set the speed by checking for keystrokes at the gamespeed in miliseconds
                DateTime nextCheck = DateTime.Now.AddMilliseconds(GameSpeed);

                while (!IsGameOver && !DidHitWall)
                {
                    //Display the length at the top of the screen
                    outputProvider.CreateTitle(Message.Score + snake.Length.ToString());

                    //wait for the next time you can check for keys
                    while (nextCheck > DateTime.Now)
                    {
                        // see if the player has changed direction
                        if (Console.KeyAvailable)
                        {
                            //read the key and map it to a direction
                            command = Console.ReadKey(true);
                            MapCommandToDirection(command);
                        }
                    }

                    if (!IsGameOver)
                    {
                        ChangeDirection(snake, board);

                        if (!DidHitWall)
                        {
                            //format the current positions to two rounded digits
                            string positions = snake.XPosition.ToString("00") + snake.YPosition.ToString("00");
                            //if the snake hasn't been to the current positions, add the length and keep going
                            if (!Eaten.ContainsKey(positions))
                            {
                                snake.Length++;
                                Eaten.Add(positions, true);
                                snake.DrawSnake();
                            }
                            //otherwise say they hit the wall
                            else
                            {
                                DidHitWall = true;
                            }
                        }

                        nextCheck = DateTime.Now.AddMilliseconds(GameSpeed);
                    }
                }

                if (DidHitWall)
                {
                    outputProvider.CreateTitle(Message.You_Died + snake.Length.ToString());
                    SetConsoleToDefault();
                    outputProvider.WriteLine(Message.SkullArt);
                    JustWait();
                    IsGameOver = true;
                }
            }
            if (IsGameOver)
            {
                SetConsoleToDefault();
                outputProvider.CreateTitle(Message.Youre_Done + snake.Length.ToString());
                outputProvider.Write(Message.SnakeArt);
                JustWait();
            }
        }
示例#6
0
        /// <summary>
        /// Create Players from input provider
        /// </summary>
        private void createPlayersForTable()
        {
            outputProvider.Write("How many players: ");
            var numsPlayer = 1;

            int.TryParse(inputProvider.Read(), out numsPlayer);

            if (numsPlayer <= 0)
            {
                numsPlayer = 1;
                outputProvider.WriteLine();
                outputProvider.WriteLine($"Defaulting to {numsPlayer} players");
            }


            this.players = new List <IPlayer>();
            for (int i = 0; i < numsPlayer; i++)
            {
                var name = GetName();
                this.players.Add(new HumanPlayer(name));
            }

            this.table.Players = this.players as IEnumerable <IPlayer>;
        }
示例#7
0
        public void UpdateDatabase(IDataInteraction dataProvider, IOutputProvider outputProvider, ILogger logger, int sellerId, int buyerId, int shareId, decimal sharePrice, int purchaseQuantity)
        {
            try
            {
                if (sellerId == 0 || buyerId == 0 || shareId == 0 || sharePrice == 0 || purchaseQuantity == 0)
                {
                    logger.Write("Incorrect data from randomizer");
                    throw new Exception("Incorrect data from randomizer");
                }

                var sellerToChange = dataProvider.GetTrader(sellerId);

                if (sellerToChange != null)
                {
                    sellerToChange.Balance += sharePrice * purchaseQuantity;
                }

                var buyerToChange = dataProvider.GetTrader(buyerId);

                if (buyerToChange != null)
                {
                    buyerToChange.Balance -= sharePrice * purchaseQuantity;
                }

                var sellerShareRecordToChange = dataProvider.GetPortfolio(sellerId, shareId);

                if (sellerShareRecordToChange != null)
                {
                    sellerShareRecordToChange.Quantity -= purchaseQuantity;

                    if (sellerShareRecordToChange.Quantity == 0)
                    {
#if DEBUG
                        outputProvider.WriteLine("Removed share record with 0 quantity");
#endif
                        logger.Write("Removed share record with 0 quantity");

                        dataProvider.RemovePortfolio(sellerShareRecordToChange);
                    }
                }

                if (dataProvider.GetPortfoliosCount(buyerId, shareId) > 0)
                {
                    var buyerShareRecordToChange = dataProvider.GetPortfolio(buyerId, shareId);

                    if (buyerShareRecordToChange != null)
                    {
                        buyerShareRecordToChange.Quantity += purchaseQuantity;
                    }
                }
                else
                {
#if DEBUG
                    outputProvider.WriteLine("Add new record to portfolio");
#endif
                    logger.Write("Add new record to portfolio");

                    dataProvider.AddPortfolio(buyerId, shareId, purchaseQuantity);
                }

                var transaction = dataProvider.AddTransaction(buyerId, sellerId, shareId, sharePrice, purchaseQuantity);

                dataProvider.SaveChanges();

                string message = "Buyer = " + transaction.BuyerId + " Seller = " + transaction.SellerId + " Share name = " + transaction.ShareId +
                                 " Quantity = " + transaction.Quantity + " Price per share = " + transaction.PricePerShare +
                                 " Transaction total = " + transaction.PricePerShare * transaction.Quantity + " Timestamp = " + transaction.DateTime;

                outputProvider.WriteLine(message);
                logger.Write(message);
            }
            catch (Exception e)
            {
                outputProvider.WriteLine(e.Message);
                logger.Write(e.Message);
            }
        }
示例#8
0
        PerformRandomOperation(IDataInteraction dataProvider, IOutputProvider outputProvider, ILogger logger)
        {
            int     sellerId;
            int     buyerId;
            int     shareId;
            decimal sharePrice;
            int     purchaseQuantity;

            try
            {
                int numberOfTraders = dataProvider.GetNumberOfTraders();

                if (numberOfTraders > 1)
                {
                    List <int> availableSellers = dataProvider.GetAvailableSellers();

                    if (availableSellers.Count > 0)
                    {
                        sellerId = availableSellers[new Random().Next(0, availableSellers.Count)];
                    }
                    else
                    {
                        throw new Exception("No traders with shares");
                    }

                    buyerId = new Random().Next(1, numberOfTraders + 1);

                    while (sellerId == buyerId)
                    {
                        buyerId = new Random().Next(1, numberOfTraders + 1);
                    }

                    if (buyerId == sellerId)
                    {
                        throw new Exception("buyerId == sellerId");
                    }
                }
                else
                {
                    throw new Exception("Not enough traders for a transaction");
                }

                List <int> availableShares = dataProvider.GetAvailableShares(sellerId);
#if DEBUG
                outputProvider.WriteLine("Available shares types = " + availableShares.Count);
#endif
                logger.Write("Available shares types = " + availableShares.Count);

                shareId          = availableShares[new Random().Next(0, availableShares.Count)];
                sharePrice       = dataProvider.GetSharePrice(shareId);
                purchaseQuantity = new Random().Next(1, dataProvider.GetShareQuantityFromPortfoio(sellerId, shareId) + 1);

                return(sellerId, buyerId, shareId, sharePrice, purchaseQuantity);

                //UpdateDatabase(dataProvider, outputProvider, logger, sellerId, buyerId, shareId, sharePrice, purchaseQuantity);
            }
            catch (Exception e)
            {
                outputProvider.WriteLine(e.Message);
                logger.Write(e.Message);
            }

            return(0, 0, 0, 0M, 0);
        }