Exemplo n.º 1
0
        public long BuyGate(Gate gate, long sessionId, long accountId, string accountName)
        {
            string money = _moneyType == MoneyType.GOLD ? "Vàng" : "Xu";
            var    g     = _bets[(int)gate];

            if (g.GateState == 0)
            {
                long betResult = -99;
                long buyAmount = g.Logs.Sum(x => x.betAmount) * GetWinnerMulti(gate);
                betResult = GameDAO.Bet(sessionId, accountId, accountName, $"Mua cửa: {gate.ToString()}, {buyAmount} {money}", buyAmount, (int)_moneyType);
                if (betResult >= 0)
                {
                    g.Owner     = accountId;
                    g.GateState = 1;
                }
                else
                {
                    throw new BuyGateException();
                }
                return(betResult);
            }
            else
            {
                throw new BuyGateException();
            }
        }
Exemplo n.º 2
0
        public long SellGate(Gate gate, long sessionId)
        {
            if (gate != Gate.Even && gate != Gate.Odd)
            {
                throw new SellGateException();
            }

            string money = _moneyType == MoneyType.GOLD ? "Vàng" : "Xu";
            var    g     = _bets[(int)gate];

            if (g.GateState == -1)
            {
                long refundAmount = g.Logs.Sum(x => x.betAmount) * GetWinnerMulti(gate);
                if (refundAmount > 0)
                {
                    long refund = GameDAO.Refund(sessionId, _banker.AccountId, _banker.AccountName, $"Hoàn tiền bán cửa: {gate.ToString()}, {refundAmount} {money}", refundAmount, (int)_moneyType);
                    if (refund >= 0)
                    {
                        g.GateState = 0;
                    }
                    return(refund);
                }
                throw new SellGateException();
            }
            else
            {
                throw new GateSoldOutException();
            }
        }
Exemplo n.º 3
0
        public void ShouldAddGames()
        {
            using (var db = new JUGContext())
            {
                var teamDataService = new BaseDataService <TeamDAO>();
                var gameDataService = new GameDataService();

                Assert.Empty(teamDataService.GetAll(db));
                Assert.Empty(gameDataService.GetAll(db));

                DbHelper.AddSomeTeams(10, db);

                var game = new GameDAO();
                game.Home       = teamDataService.GetAll(db).Where(t => t.Name == "Team 1").FirstOrDefault();
                game.Away       = teamDataService.GetAll(db).Where(t => t.Name == "Team 6").FirstOrDefault();
                game.AwayScore  = 5;
                game.HomeScore  = 6;
                game.IsComplete = true;
                game.IsStarted  = true;
                game.CanTie     = true;

                gameDataService.Create(game, db);


                Assert.Single(db.Games.Local);
            }
        }
Exemplo n.º 4
0
        /*
         * Tis function finds a specific game by its id in the db.
         */
        public string GetById(string id)
        {
            //new GameDAO
            GameDAO service = new GameDAO();

            //parse id(string) to int
            int gameId = Int32.Parse(id);

            //store game found in string
            string gameJSON = service.readById(gameId);

            if (gameJSON == "")
            {
                //new DTO with no data
                DTO dto = new DTO(-1, "Game Not Found", gameJSON);

                string dtoJSON = JsonConvert.SerializeObject(dto);

                return(dtoJSON);
            }
            else
            {
                //new DTO with data
                DTO dto = new DTO(0, "OK", gameJSON);

                string dtoJSON = JsonConvert.SerializeObject(dto);

                return(dtoJSON);
            }
        }
Exemplo n.º 5
0
        // GET: Game/Create
        public JsonResult Create()
        {
            GameDAO dao  = new GameDAO();
            Game    game = dao.generateNewGame();

            return(Json("{\"gameid\":\"" + game.GameId + "\"}"));
        }
Exemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlEditor.DataSource     = PublisherDAO.getPublishers();
                ddlEditor.DataValueField = "id_publisher";
                ddlEditor.DataTextField  = "name_publisher";
                ddlEditor.DataBind();

                ddlGenero.DataSource     = GenreDAO.getGenres();
                ddlGenero.DataValueField = "id_genre";
                ddlGenero.DataTextField  = "description_genre";
                ddlGenero.DataBind();

                int id_game = Convert.ToInt32(Request.QueryString["id_game"]);
                if (id_game == 0)
                {
                    Response.Redirect("~/Games/GameLibraryPL/GameLibrary.aspx");
                }
                Game game = GameDAO.GetGame(id_game);
                tbxValorPago.Text = game.amount_paid.ToString();
                Genre     genre     = GenreDAO.GetGenre(game.id_genre);
                Publisher publisher = PublisherDAO.GetPublisher(game.id_publisher);
                ddlGenero.SelectedValue = genre.description_genre;
                ddlEditor.SelectedValue = publisher.name_publisher;
                tbxTitulo.Text          = game.title;
                tbxDataCompra.Text      = Convert.ToDateTime(game.purchase_date).ToString("yyyy-MM-dd");
                imgCapa.ImageUrl        = "../../Content/CoverImages/" + game.cover_image;
            }
        }
Exemplo n.º 7
0
        private long BetNornal(long sessionId, long accountId, string accountName, long amount, Gate gate, out long gateSumary, bool skipDAO = false)
        {
            gateSumary = 0;
            string money     = _moneyType == MoneyType.GOLD ? "Vàng" : "Xu";
            long   betResult = -99;

            if (!skipDAO)
            {
                betResult = GameDAO.Bet(sessionId, accountId, accountName, $"Đặt cửa: {gate.ToString()}, {amount} {money}", amount, (int)_moneyType);
            }
            else
            {
                betResult = 1;
            }
            if (betResult >= 0)
            {
                _bets[(int)gate].Logs.Add(new BetLog
                {
                    accountId   = accountId,
                    accountName = accountName,
                    betAmount   = amount,
                    betGate     = gate
                });
                gateSumary = _bets[(int)gate].Logs.Sum(x => x.betAmount);
            }
            return(betResult);
        }
        /*
         * this method saves a game
         */
        public bool Save(GameStorageModel storageModel)
        {
            // assume the game will not be saved
            bool success = false;

            // databse connection string
            String connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MinesweeperDatabase;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            // connect to databse in business service to support ACID transactions
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // instantiate DAO
                GameDAO dao = new GameDAO(connection);

                // open databse connection
                connection.Open();

                // pass control to DAO to delete user previous save
                dao.Delete(storageModel.User);

                // pass control to DAO to save the current game and catch return value
                success = dao.Create(storageModel);

                // close database connection
                connection.Close();
            }

            // return result of save attempt
            return(success);
        }
Exemplo n.º 9
0
        public List <HighscoreModel> getTopThreeHighscores()
        {
            GameDAO service = new GameDAO();
            List <HighscoreModel> highscores = new List <HighscoreModel>();

            highscores = service.getTopThreeHighscores();
            return(highscores);
        }
Exemplo n.º 10
0
        public List <HighscoreModel> getUserHighscore(string userName)
        {
            GameDAO service = new GameDAO();
            List <HighscoreModel> highscore = new List <HighscoreModel>();

            highscore = service.getUserHighscore(userName);
            return(highscore);
        }
        public CartController()
        {
            string log = ConfigurationManager.AppSettings["ErrorLogPath"];
            string connectionString = ConfigurationManager.ConnectionStrings["DataSource"].ConnectionString;

            _Logger         = new Logger(log);
            _GameDataAccess = new GameDAO(connectionString, log);
        }
Exemplo n.º 12
0
        bool IService1.SaveGame(string data)
        {
            GameDAO    game       = new GameDAO();
            GameObject gameObject = new GameObject(data);
            bool       success    = game.SaveGame(gameObject);

            return(success);
        }
