コード例 #1
0
        public async Task <ActionResult> Buy(BuyModel model)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("https://cloud-sse.iexapis.com");
                    var response = await client.GetAsync($"/stable/stock/{model.Symbol}/quote?token=pk_f7b30f305a8c4aef8eaec49711a8344e");

                    response.EnsureSuccessStatusCode();

                    var stringResult = await response.Content.ReadAsStringAsync();

                    var    rawShare = JsonConvert.DeserializeObject <Bought>(stringResult);
                    string userId   = User.Claims.First(c => c.Type == "Id").Value;
                    var    user     = db.ApplicationUsers.Where(au => au.Id == userId).ToList();

                    double        total  = 0;
                    List <Bought> shares = db.Boughts.Where(s => s.AspNetUserId == userId).Where(s => s.IsOwned == true).ToList();
                    foreach (Bought item in shares)
                    {
                        total += (item.latestPrice * item.NumOfShare);
                    }

                    double cash = user[0].Fund - total;

                    double cost = rawShare.latestPrice * model.Share;

                    if (cash >= cost)
                    {
                        DateTime date = DateTime.Now;

                        Bought share = new Bought
                        {
                            TransactionType = "Buy",
                            DateAndTime     = date,
                            Symbol          = model.Symbol.ToUpper(),
                            companyName     = rawShare.companyName,
                            latestPrice     = rawShare.latestPrice,
                            NumOfShare      = model.Share,
                            IsOwned         = true,
                            AspNetUserId    = userId
                        };


                        db.Boughts.Add(share);
                        await db.SaveChangesAsync();

                        string message = "Bought";
                        return(Ok(new { message }));
                    }
                    string errorMessage = "Failed. Total cost exceeds your available cash.";
                    return(BadRequest(new { errorMessage }));
                }
                catch (HttpRequestException httpRequestException)
                {
                    return(BadRequest(new { httpRequestException.Message }));
                }
            }
        }
コード例 #2
0
 public async Task <int> SaveChanges()
 {
     return(await Db.SaveChangesAsync());
 }