Example #1
0
        public JsonResult ResetTurn()
        {
            int turn    = 1;
            var csvFile = turnPath;

            try
            {
                // Reset game turn
                using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile, false))
                {
                    // Write csv column
                    writer.AddRow("turn");
                    // Write turn
                    writer.AddRow(turn.ToString());
                }

                UpdateMarketData(turn);
            }
            catch (Exception ex)
            {
                return(JSONHelper.CreateJSONResult(false, ex));
            }

            return(JSONHelper.CreateJSONResult(true, turn));
        }
Example #2
0
 /// <summary>
 /// Save player data
 /// </summary>
 /// <param name="player">The player data</param>
 private void SavePlayerData(PlayerModel player)
 {
     playerPath = string.Format("{0}\\{1}.csv", PLAYER_NAMES_PATH, Session["USER_NAME"]);
     using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(playerPath, false))
     {
         // Add file header column
         writer.AddRow("id,name,cash,portfolio");
         // New player data
         writer.AddRow(string.Format("{0},{1},{2},{3}",
                                     Session["USER_ID"],
                                     Session["USER_NAME"],
                                     player.Cash,
                                     player.Portfolio));
     }
 }
Example #3
0
        //public async Task<ActionResult> Register(RegisterViewModel model)
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                //var result = await UserManager.CreateAsync(user, model.Password);
                //if (result.Succeeded)
                //{
                //    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                //    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //    // Send an email with this link
                //    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                //    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                //    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                //    return RedirectToAction("Index", "Home");
                //}
                //AddErrors(result);
                var path = string.Format("{0}\\{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data"), ConfigurationManager.AppSettings["players"]);
                // Get latest player id
                var latestId = 0;
                using (var reader = new CSVHelper.CsvFileReader(path))
                {
                    var cols = new List <string>()
                    {
                        "id"
                    };
                    //while (reader.ReadRow(new List<string>() { "id" }))
                    while (reader.ReadRow(cols))
                    {
                        int.TryParse(cols[0], out latestId);
                    }
                }
                // Create new player
                using (var writer = new CSVHelper.CsvFileWriter(path))
                {
                    // Write each row of data
                    var data = string.Format("{0},\"{1}\",\"{2}\"", latestId + 1, model.Email, model.Password);
                    writer.AddRow(data);
                }

                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #4
0
        /// <summary>
        /// Change market close/open status
        /// </summary>
        /// <param name="status">0 - close, 1 - open</param>
        private void ChangeMarketStatus(int status)
        {
            // Find market status file
            var csvFile = string.Format("{0}\\{1}\\{2}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data"), ConfigurationManager.AppSettings["boards"], ConfigurationManager.AppSettings["marketStatus"]);

            using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile, false))
            {
                var row = new List <string>();
                // Write csv column
                row.Add("status");
                writer.WriteRow(row);
                // Write turn data
                row.Clear();
                row.Add(status.ToString());
                writer.WriteRow(row);
            }
        }
Example #5
0
        public JsonResult NextTurn()
        {
            int?turn    = null;
            var csvFile = turnPath;

            try
            {
                // Get current game turn
                using (CSVHelper.CsvFileReader reader = new CSVHelper.CsvFileReader(csvFile))
                {
                    while (reader.ReadRow(searchAll))
                    {
                        if (!searchAll.Contains("turn"))
                        {
                            turn = int.Parse(searchAll[0]) + 1;
                        }
                    }
                }

                // Update game turn
                if (turn.HasValue)
                {
                    using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile, false))
                    {
                        // Write csv column
                        writer.AddRow("turn");
                        // Write turn data
                        writer.AddRow(turn.Value.ToString());
                    }

                    UpdateMarketData(turn.Value);
                }
            }
            catch (Exception ex)
            {
                return(JSONHelper.CreateJSONResult(false, ex));
            }

            return(JSONHelper.CreateJSONResult(true, turn));
        }