Exemplo n.º 13
0
        //Constructor for assigning fields for connections
        public GameController()
        {
            //setting variable equal to the SqlConnection in appConfig
            string connection = ConfigurationManager.ConnectionStrings["dataSource"].ConnectionString;

            //setting fields equal to new variant connections
            _dataAccess   = new GameDAO(connection);
            _playerAccess = new PlayerDAO(connection);
        }
        /// <summary>
        /// Review Controller handles all of the views focused on reviews. This controller needs a ReviewDAO, UserDAO, and GameDAO that connect to the
        /// GAMEGROOVE database, as well as a logger to fill out an error log. Retrieve the parameters needed for each of the above from WebConfig.
        /// </summary>
        public ReviewController()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["GameGroove"].ConnectionString;
            string logPath          = ConfigurationManager.AppSettings["LogPath"];

            _Logger           = new Logger(logPath);
            _ReviewDataAccess = new ReviewDAO(logPath, connectionString);
            _UserDataAccess   = new UserDAO(logPath, connectionString);
            _GameDataAccess   = new GameDAO(logPath, connectionString);
        }
Exemplo n.º 15
0
        public static void Initialize()
        {
            Game = new Dictionary <int, string>();
            var gameLst = GameDAO.GetGame();

            foreach (var g in gameLst)
            {
                Game.Add(g.ID, g.Name);
            }
        }
Exemplo n.º 16
0
        //THIS CAN BE AN API
        public int getLoadedSeconds()
        {
            //Use session to grab user
            int userID = (int)HttpContext.Session.GetInt32("userID");

            //Create a new instance of GameDAO and load the game
            GameDAO gameDAO    = new GameDAO();
            Game    gameObject = gameDAO.LoadGame(userID);

            return(gameObject.seconds);
        }
Exemplo n.º 17
0
        public HomeController()
        {
            string log = ConfigurationManager.AppSettings["ErrorLogPath"];

            string connectionString = ConfigurationManager.ConnectionStrings["DataSource"].ConnectionString;

            _Logger = new Logger(log);
            calc    = new CalculationBLL();
            game    = new GameDAO(connectionString, log);
            _GameOrderDataAccess = new GameOrderDAO(connectionString, log);
        }
Exemplo n.º 18
0
        private long BetWithBanker(long sessionId, long accountId, string accountName, long amount, Gate gate, long banker, string bankerName, out long gateSumary, bool skipDAO = false)
        {
            gateSumary = 0;
            long sumaryBanker    = _bankerLocks.Sum(x => x.betAmount);
            long requireNextLock = amount * GetWinnerMulti(gate);
            long oddLock         = _bets[1].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.Odd)
                                   + _bets[2].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.ThreeUp)
                                   + _bets[3].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.ThreeDown);
            long evenLock = _bets[4].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.Even)
                            + _bets[5].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.FourUp)
                            + _bets[6].Logs.Sum(x => x.betAmount) * GetWinnerMulti(Gate.FourDown);

            if (gate >= Gate.Odd && gate <= Gate.ThreeDown)
            {
                oddLock += requireNextLock;
            }
            else
            {
                evenLock += requireNextLock;
            }
            long   lockAmount = oddLock > evenLock ? oddLock - sumaryBanker : evenLock - sumaryBanker;
            long   betResult  = -99;
            string money      = _moneyType == MoneyType.GOLD ? "Vàng" : "Xu";

            if (!skipDAO)
            {
                betResult = GameDAO.BetWithBanker(sessionId, accountId, accountName, $"Đặt cửa: {gate.ToString()}, {amount} {money}",
                                                  amount, (int)_moneyType, banker, lockAmount, bankerName, $"Tạm giữ bổ sung nhà cái: {gate.ToString()}, {amount} {money}");
            }
            else
            {
                betResult = 1;
            }

            if (betResult >= 0)
            {
                _bets[(int)gate].Logs.Add(new BetLog
                {
                    accountId   = accountId,
                    accountName = accountName,
                    betAmount   = amount,
                    betGate     = gate
                });
                _bankerLocks.Add(new BetLog
                {
                    accountId   = banker,
                    accountName = bankerName,
                    betAmount   = lockAmount,
                    betGate     = gate
                });
                gateSumary = _bets[(int)gate].Logs.Sum(x => x.betAmount);
            }
            return(betResult);
        }
        public List <dynamic> GetGameHistory(int searchType, long?accountId, string username, string displayName, int page = 0)
        {
            try
            {
                var gameLst  = SimpleCache.Game;
                var skipItem = 20 * page;

                long id = 0;
                if (searchType == 0)
                {
                    id = accountId.Value;
                }
                else if (searchType == 1)
                {
                    var acc = UserDAO.GetInfo(displayName);
                    if (acc != null)
                    {
                        id = acc.AccountID;
                    }
                }
                else if (searchType == 2)
                {
                    var acc = UserDAO.GetInfoByUsername(username);
                    if (acc != null)
                    {
                        id = acc.AccountID;
                    }
                }

                var            transaction = GameDAO.GetGameTransaction(id, skipItem, 20);
                List <dynamic> data        = new List <dynamic>();
                foreach (var trans in transaction)
                {
                    data.Add(new
                    {
                        AccountId   = id,
                        Game        = gameLst[trans.GameId],
                        CreatedTime = trans.CreatedTime,
                        Amount      = trans.Amount,
                        Balance     = trans.Balance,
                        Description = trans.Description,
                        Type        = trans.Type
                    });
                }

                return(data);
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }

            return(new List <dynamic>());
        }
