예제 #1
0
        public async Task <ServiceResponse <int> > Register(User user, string password)
        {
            if (await UserExists(user.Email))
            {
                return(new ServiceResponse <int>
                {
                    Success = false,
                    Message = "User already exists"
                });
            }

            CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);
            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            await _context.Users.AddAsync(user);

            await _context.SaveChangesAsync();

            UserPortfolio newPortfolio = new UserPortfolio()
            {
                UserId = user.Id, CurrentlySelected = true, Name = "default"
            };
            await _context.UserPortfolios.AddAsync(newPortfolio);

            await _context.SaveChangesAsync();

            return(new ServiceResponse <int>
            {
                Data = user.Id,
                Message = "Registration successful!"
            });
        }
예제 #2
0
        public void AddToProfile(UserPortfolio userPortfolio)
        {
            var user = _unitOfWork.Users.Get(userPortfolio.UserId);

            user.UserPortfolios.Add(userPortfolio);
            _unitOfWork.Complete();
        }
예제 #3
0
        private static void ShowPortfolio(UserPortfolio userPortfolio)
        {
            var container    = UnityIocConfig.Container;
            var shareService = container.Resolve <IShareService>();

            Console.WriteLine("Name: " + userPortfolio.Name);
            Console.WriteLine("Remaining amount of cash: " + userPortfolio.Cash);

            if (!userPortfolio.Shares.Any())
            {
                Console.WriteLine("This user does not have any shares.");
            }
            else
            {
                foreach (var shareRecord in userPortfolio.Shares)
                {
                    var share = shareService.Get(shareRecord.Key);
                    Console.WriteLine("- Share name: " + share.Name);
                    Console.WriteLine("Share price: " + share.Price);
                    Console.WriteLine("Quantity: " + shareRecord.Value);
                    Console.WriteLine("Share price total: " + (shareRecord.Value * share.Price));
                }
            }
            Console.WriteLine("=================================");
        }
예제 #4
0
 public void UpdatePortfolioItem(UserPortfolio portfolioItem)
 {
     using (var transaction = _session.BeginTransaction())
     {
         _session.Update(portfolioItem);
         transaction.Commit();
     }
 }
        public void _AddToPortfolio(UserPortfolio userPortfolio)
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            userPortfolio.UserId = Convert.ToInt32(Convert.ToInt32(User.Identity.Name));
            _services.AddToProfile(userPortfolio);
        }
예제 #6
0
        public UserPortfolio ReadPortfolioItemById(int id)
        {
            var itemRead = new UserPortfolio();

            using (var transaction = _session.BeginTransaction())
            {
                itemRead = _session.Get <UserPortfolio>(id);
                transaction.Commit();
            }

            return(itemRead);
        }
예제 #7
0
        public bool Update(UserPortfolio userPortfolio)
        {
            var update = _repository.UserPortfolios().FirstOrDefault(u => u.ID == userPortfolio.ID);

            if (update != null)
            {
                update = userPortfolio;
                return(true);
            }

            return(false);
        }
예제 #8
0
        public UserPortfolio CreatePortfolioItem(UserPortfolio portfolioItem)
        {
            var itemCreated = new UserPortfolio();

            using (var transaction = _session.BeginTransaction())
            {
                var newId = _session.Save(portfolioItem);
                itemCreated = _session.Get <UserPortfolio>(newId);
                transaction.Commit();
            }

            return(itemCreated);
        }
예제 #9
0
        public async Task DeletePortfolio(UserPortfolio portfolio)
        {
            var result = await _http.PostAsJsonAsync <UserPortfolio>("api/userportfolio/deleteportfolio", portfolio);

            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                _toastService.ShowError(await result.Content.ReadAsStringAsync());
            }
            else
            {
                _toastService.ShowSuccess($"{portfolio.Name} has been deleted.", "Portfolio deleted");
            }
        }
예제 #10
0
        public async Task AddPortfolio(UserPortfolio portfolio)
        {
            var result = await _http.PostAsJsonAsync <UserPortfolio>("api/userportfolio/addportfolio", portfolio);

            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                _toastService.ShowError(await result.Content.ReadAsStringAsync());
            }
            else
            {
                _toastService.ShowSuccess($"{portfolio.Name} was added to your account!", "Portfolio added!");
            }
        }
예제 #11
0
        public async Task <IActionResult> AddPortfolio([FromBody] UserPortfolio portfolio)
        {
            var user = await _utilityService.GetUser();

            portfolio.UserId            = user.Id;
            portfolio.CurrentlySelected = false;

            await _context.AddAsync <UserPortfolio>(portfolio);

            await _context.SaveChangesAsync();

            return(Ok(portfolio));
        }
예제 #12
0
        public async Task UpdatePortfolio(UserPortfolio portfolio)
        {
            var result = await _http.PostAsJsonAsync <UserPortfolio>("api/userportfolio/updateportfolio", portfolio);

            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                _toastService.ShowError(await result.Content.ReadAsStringAsync());
            }
            else
            {
                _toastService.ShowSuccess($"{portfolio.Name} was updated successfully.", "Update successful");
            }
        }