Example #6
0
        public JsonResult BuyStock(int id, string name, int vol)
        {
            // Check if user already logged in
            //if (Session["username"] == null)
            //    return;

            // Check Buy/Sell volumns if less than 0 return error
            if (vol < 1)
            {
                return(JSONHelper.CreateJSONResult(false, "The volumns cannot less than 100."));
            }

            var        row   = new List <string>();
            decimal    cost  = 0;
            StockModel stock = null;

            try
            {
                // Read stocks data (price, dividend) at current turn
                stock = GetStockMarketByName(name).First();
                // Calculate stock cost
                cost = stock.Price * vol;
                // Apply commission cost
                cost += cost * COMMISSION_RATE;
                // Find player data
                var player = GetPlayerData();
                // Check player cash
                // If cash not enough return error
                if (player.Cash - cost < 0)
                {
                    return(JSONHelper.CreateJSONResult(false, "Not enough cash"));
                }

                // Read player portfolio
                var playerPortfolio = GetPortfolio();

                // Stock info
                var newStock = GetStockMarketByName(name).First();
                // Add new stock to player protfolio
                playerPortfolioPath = string.Format("{0}\\{1}{2}", PLAYER_NAMES_PATH, Session["USER_NAME"], PORTFOLIO_FILE_FORMAT);
                using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(playerPortfolioPath))
                {
                    writer.AddRow(string.Format("{0},{1},{2},{3},{4},{5}", id, name.ToLower(), newStock.Price, 0.00, vol, Session["USER_ID"]));
                }

                // Update player cash
                //var player = GetPlayerData(name);
                player.Cash -= cost;
                // Update Portfolio value
                var total = 0m;
                foreach (var item in playerPortfolio)
                {
                    total += item.Price * item.Vol;
                }
                player.Portfolio = player.Cash + total;
                // Write new player data
                SavePlayerData(player);
            }
            catch (Exception ex)
            {
                return(JSONHelper.CreateJSONResult(false, ex));
            }

            return(JSONHelper.CreateJSONResult(true, "Trade success"));
        }
Example #7
0
        /// <summary>
        /// Player action to sell stock in portfolio
        /// </summary>
        /// <param name="id">The stock id</param>
        /// <param name="name">The stock name</param>
        /// <param name="vol">The stock volumns</param>
        /// <returns></returns>
        public JsonResult SellStock(int id, string name, int vol)
        {
            // Check if user already logged in
            //if (Session["username"] == null)
            //    return;

            // Check Buy/Sell volumns if less than 0 return error
            if (vol < 1)
            {
                return(JSONHelper.CreateJSONResult(false, "The volumns cannot less than 100."));
            }

            var amount = 0m;
            var row    = new List <string>();

            var stockMarket = GetStockMarketByName(name).First();
            // Get player portfolio every record
            var portfolio = GetPortfolio(false);

            // Find all stocks in portfolio with the same name
            var stocks = portfolio.Where(p => p.Name.ToLower().Equals(name.ToLower())).OrderBy(p => p.Price).ToList();

            // If sell volumns are more than existing stock return error
            if (stocks.Sum(p => p.Vol) - vol < 0)
            {
                return(JSONHelper.CreateJSONResult(false, "Not enough stock for sell"));
            }
            // Sell stock
            foreach (var item in stocks)
            {
                // If sell volumns are more than exists volumns, delete record
                if (item.Vol - vol < 0)
                {
                    // Cash gain from selling stock
                    amount  += stockMarket.Price * item.Vol;
                    vol     -= item.Vol;
                    item.Vol = 0;
                }
                // There are volumns left after sell
                else
                {
                    // Cash gain from selling stock
                    amount   += stockMarket.Price * vol;
                    item.Vol -= vol;
                    vol       = 0;
                    break;
                }
            }
            // Apply commission rate when sell
            amount -= amount * COMMISSION_RATE;

            // Update player data
            var player = GetPlayerData();

            player.Cash     += amount;
            player.Portfolio = portfolio.Sum(p => p.Price * p.Vol);
            // Save new player data
            SavePlayerData(player);

            // Update portfolio
            playerPortfolioPath = string.Format("{0}\\{1}{2}", PLAYER_NAMES_PATH, Session["USER_NAME"], PORTFOLIO_FILE_FORMAT);
            using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(playerPortfolioPath, false))
            {
                // Write file header
                writer.AddRow("id,name,price,dividend,volumn,playerid");
                // Update stocks in portfolio which have volumns more than 0
                foreach (var item in portfolio)
                {
                    if (item.Vol > 0)
                    {
                        writer.AddRow(string.Format("{0},{1},{2},{3},{4},{5}",
                                                    0,
                                                    item.Name.ToLower(),
                                                    item.Price,
                                                    item.Dividend,
                                                    item.Vol,
                                                    Session["USER_ID"]));
                    }
                }
            }

            return(JSONHelper.CreateJSONResult(true, "Trade success"));
        }