Exemplo n.º 20
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         repeaterGameLibrary.DataSource = GameDAO.getGames();
         repeaterGameLibrary.DataBind();
     }
     if (Session["role"].ToString() == "U")
     {
         btNovoJogo.Visible = false;
     }
 }
Exemplo n.º 21
0
        public void GenerateNewGameSavesXMLFileWithGameIDInTitle()
        {
            Random      random = new Random();
            long        value  = (long)((random.NextDouble() * 2.0 - 0.1) * long.MaxValue);
            GameDAO     dao    = new GameDAO(value);
            XmlDocument doc    = new XmlDocument();
            Game        game   = dao.generateNewGame();

            doc.Load("game" + game.GameId.ToString() + ".xml");
            Xunit.Assert.Contains("<GameID>" + game.GameId + "</GameID>",
                                  doc.InnerXml.ToString());
        }
Exemplo n.º 22
0
 public dynamic GetMinusGameFund()
 {
     try
     {
         return(GameDAO.GetMinusGameFund());
     }
     catch (Exception ex)
     {
         NLogManager.PublishException(ex);
     }
     return(0);
 }
Exemplo n.º 23
0
        private async Task FinishSession()
        {
            try
            {
                Result.GenerateResult();
                _query.Clear();
                _query.AppendLine("begin transaction");
                _query.AppendLine("begin try");
                _query.AppendLine(_logicGold.BuildResult(Result));
                _query.AppendLine(_logicCoin.BuildResult(Result));
                _query.AppendLine($"update dbo.Session set Status = 1, Dice1 = {(int)Result.Dice1}, Dice2 = {(int)Result.Dice2}, Dice3 = {(int)Result.Dice3} where SessionId = {SessionId}");
                _query.AppendLine("commit transaction");
                _query.AppendLine("end try");
                _query.AppendLine("begin catch");
                _query.AppendLine("if @@trancount > 0 begin rollback transaction end;");
                _query.AppendLine("throw 50000, 'sql exception', 1");
                _query.AppendLine("end catch");

                await GameDAO.ExecuteAsync(_query.ToString());

                var award     = _logicGold.GetAwards();
                var awardCoin = _logicCoin.GetAwards();

                List <string> excludeConnection = new List <string>(
                    award.SelectMany(x => GetAllConnectionById(x.Key))
                    .Union(awardCoin.SelectMany(x => GetAllConnectionById(x.Key)))
                    );

                List <long> winner = new List <long>(
                    award.Select(x => x.Key).Union(awardCoin.Select(x => x.Key)).Distinct()
                    );

                var           exclude       = excludeConnection.Distinct();
                List <string> nonResultUser = new List <string>();
                nonResultUser.AddRange(_connectionGold.GetAll().Union(_connectionCoin.GetAll()).Except(exclude));
                await Clients.Clients.Clients(nonResultUser).showResult(Elapsed, Result, null, null);

                foreach (var w in winner)
                {
                    Dictionary <int, BetLog> gold;
                    Dictionary <int, BetLog> coin;
                    award.TryGetValue(w, out gold);
                    awardCoin.TryGetValue(w, out coin);
                    await Clients.Clients.Clients(GetAllConnectionById(w)).showResult(Elapsed, Result, gold, coin);
                }
            }
            catch (Exception ex)
            {
                _logicGold.ReloadRealFund();
                _logicCoin.ReloadRealFund();
                NLogManager.PublishException(ex);
            }
        }
