public void Service_IsActive_property() { var file = "../../../Stocks.Service/companyData.json"; var configurationService = new ConfigurationService(file); using (var webClientShim = new WebClientShim(new WebClient())) { var service = new StocksService( configurationService, webClientShim); Assert.Equal(false, service.IsActive); using (var task = Task.Factory.StartNew(() => { service.Start(); Assert.Equal(true, service.IsActive); using (var task2 = Task.Factory.StartNew(() => Thread.Sleep(50))) { task2.Wait(); } service.Stop(); Assert.Equal(false, service.IsActive); })) { task.Wait(); } } }
public void AddBondTest() { var service = new StocksService(); var stock = new Bond() { Price = 50000, Quantity = 3 }; var newStockId = service.AddStock(stock); var newStock = service.GetStock(newStockId); Assert.IsNotNull(newStock); Assert.AreEqual(stock.Price, newStock.Price); Assert.AreEqual(stock.Quantity, newStock.Quantity); }
public void DeleteEquityTest() { var service = new StocksService(); var stock = new Equity() { Price = 50000, Quantity = 3 }; var newStockId = service.AddStock(stock); var newStock = service.GetStock(newStockId); Assert.IsNotNull(newStock); service.DeleteStock(newStock.Id); newStock = service.GetStock(newStockId); Assert.IsNull(newStock); }
public void ShouldNotRegisterNewStockIfItExists() { //Arrange var stockTableRepository = Substitute.For<IStockTableRepository>(); StocksService stockService = new StocksService(stockTableRepository); StockRegistrationInfo args = new StockRegistrationInfo(); args.Type = "StockTypeA"; args.Price = 10; //Act stockService.RegisterNewStock(args); stockTableRepository.Contains(Arg.Is<StockEntity>(w => w.Type == args.Type && w.Price == args.Price)).Returns(true); stockService.RegisterNewStock(args); }
public void ShouldRegisterNewStock() { //Arrange var stockTableRepository = Substitute.For<IStockTableRepository>(); StocksService stockService = new StocksService(stockTableRepository); StockRegistrationInfo args = new StockRegistrationInfo(); args.Type = "StockTypeA"; args.Price = 10; //Act var stockId = stockService.RegisterNewStock(args); //Assert stockTableRepository.Received(1).Add(Arg.Is<StockEntity>(w => w.Type == args.Type && w.Price == args.Price)); stockTableRepository.Received(1).SaveChanges(); }
static void SetUpData() { _stockRepository.Add(new StockCommon("TEA", 100, 0, 100)); _stockRepository.Add(new StockCommon("POP", 100, 8, 100)); _stockRepository.Add(new StockCommon("ALE", 60, 23, 60)); _stockRepository.Add(new StockPreferred("GIN", 100, 8, 100, 2)); _stockRepository.Add(new StockCommon("JOE", 250, 13, 250)); _stockService = new StocksService(_stockRepository); _tradeRepository.Add(new Trade(new StockCommon("TEA", 100, 0, 100), DateTime.Now.AddMinutes(-5), 3, Trade.TradeType.Buy, 23)); _tradeRepository.Add(new Trade(new StockCommon("TEA", 100, 0, 100), DateTime.Now.AddMinutes(5), 3, Trade.TradeType.Buy, 33)); _tradeRepository.Add(new Trade(new StockCommon("POP", 100, 8, 100), DateTime.UtcNow.AddMinutes(-5), 4, Trade.TradeType.Buy, 33)); _tradeRepository.Add(new Trade(new StockCommon("ALE", 60, 23, 60), DateTime.UtcNow.AddMinutes(-1), 5, Trade.TradeType.Buy, 23)); _tradeRepository.Add(new Trade(new StockPreferred("GIN", 100, 8, 100, 2), DateTime.UtcNow.AddMinutes(-1), 6, Trade.TradeType.Buy, 23)); _tradeRepository.Add(new Trade(new StockCommon("JOE", 250, 13, 250), DateTime.UtcNow.AddMinutes(-1), 7, Trade.TradeType.Buy, 23)); _tradeService = new TradeService(_tradeRepository); }
private async Task ProcessStocksOnArrival() { try { var tickers = Ticker.Text.Split(',', ' '); var service = new StocksService(); var stocks = new ConcurrentBag <StockPrice>(); var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >(); foreach (var ticker in tickers) { var loadtask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token) .ContinueWith(t => { foreach (var stock in t.Result.Take(5)) { // stocks collection can be safely used with different threads stocks.Add(stock); } Dispatcher.Invoke(() => { Stocks.ItemsSource = stocks.ToArray(); }); return(t.Result); }); tickerLoadingTasks.Add(loadtask); } await Task.WhenAll(tickerLoadingTasks); } catch (Exception ex) { Notes.Text += ex.Message + Environment.NewLine; } finally { cancellationTokenSource = null; } }
public void GetStocksTest() { var service = new StocksService(); var stock = new Equity() { Price = 50000, Quantity = 3 }; var stock1 = new Equity() { Price = 50000, Quantity = 3 }; var newStockId = service.AddStock(stock); var newStock1Id = service.AddStock(stock1); var stocks = service.GetStocks(); Assert.IsTrue(stocks.Any(s => s.Id == newStockId)); Assert.IsTrue(stocks.Any(s => s.Id == newStock1Id)); }
public void EquityNameIsInctementedTest() { var service = new StocksService(); var stock = new Equity() { Price = 50000, Quantity = 3 }; var stock1 = new Equity() { Price = 50000, Quantity = 3 }; var newStockId = service.AddStock(stock); var newStock = service.GetStock(newStockId); var newStock1Id = service.AddStock(stock1); var newStock1 = service.GetStock(newStock1Id); var numericPart1 = Convert.ToInt32(Regex.Match(newStock.Name, @"\d+").Value); var numericPart2 = Convert.ToInt32(Regex.Match(newStock1.Name, @"\d+").Value); Assert.IsTrue(numericPart2 - numericPart1 == 1); }
public BuyController(StocksService stocksService, CurrentUserService currentUserService) { _stocksService = stocksService ?? throw new ArgumentNullException(nameof(stocksService)); _currentUserService = currentUserService ?? throw new ArgumentNullException(nameof(currentUserService)); }
public StocksController(StocksService stocksService) { _stocksService = stocksService ?? throw new ArgumentNullException(nameof(stocksService)); }
public CompaniesController(FinnhubClient client, StocksService stocksService) { _client = client; _stocksService = stocksService; }
private async void Search_Click(object sender, RoutedEventArgs e) { #region Before loading stock data var watch = new Stopwatch(); watch.Start(); StockProgress.Visibility = Visibility.Visible; StockProgress.IsIndeterminate = true; Search.Content = "Cancel"; #endregion #region Cancellation if (cancellationTokenSource != null) { cancellationTokenSource.Cancel(); cancellationTokenSource = null; return; } cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Token.Register(() => { Notes.Text += "Cancellation requested" + Environment.NewLine; }); #endregion try { #region Load One or Many Tickers var tickers = Ticker.Text.Split(',', ' '); var service = new StocksService(); var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >(); foreach (var ticker in tickers) { var loadTask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token); tickerLoadingTasks.Add(loadTask); } #endregion // Stocks loaded - now need processing var loadedStocks = await Task.WhenAll(tickerLoadingTasks); // Use threadsafe collection var values = new ConcurrentBag <StockCalculation>(); // Standard foreach loop converted into a Parallel foreach // Includes guidance on max number of concurrent tasks var exResult = Parallel.ForEach(loadedStocks, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (stocks, state) => { var stockName = stocks.First().Ticker; // Will break out of current thread // Will not execute outstanding iterations // On-going tasks will not be stopped // return - explicitly return from current thread context if (stockName == "MBI") { state.Break(); return; } var result = CalculateExpensiveComputation(stocks); var data = new StockCalculation { Ticker = stocks.First().Ticker, Result = result }; values.Add(data); }); if (exResult.IsCompleted) { Stocks.ItemsSource = values; } else { Notes.Text = "Parallel computation of stocks did not complete successfully"; } // Calculate total stock price for each ticker decimal totalStocksValue = 0; exResult = Parallel.For(0, loadedStocks.Length, i => { var value = 0m; foreach (var s in loadedStocks[i]) { // 1. Unstable: totalStocksValue += Compute(s); // 2. Fix, but limited solution: // Interlocked.Add(ref totalStocksValue, (int)Compute(s)); // 3. Minimise code inside lock value += Compute(s); } lock (syncRoot) { totalStocksValue += value; } }); Notes.Text = $"Stock price total: {totalStocksValue:N2}"; } catch (Exception ex) { Notes.Text += ex.Message + Environment.NewLine; } finally { cancellationTokenSource = null; } #region After stock data is loaded StocksStatus.Text = $"Loaded stocks for {Ticker.Text} in {watch.ElapsedMilliseconds}ms"; StockProgress.Visibility = Visibility.Hidden; Search.Content = "Search"; #endregion }
public StockServiceTest() { stockService = new StocksService(); }
public StockViewModel(StocksService.Stock stock) { _Stock = stock; }