Beispiel #1
0
        public IHttpActionResult PostStock(string stockSymbol)
        {
            Stock stock = null;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!db.Stocks.Any(s => s.Symbol == stockSymbol))
            {
                try
                {
                    stock = DataFetcher.GetStockQuote(stockSymbol);
                }
                catch (Exception)
                {
                    return(Content(HttpStatusCode.BadRequest, "Stock symbol not found."));
                }

                db.Stocks.Add(stock);
                db.SaveChanges();
            }
            else
            {
                return(Content(HttpStatusCode.BadRequest, "The stock you are trying to add is already in the list."));
            }

            return(CreatedAtRoute("DefaultApi", new { id = stock.ID }, stock));
        }
Beispiel #2
0
        // GET: api/Stocks
        public List <Stock> GetStocks(bool forceRefresh)
        {
            List <Stock> result = new List <Stock>();

            List <Stock> stocks = db.Stocks.ToList();

            ApplicationDbContext stockPriceContext = new ApplicationDbContext();

            StockPrice stockPrice = null;

            foreach (var stock in stocks)
            {
                stockPrice = stockPriceContext.StockPrices.Where(s => s.StockID == stock.ID).OrderByDescending(s => s.Created).First();

                if ((stockPrice == null || stockPrice.Created < DateTime.Now.AddHours(-1)) || forceRefresh)
                {
                    try
                    {
                        stockPrice = DataFetcher.GetStockQuote(stock.Symbol).StockPrices.FirstOrDefault();
                    }
                    catch (Exception)
                    {
                    }
                    stockPrice.StockID = stock.ID;
                    stockPriceContext.StockPrices.Add(stockPrice);
                }

                stockPrice.CalculateValues();

                if (stock.StockPrices.Count > 0)
                {
                    stock.StockPrices.Clear();
                    stock.StockPrices.Add(stockPrice);
                }
                result.Add(stock);
            }

            stockPriceContext.SaveChanges();

            return(result.OrderBy(res => res.Name).ToList());
        }