예제 #13
0
        public async Task <IActionResult> DeletePortfolio([FromBody] UserPortfolio portfolio)
        {
            var user = await _utilityService.GetUser();

            if (user.Id != portfolio.UserId)
            {
                return(BadRequest("User does not own this portfolio"));
            }

            if (portfolio.CurrentlySelected)
            {
                return(BadRequest("Deselect portfolio before deleting"));
            }

            _context.Remove(portfolio);
            await _context.SaveChangesAsync();

            return(Ok());
        }
예제 #14
0
        public async Task <PortfolioAddedResponse> Create(UserPortfolio userPortfolio)
        {
            bool success   = false;
            var  portfolio = _mapper.Map <Portfolio>(userPortfolio);
            List <ResponseError> responseErrors = new List <ResponseError>();

            try
            {
                _context.Portfolios.Add(portfolio);
                await _context.SaveChangesAsync();

                success = true;
            }
            catch (Exception e)
            {
                success = false;
                responseErrors.Add(new ResponseError("400", e.Message));
                throw;
            }

            return(new PortfolioAddedResponse(portfolio.Id.ToString(), success, responseErrors));
        }
예제 #15
0
        public async Task <IActionResult> UpdatePortfolio([FromBody] UserPortfolio portfolio)
        {
            var user = await _utilityService.GetUser();

            var originalPortfolio = await _context.UserPortfolios.FirstOrDefaultAsync <UserPortfolio>(u => u.Id == portfolio.Id && u.UserId == user.Id);

            if (originalPortfolio == null)
            {
                return(BadRequest($"Portfolio with id: {portfolio.Id} not found for user with id: {user.Id}."));
            }

            var currentlySelectedPortfolio = await _context.UserPortfolios.FirstOrDefaultAsync(u => u.CurrentlySelected == true);

            if (portfolio.CurrentlySelected && currentlySelectedPortfolio != null)
            {
                currentlySelectedPortfolio.CurrentlySelected = false;
            }

            originalPortfolio.Name = portfolio.Name;
            originalPortfolio.CurrentlySelected = portfolio.CurrentlySelected;
            await _context.SaveChangesAsync();

            return(Ok(originalPortfolio));
        }