Example #8
0
        public JsonResult ChangeStockInMarket(string stockName, bool isAdd)
        {
            var csvData = new List <StockModel>();
            var csvFile = marketDataPath;

            try
            {
                if (isAdd)
                {
                    // Add new stock to market
                    using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile))
                    {
                        writer.AddRow(string.Format("0,{0},0,0", stockName.ToLower()));
                    }
                }
                else
                {
                    // Get all stock in market
                    var market = GetMarketStocks();
                    // Remove stock from market
                    var stockToRemove = market.Where(p => p.Name.Equals(stockName.ToUpper())).First();
                    market.Remove(stockToRemove);
                    // Rewrite market data
                    using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile, false))
                    {
                        // Add market csv header
                        writer.AddRow("id,name,price,dividend");

                        foreach (var item in market)
                        {
                            writer.AddRow(string.Format("0,{0},{1},{2}", item.Name, item.Price, item.Dividend));
                        }
                    }

                    // Read stocks data (price, dividend) at current turn
                    //using (CSVHelper.CsvFileReader reader = new CSVHelper.CsvFileReader(csvFile))
                    //{
                    //    while (reader.ReadRow(searchAll))
                    //    {
                    //        if (!searchAll.Contains("id"))
                    //        {
                    //            // Create stock model data from csv
                    //            csvData.Add(new StockModel(int.Parse(searchAll[0]), searchAll[1].ToUpper(), decimal.Parse(searchAll[2]), decimal.Parse(searchAll[3])));
                    //        }
                    //    }
                    //}
                }

                // Find current turn
                int?turn = null;
                csvFile = turnPath;
                using (CSVHelper.CsvFileReader reader = new CSVHelper.CsvFileReader(csvFile))
                {
                    while (reader.ReadRow(searchAll))
                    {
                        if (!searchAll.Contains("turn"))
                        {
                            turn = int.Parse(searchAll[0]);
                        }
                    }
                }

                //Update market value
                if (turn.HasValue)
                {
                    UpdateMarketData(turn.Value);

                    csvData = GetMarketStocks();
                }
            }
            catch (Exception ex)
            {
                return(JSONHelper.CreateJSONResult(false, ex));
            }

            return(JSONHelper.CreateJSONResult(true, csvData));
        }
Example #9
0
        /// <summary>
        /// Update all stock data that in market
        /// </summary>
        /// <param name="turn">The board turn</param>
        private void UpdateMarketData(int turn)
        {
            turn--;
            //--------------------//
            // Update market data //
            //--------------------//
            var stockNames = new List <string>();
            var csvFile    = marketDataPath;

            // Read current market stock
            using (CSVHelper.CsvFileReader reader = new CSVHelper.CsvFileReader(csvFile))
            {
                while (reader.ReadRow(searchAll))
                {
                    if (!searchAll.Contains("id"))
                    {
                        // Create stock model data from csv
                        //csvData.Add(new StockModel(int.Parse(searchAll[0]), searchAll[1].ToUpper(), decimal.Parse(searchAll[2]), decimal.Parse(searchAll[3])));
                        stockNames.Add(searchAll[1].ToUpper());
                    }
                }
            }
            // Update stocks price in market accoring to current turn
            var csvFloder      = stockNamesPath;
            var stocksData     = new List <string>();
            var stocksPriceAvg = new List <decimal>();
            var stocksDivAvg   = new List <decimal>();

            // Find all stocks name
            foreach (var files in Directory.GetFiles(csvFloder))
            {
                FileInfo info      = new FileInfo(files);
                var      stockName = info.Name.Replace(".csv", string.Empty).ToUpper();

                if (stockNames.Contains(stockName))
                {
                    using (CSVHelper.CsvFileReader reader = new CSVHelper.CsvFileReader(info.FullName))
                    {
                        while (reader.ReadRow(searchAll))
                        {
                            if (!searchAll.Contains("id") && searchAll[0].Equals((turn).ToString()))
                            {
                                // Set stock id
                                searchAll[0] = stocksData.Count.ToString();
                                // Create stock model data from csv
                                stocksData.Add(string.Join(",", searchAll.ToArray()));
                                // Add stock price/dividend to find market index price/dividend
                                stocksPriceAvg.Add(decimal.Parse(searchAll[2]));
                                stocksDivAvg.Add(decimal.Parse(searchAll[3]));
                                break;
                            }
                        }
                    }
                }
            }
            // Calculate market index
            var indexPrice = stocksPriceAvg.Count == 0 ? 0 : (stocksPriceAvg.Sum() / stocksPriceAvg.Count);
            var indexDiv   = stocksDivAvg.Count == 0 ? 0 : (stocksDivAvg.Sum() / stocksDivAvg.Count);
            var indexStock = string.Format("{0},index,{1},{2}", stocksData.Count, indexPrice, indexDiv);

            stocksData.Add(indexStock);
            // Write new market data
            using (CSVHelper.CsvFileWriter writer = new CSVHelper.CsvFileWriter(csvFile, false))
            {
                // Write csv column
                string marketCols = "id,name,price,dividend";
                //var row = new List<string>() { "id,name,price,dividend" };
                writer.AddRow(marketCols);

                foreach (var item in stocksData)
                {
                    writer.AddRow(item);
                }
            }
        }