Exemplo n.º 24
0
        public long Bet(long sessionId, long accountId, string accountName, string betData)
        {
            try
            {
                long betAmount = 0;
                betData = betData.TrimEnd('|');
                string[] data = betData.Split('|');

                foreach (var d in data)
                {
                    string[] parse = d.Split(';');
                    if (long.Parse(parse[1]) < 1000)
                    {
                        return(-99);
                    }
                    betAmount += long.Parse(parse[1]);

                    int gate = int.Parse(parse[0]);
                    if (gate < 1 || gate > 6)
                    {
                        return(-99);
                    }
                }

                long response = GameDAO.Bet(sessionId, accountId, accountName, betData, betAmount, (int)_moneyType);

                if (response > 0)
                {
                    _fund += betAmount;
                    foreach (var d in data)
                    {
                        string[] parse  = d.Split(';');
                        int      gate   = int.Parse(parse[0]);
                        long     amount = long.Parse(parse[1]);

                        BetGates.AddOrUpdate((int)gate, amount, (k, v) => v += amount);
                        if (!_betLogs.ToList().Exists(x => x.accountId == accountId))
                        {
                            BetGateCount.AddOrUpdate(gate, 1, (k, v) => v += 1);
                        }
                        _betLogs.Enqueue(new BetLog {
                            accountId = accountId, amount = amount, betGate = (BetGate)gate, accountName = accountName
                        });
                    }
                }
                return(response);
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }
            return(-99);
        }
Exemplo n.º 25
0
        /// <summary>
        /// On game draw, all information is saved into their respective databases.
        /// </summary>
        /// <param name="playerDB"></param>
        /// <param name="recordDB"></param>
        /// <param name="gameDB"></param>
        public void SaveDraw(PlayerDAO playerDB, RecordDAO recordDB, GameDAO gameDB)
        {
            // Updates player table information.
            playerDB.UpdateBalance(Player);
            // Updates record table information.
            Record record = recordDB.ReadRecordByUserName(Player.UserName);

            record.GamesPlayed++;
            record.Draws++;
            recordDB.UpdateRecord(record);
            // Updates game table information.
            gameDB.AddNewGame(new Game(Player.UserName, Result.DRAW, GameBalance / 2));
        }
Exemplo n.º 26
0
        public dynamic GetFundChangeHistory()
        {
            try
            {
                return(GameDAO.GetFundChangeHistory());
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }

            return(null);
        }
Exemplo n.º 27
0
        /*
         * This function instantiates a new GameDAO and calls read() method to load a game from the database
         */
        public GameModel LoadGame()
        {
            //new GameDAO
            GameDAO service = new GameDAO();

            //read row from db
            string gameJSON = service.read();

            //deserialize the string, store in GameModel
            GameModel game = JsonConvert.DeserializeObject <GameModel>(gameJSON);

            //return game model
            return(game);
        }
