public IActionResult WatchlistAdd(AllStockViewModels s) { int?id = HttpContext.Session.GetInt32("LoggedUserId"); if (id == null) { return(RedirectToAction("Index", "User")); } // Get the User object based on the id stored in session. User User = _context.Users.SingleOrDefault(u => u.Id == (int)id); // Get the Watchlist and Stocks of the user. Watchlist Watchlist = _context.Watchlists .Include(w => w.Stocks) .SingleOrDefault(p => p.User == User); if (ModelState.IsValid) { try { Dictionary <string, object> Data = new Dictionary <string, object>(); // Make a API call to ensure that the inputted ticker/symbol is a valid one before storing it in user's list of Stocks. WebRequest.GetQuote(s.WatchlistStockViewModel.Symbol, JsonResponse => { Data = JsonResponse; } ).Wait(); Stock NewStock = new Stock { Symbol = s.WatchlistStockViewModel.Symbol, Name = (string)Data["companyName"], CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, }; Watchlist.Stocks.Add(NewStock); _context.Add(NewStock); _context.SaveChanges(); return(RedirectToAction("Watchlist")); } // Catch will run if the ticker/symbol submitted was not found in the DB. catch { // Return reason for error TempData["NewStockError"] = "That stock does not exist in our database. Please try again."; return(RedirectToAction("Watchlist")); } } // If ModelState is invalid, return View with validation errors and also make API call to retrieve proper data to display (Stock data, place User in viewbag, place error in ViewBag) // For each Stock in Portfolio, call API based on values in database // Also, populate Stocks list for later use in ViewBag ViewBag.Total = 0; foreach (Stock Stock in Watchlist.Stocks) { // Create a Dictionary object to store JSON values from API call Dictionary <string, object> Data = new Dictionary <string, object>(); // Make API call WebRequest.GetQuote(Stock.Symbol, JsonResponse => { Data = JsonResponse; } ).Wait(); // Define values for each stock to be stored in ViewBag double CurrentPrice = Convert.ToDouble(Data["latestPrice"]); Stock.Name = (string)Data["companyName"]; Stock.PurchaseValue = Stock.PurchasePrice * Stock.Shares; Stock.CurrentPrice = CurrentPrice; Stock.CurrentValue = CurrentPrice * Stock.Shares; Stock.GainLossPrice = CurrentPrice - Stock.PurchasePrice; Stock.GainLossValue = (CurrentPrice - Stock.PurchasePrice) * Stock.Shares; Stock.GainLossPercent = 100 * (CurrentPrice - Stock.PurchasePrice) / (Stock.PurchasePrice); Stock.Week52Low = Convert.ToDouble(Data["week52Low"]); Stock.Week52High = Convert.ToDouble(Data["week52High"]); Stock.UpdatedAt = DateTime.Now; _context.SaveChanges(); ViewBag.Total += Stock.CurrentValue; } // Store values in ViewBag for Portfolio page rendering ViewBag.Watchlist = Watchlist; ViewBag.User = User; return(View("Watchlist")); }
public IActionResult NewUser(AllUserViewModels model) { // Check if models received any validation errors. if (ModelState.IsValid) { try { // Check if email already exists in DB. var EmailExists = _context.Users.Where(e => e.Email == model.Reg.Email).SingleOrDefault(); // If email is unique, perform registration. if (EmailExists == null) { // Hash and store password in DB. PasswordHasher <RegisterViewModel> Hasher = new PasswordHasher <RegisterViewModel>(); string HashedPassword = Hasher.HashPassword(model.Reg, model.Reg.Password); User NewUser = new User { FirstName = model.Reg.FirstName, LastName = model.Reg.LastName, Email = model.Reg.Email, Password = HashedPassword, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, }; Portfolio Portfolio = new Portfolio { User = NewUser, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, }; Watchlist Watchlist = new Watchlist { User = NewUser, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, }; _context.Add(NewUser); _context.Add(Portfolio); _context.Add(Watchlist); _context.SaveChanges(); // Set user id in session for use in identification, future db calls, and for greeting the user. HttpContext.Session.SetInt32("LoggedUserId", NewUser.Id); // Redirect to Profile method. return(RedirectToAction("Profile")); } // Redirect w/ error if email already exists in db. else { ViewBag.email = "That email is already in use. Please try again using a different one."; MostActiveStocksAPICall(); return(View("landing")); } } // Catch should only run if there was an error with the password hashing or storing on the new user in the DB. catch { MostActiveStocksAPICall(); return(View("landing")); } } // Else statement will run if the ModelState is invalid. else { MostActiveStocksAPICall(); return(View("landing")); } }