예제 #16
0
        /**
         * Sells a number of stocks, adds the transaction to portfolio and history, and updates the user's money
         */
        public void sellShares(ComboBox cmbSell, string idOfCompany, string amountOfShares, string costOfShares, string symbolOfCompany, string nameOfCompany, string priceOfShare)
        {
            // check if the user has selected a stock
            int parsedValue;
            if (String.IsNullOrEmpty(cmbSell.Text))
            {
                MessageBox.Show("You must specify a stock to sell.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // check if user has entered an amount of shares
            else if (String.IsNullOrWhiteSpace(amountOfShares))
            {
                MessageBox.Show("You must specify an amount of shares.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // make sure that user buys whole shares, not fractions
            else if (!int.TryParse(amountOfShares, out parsedValue))
            {
                MessageBox.Show("Invalid number of shares.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // check how much shares user has
                UserPortfolio checkShares = new UserPortfolio();
                double userShares = Convert.ToDouble(checkShares.getShares(nameOfCompany));

                // convert variables
                int id = Convert.ToInt32(idOfCompany);
                int shares = Convert.ToInt32(amountOfShares);
                NumberFormat format = new NumberFormat();
                double price = Convert.ToDouble(priceOfShare);
                string priceString = format.ToUSString(price);
                double total = Convert.ToDouble(costOfShares);
                string totalString = format.ToUSString(total);

                // check if the user wants to sell more than he has
                if (userShares < shares)
                {
                    MessageBox.Show("You have less than the amount of shares you want to sell.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    try
                    {
                        // remove stock from the portfolio
                        sqlConnection.Open();
                        SqlCommand sqlCommandSell = new SqlCommand(String.Format("update portfolio set shares = shares - {3}, total = total - {5} where id = {0} if ((select shares from portfolio where Id = {0}) <= {3}) delete from portfolio where id = {0}", id, symbolOfCompany, nameOfCompany, shares, priceString, totalString), sqlConnection);
                        sqlCommandSell.ExecuteNonQuery();

                        // add selling stock to history
                        SqlCommand sqlCommandHistory = new SqlCommand(String.Format("insert into history values ({0}, 'SELL', CURRENT_TIMESTAMP, '{1}', '{2}', {3}, {4})", id, symbolOfCompany, nameOfCompany, shares, priceString), sqlConnection);
                        sqlCommandHistory.ExecuteNonQuery();

                        // update money
                        SqlCommand sqlCommandMoney = new SqlCommand(String.Format("update account set money = money + {0}", totalString), sqlConnection);
                        sqlCommandMoney.ExecuteNonQuery();

                        // inform the user about the sucessfull transaction
                        MessageBox.Show(String.Format("You successfully sold {0} shares from {1}. The total cost was {2}.", shares, nameOfCompany, total), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        sqlConnection.Close();
                    }
                }
            }
        }
예제 #17
0
        public async Task <bool> Execute(string Ticker, int NumShares, int UserId)
        {
            try
            {
                var stockPriceQueryRequest = new QueryRequest
                {
                    TableName                 = "StockPrice",
                    ProjectionExpression      = "Price",
                    KeyConditionExpression    = "Ticker = :v_Ticker",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                        { ":v_Ticker", new AttributeValue {
                              S = Ticker
                          } }
                    }
                };
                var stockPriceQuery = await _amazonDynamoDB.QueryAsync(stockPriceQueryRequest);

                var stockPrice = float.Parse(stockPriceQuery.Items.First().First().Value.N);

                var portfolioQueryRequest = new QueryRequest
                {
                    TableName                 = "Users",
                    ProjectionExpression      = "OwnedStocks, Money",
                    KeyConditionExpression    = "UserId = :v_Id",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                        { ":v_Id", new AttributeValue {
                              N = UserId.ToString()
                          } }
                    }
                };
                var portfolioQuery = await _amazonDynamoDB.QueryAsync(portfolioQueryRequest);

                var portfolio = new UserPortfolio
                {
                    Money  = 0,
                    UserId = UserId
                };

                if (portfolioQuery.Items.Any() && portfolioQuery.Items.First().Any(x => x.Key == "OwnedStocks") && portfolioQuery.Items.First().Any(x => x.Key == "Money"))
                {
                    portfolio.OwnedShares = portfolioQuery.Items.First().First(x => x.Key == "OwnedStocks").Value.M.Select(x => new OwnedShare {
                        Ticker = x.Key, Shares = int.Parse(x.Value.N)
                    }).ToList();
                    portfolio.Money = float.Parse(portfolioQuery.Items.First().First(x => x.Key == "Money").Value.N);
                }

                if (portfolio.OwnedShares.First(x => x.Ticker == Ticker).Shares > NumShares)
                {
                    portfolio.OwnedShares.First(x => x.Ticker == Ticker).Shares -= NumShares;
                }
                else
                {
                    portfolio.OwnedShares.Remove(portfolio.OwnedShares.First(x => x.Ticker == Ticker));
                }

                //GAIN MONEY
                portfolio.Money += (stockPrice * NumShares);

                //RESAVE
                var portfolioDict = portfolio.OwnedShares.ToDictionary(x => x.Ticker, x => new AttributeValue {
                    N = x.Shares.ToString()
                });
                var portfolioMap = new AttributeValue {
                    M = portfolioDict
                };
                var update = await _amazonDynamoDB.UpdateItemAsync(new UpdateItemRequest
                {
                    TableName = "Users",
                    Key       = new Dictionary <string, AttributeValue> {
                        { "UserId", new AttributeValue {
                              N = UserId.ToString()
                          } }
                    },
                    AttributeUpdates = new Dictionary <string, AttributeValueUpdate>
                    {
                        { "Money", new AttributeValueUpdate {
                              Action = AttributeAction.PUT, Value = new AttributeValue {
                                  N = portfolio.Money.ToString()
                              }
                          } },
                        { "OwnedStocks", new AttributeValueUpdate {
                              Action = AttributeAction.PUT, Value = portfolioMap
                          } }
                    }
                });

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
예제 #18
0
        public async Task <IActionResult> Create(UserPortfolio userPortfolio, IFormFileCollection files)
        {
            int    id             = 0;
            string statusPassword = "";

            if (Request.Cookies.ContainsKey("IdUser") && Request.Cookies.ContainsKey("UserPassword"))
            {
                id             = int.Parse(Request.Cookies["IdUser"]);
                statusPassword = Request.Cookies["UserPassword"];
            }

            if (statusPassword == "true" && id > 0)
            {
                if (ModelState.IsValid)
                {
                    userPortfolio.DatePortfolio = DateTime.Now;
                    userPortfolio.IdUser        = id;
                    _context.Add(userPortfolio);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    return(View(userPortfolio));
                }

                ImgPortfolio img = new ImgPortfolio();

                int count = 0;
                count = _context.UserPortfolio.Max(p => p.IdPortfolio);

                foreach (var file in files)
                {
                    if (file != null)
                    {
                        byte[] imageData = null;

                        using (var fileStream = file.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                imageData = ms.ToArray();
                            }

                        string type = file.ContentType;
                        img.IdPortfolio = count;
                        img.IdImg       = 0;
                        img.DataImg     = imageData;
                        img.IdUser      = id;
                        img.TypeImg     = type;

                        _context.Add(img);
                    }
                    await _context.SaveChangesAsync();

                    int lastIdImg     = _context.ImgPortfolio.Max(p => p.IdImg);
                    int lastPortfolio = _context.UserPortfolio.Max(p => p.IdPortfolio);
                    var portfolio     = _context.UserPortfolio.Find(lastPortfolio);
                    portfolio.MainImg = lastIdImg;
                    _context.Update(portfolio);
                    await _context.SaveChangesAsync();
                }
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(Redirect("/UserAuthorization/Index"));
            }
        }