Exemplo n.º 28
0
        /*
         * This function instantiates a new GameDAO and calls create() method to save a game to the database
         */
        public bool SaveGame(GameModel game)
        {
            //new GameDAO
            GameDAO service = new GameDAO();

            //serialize object, store in string
            string gameJSON = JsonConvert.SerializeObject(game);

            //create new row in db
            bool success = service.create(gameJSON);

            //return fail or success
            return(success);
        }
        public dynamic GetCashoutHistory(long accountId, int page = 0)
        {
            try
            {
                var gameLst     = SimpleCache.Game;
                var skipItem    = 20 * page;
                var transaction = GameDAO.GetCashoutHistory(accountId, skipItem, 20);

                return(transaction);
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }

            return(null);
        }
Exemplo n.º 30
0
        public dynamic GetLuckySpinFund(int month, int year)
        {
            try
            {
                int      start = int.Parse($"{year.ToString("D4")}{month.ToString("D2")}01");
                DateTime _end  = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
                int      end   = int.Parse($"{year.ToString("D4")}{month.ToString("D2")}{_end.Day.ToString("D2")}");

                return(GameDAO.GetLuckySpinFund(start, end));
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }

            return(null);
        }
Exemplo n.º 31
0
        public string AddGame(FormCollection form)
        {
            try
            {
                var dao = new GameDAO();
                Game model = new Game();
                //if edit
                if (string.IsNullOrWhiteSpace(form["game-id"]))
                {
                    model = dao.Table.Where(x => x.UserId == AppCookies.UserId && x.ID == Convert.ToInt32(form["game-id"])).FirstOrDefault();
                    if (model == null) throw new Exception("Game not found");
                }
                //step 1
                model.Name = form["game-name"];
                model.UserId = AppCookies.UserId;
                model.GameType = form["game-game"];
                model.Description = form["game-description"];
                //step 2
                string[] stages = form.AllKeys.Where(x => x.StartsWith("ingress-")).Select(x => x.Split('-')[1]).ToArray();

                string[] competitionTypes = form["competitiontype-" + stages[0]].Split(',').ToArray();
                int index = -1;
                model.Stages = new List<Stage>();
                foreach (var stage in stages)
                {
                    index++;
                    Stage new_stage = new Stage();

                    CompetitionType c_type = (CompetitionType)Convert.ToInt32(competitionTypes[index]);
                    new_stage.CompetitionType = c_type;
                    new_stage.Egress = Convert.ToInt32(form["egress-" + stage]);
                    new_stage.Ingress = Convert.ToInt32(form["ingress-" + stage]);
                    model.Stages.Add(new_stage);
                }
                model.StageListJson = JsonConvert.SerializeObject(model.Stages);
                //step 3
                Score score = new Score();
                ScoringType s_type = (ScoringType)Convert.ToInt32(form["score-type"]);
                score.ScoringType = s_type;
                if (s_type != ScoringType.Percentage)
                {
                    score.Ranged = form["has-range"] == "on" ? true : false;
                    if (score.Ranged)
                    {
                        score.Minimum = Convert.ToDecimal(form["minimum-score"]);
                        score.Maximum = Convert.ToDecimal(form["maximum-score"]);
                    }
                }
                model.ScoreParams = score;
                model.ScoreJson = JsonConvert.SerializeObject(model.ScoreParams);
                //step 4
                model.LiveStreamUrl = form["live-video-stream"];
                model.BannerImages = form["banner-images"];
                model.Avatar = form["game-avatar"];

                //save or update
                model.DateUpdated = DateTime.Now;
                if(model.ID == 0)//save
                {
                    model.DateCreated = DateTime.Now;
                    dao.Save(model);
                }
                else //update
                {
                    dao.Update(model);
                }
                return AppConstants.SuccessBigBox("Game Setup Successful!", "templates/addgame");
            }
            catch(Exception e)
            {
                string fullExceptionMessage = e.Message + " ";
                if (e.InnerException != null)
                {
                    fullExceptionMessage += e.InnerException.Message;
                }
                return AppConstants.ErrorBigBox(fullExceptionMessage, "templates/addgame");
            }
        }