Exemplo n.º 1
0
        public ActionResult GetLeague(ObjectId objectId)
        {
            var league = Dbh.GetCollection <League>("Leagues")
                         .Find(Query.EQ("_id", objectId));

            return(Json(league, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 2
0
        public ActionResult LogOn(string email, string password, string refUrl, bool rememberMe = false)
        {
            var loginEmail     = email;
            var userCollection = Dbh.GetCollection <User>("Users");
            var user           = userCollection.FindOne(Query.EQ("Email", loginEmail));
            var loginInfo      = new AjaxResponse();

            if (user != null)
            {
                if (user.Password == Md5.CalculateMd5(password))
                {
                    if (Login(user))
                    {
                        loginInfo.Message = "Success";
                        loginInfo.Data    = GetSessionInfo();
                        loginInfo.Success = true;
                    }
                }
                else
                {
                    loginInfo.Message = "Wrong user name or password";
                    loginInfo.Success = false;
                }
            }
            else
            {
                loginInfo.Message = "Wrong user name or password";
                loginInfo.Data    = GetSessionInfo(refresh: true);
                loginInfo.Success = false;
            }

            return(Json(loginInfo, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 3
0
        public ActionResult GetTeamName(string name)
        {
            //Fetch all FoosBall teamNames
            var teamName = Dbh.GetCollection <TeamName>("TeamNames")
                           .FindOne(Query.EQ("Name", name));

            return(Json(teamName, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 4
0
        public ActionResult GetTeams()
        {
            //Fetch all FoosBall teamNames
            var teamNames = Dbh.GetCollection <TeamName>("TeamNames")
                            .FindAll()
                            .OrderByDescending(x => x.Name);

            return(Json(teamNames, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 5
0
        public ActionResult GetAllLeaguesByUserId(string userId)
        {
            var leagueCollection = Dbh.GetCollection <League>("Leagues")
                                   .Find(Query.EQ("Administrators", userId))
                                   .SetSortOrder(SortBy.Ascending("Name"))
                                   .ToList();

            return(Json(leagueCollection, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 6
0
        public ActionResult GetAllLeagues()
        {
            var leagueCollection = Dbh.GetCollection <League>("Leagues")
                                   .FindAll()
                                   .SetSortOrder(SortBy.Ascending("Name"))
                                   .ToList();

            return(Json(leagueCollection, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 7
0
        public ActionResult GetActivePlayers()
        {
            var playerCollection = Dbh.GetCollection <Player>("Players")
                                   .Find(Query.EQ("Deactivated", false))
                                   .SetSortOrder(SortBy.Ascending("Name"))
                                   .ToList();

            return(Json(playerCollection, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 8
0
        public JsonResult GetPlayerRatingData(string playerId)
        {
            var       chartData     = new PlayerRatingChartData();
            const int defaultRating = 1000;

            chartData.DataPoints.Add(new PlayerRatingChartDataPoint
            {
                TimeSet = new List <string>(),
                Rating  = defaultRating
            });

            if (playerId != null)
            {
                var playerCollection = Dbh.GetCollection <Player>("Players");
                var player           = playerCollection.Find(Query.EQ("_id", BsonObjectId.Parse(playerId))).FirstOrDefault();
                var matches          = Dbh.GetCollection <Match>("Matches")
                                       .FindAll()
                                       .SetSortOrder(SortBy.Ascending("GameOverTime"))
                                       .ToList()
                                       .Where(match => match.ContainsPlayer(playerId))
                                       .Where(match => match.GameOverTime != DateTime.MinValue);

                var    playedMatches = matches as List <Match> ?? matches.ToList();
                double minRating     = 10000;
                double maxRating     = 0;

                foreach (var match in playedMatches)
                {
                    var matchPlayer = match.GetPlayer(playerId);
                    minRating = (minRating > matchPlayer.Rating) ? matchPlayer.Rating : minRating;
                    maxRating = (maxRating < matchPlayer.Rating) ? matchPlayer.Rating : maxRating;

                    var time = new List <string>
                    {
                        match.GameOverTime.ToLocalTime().Year.ToString(CultureInfo.InvariantCulture),
                        match.GameOverTime.ToLocalTime().Month.ToString(CultureInfo.InvariantCulture),
                        match.GameOverTime.ToLocalTime().Day.ToString(CultureInfo.InvariantCulture),
                        match.GameOverTime.ToLocalTime().Hour.ToString(CultureInfo.InvariantCulture),
                        match.GameOverTime.ToLocalTime().Minute.ToString(CultureInfo.InvariantCulture),
                        match.GameOverTime.ToLocalTime().Second.ToString(CultureInfo.InvariantCulture)
                    };

                    chartData.DataPoints.Add(new PlayerRatingChartDataPoint
                    {
                        TimeSet = time,
                        Rating  = matchPlayer.Rating
                    });
                }

                chartData.MinimumValue = minRating;
                chartData.MaximumValue = maxRating;
                chartData.Player       = player;
            }

            return(Json(chartData, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 9
0
        public ActionResult GetExperiencedPlayers()
        {
            var playerCollection = Dbh.GetCollection <Player>("Players")
                                   .FindAll()
                                   .SetSortOrder(SortBy.Ascending("Name"))
                                   .Where(x => x.Played > 0)
                                   .ToList();

            return(Json(playerCollection, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 10
0
        public ActionResult GetRankedPlayers()
        {
            var playerCollection = Dbh.GetCollection <Player>("Players")
                                   .FindAll()
                                   .SetSortOrder(SortBy.Descending("Rating"))
                                   .Where(x => x.Played > 0 && x.Deactivated == false)
                                   .ToList();

            return(Json(playerCollection, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 11
0
        // POST: /Matches/RegisterMatch
        private Match RegisterMatch(Match newMatch)
        {
            var currentUser     = Main.Session.GetCurrentUser();
            var basicMatch      = CreateMatch(currentUser, newMatch);
            var resolvedMatch   = ResolveMatch(basicMatch);
            var matchCollection = Dbh.GetCollection <Match>("Matches");

            matchCollection.Save(resolvedMatch);
            return(resolvedMatch);
        }
Exemplo n.º 12
0
        // POST: /Matches/RegisterMatch
        private Match RegisterMatch(Match newMatch)
        {
            var currentUser     = (User)Session["User"];
            var basicMatch      = CreateMatch(currentUser, newMatch);
            var resolvedMatch   = ResolveMatch(basicMatch);
            var matchCollection = Dbh.GetCollection <Match>("Matches");

            matchCollection.Save(resolvedMatch);
            Events.SubmitEvent(EventType.MatchResolve, resolvedMatch, currentUser.Id);
            return(resolvedMatch);
        }
Exemplo n.º 13
0
        public JsonResult Config()
        {
            var currentUser = (User)Session["User"];

            if (currentUser != null && Settings.AdminAccounts.Contains(currentUser.Email))
            {
                return(Json(Dbh.GetCollection <Config>("Config").FindOne(), JsonRequestBehavior.AllowGet));
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 14
0
        public ActionResult Delete(string id)
        {
            var currentUser = Main.Session.GetCurrentUser();

            if (currentUser != null)
            {
                var matchCollection = Dbh.GetCollection <Match>("Matches");
                matchCollection.Remove(Query.EQ("_id", BsonObjectId.Parse(id)));
            }

            return(new HttpStatusCodeResult(200));
        }
Exemplo n.º 15
0
        public ActionResult GetMatches(int numberOfMatches = PageSize, int startFromMatch = 0)
        {
            var fetchNumberOfMatches = numberOfMatches == 0 ? int.MaxValue : numberOfMatches;

            // Fetch all FoosBall matches
            var playedMatches = Dbh.GetCollection <Match>("Matches")
                                .Find(Query.GT("GameOverTime", DateTime.Parse("01/01/2012")))
                                .OrderByDescending(x => x.GameOverTime)
                                .Skip(startFromMatch)
                                .Take(fetchNumberOfMatches);

            return(Json(playedMatches, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 16
0
        public ActionResult Delete(string id)
        {
            var currentUser = (User)Session["User"];

            if (currentUser != null)
            {
                var matchCollection = Dbh.GetCollection <Match>("Matches");
                var query           = Query.EQ("_id", BsonObjectId.Parse(id));
                var match           = matchCollection.FindOne(query);

                Events.SubmitEvent(EventType.MatchDelete, match, currentUser.Id);
                matchCollection.Remove(query);
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 17
0
        // POST: /Matches/Create/{FormCollection}
        private Match CreateMatch(User user, Match newMatch)
        {
            Match match = null;

            if (user != null)
            {
                var red1  = newMatch.RedPlayer1.Id;
                var red2  = string.IsNullOrWhiteSpace(newMatch.RedPlayer2.Id) ? string.Empty : newMatch.RedPlayer2.Id;
                var blue1 = newMatch.BluePlayer1.Id;
                var blue2 = string.IsNullOrWhiteSpace(newMatch.BluePlayer2.Id) ? string.Empty : newMatch.BluePlayer2.Id;

                // only try to create a match if properties are set correctly
                if (!string.IsNullOrEmpty(red1) && !string.IsNullOrEmpty(blue1))
                {
                    var playerCollection = Dbh.GetCollection <Player>("Players");
                    var redPlayer1       = string.IsNullOrEmpty(red1)
                                         ? new Player()
                                         : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(red1)));
                    var redPlayer2 = string.IsNullOrEmpty(red2)
                                         ? new Player()
                                         : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(red2)));
                    var bluePlayer1 = string.IsNullOrEmpty(blue1)
                                          ? new Player()
                                          : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(blue1)));
                    var bluePlayer2 = string.IsNullOrEmpty(blue2)
                                          ? new Player()
                                          : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(blue2)));

                    match = new Match
                    {
                        RedPlayer1   = redPlayer1,
                        RedPlayer2   = redPlayer2,
                        BluePlayer1  = bluePlayer1,
                        BluePlayer2  = bluePlayer2,
                        RedScore     = newMatch.RedScore,
                        BlueScore    = newMatch.BlueScore,
                        CreationTime = DateTime.Now,
                        GameOverTime = DateTime.MinValue,
                        CreatedBy    = user.Id,
                    };
                }
            }

            return(match);
        }
Exemplo n.º 18
0
        public ActionResult GetStatistics()
        {
            var viewModel = new StatsAggregateViewModel
            {
                MostFights   = StatsControllerHelpers.GetStatMostFights(),
                MostWins     = StatsControllerHelpers.GetStatMostWins(),
                MostLosses   = StatsControllerHelpers.GetStatMostLosses(),
                TopRanked    = StatsControllerHelpers.GetStatTopRanked(),
                BottomRanked = StatsControllerHelpers.GetStatBottomRanked()
            };

            var matches     = Dbh.GetCollection <Match>("Matches").FindAll();
            var matchesList = matches.SetSortOrder(SortBy.Ascending("GameOverTime")).ToList();

            viewModel.TotalNumberOfPlayedMatches = matches.Count();

            if (viewModel.TotalNumberOfPlayedMatches == 0)
            {
                return(Json(viewModel, JsonRequestBehavior.AllowGet));
            }

            var players = matches.Select(x => x.BluePlayer1).ToList();

            players.AddRange(matches.Select(x => x.BluePlayer2).ToList());
            players.AddRange(matches.Select(x => x.RedPlayer1).ToList());
            players.AddRange(matches.Select(x => x.RedPlayer2).ToList());

            viewModel.HighestRatingEver = StatsControllerHelpers.GetStatHighestRatingEver(players);
            viewModel.LowestRatingEver  = StatsControllerHelpers.GetStatLowestRatingEver(players);

            var winningStreak = StatsControllerHelpers.GetLongestWinningStreak(matchesList);

            winningStreak.Player           = DbHelper.GetPlayer(winningStreak.Player.Id);
            viewModel.LongestWinningStreak = winningStreak;

            var losingStreak = StatsControllerHelpers.GetLongestLosingStreak(matchesList);

            losingStreak.Player           = DbHelper.GetPlayer(losingStreak.Player.Id);
            viewModel.LongestLosingStreak = losingStreak;
            viewModel.BiggestRatingWin    = StatsControllerHelpers.GetBiggestRatingWin();

            return(Json(viewModel, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 19
0
        public JsonResult Config(Config config)
        {
            var currentUser      = (User)Session["User"];
            var configCollection = Dbh.GetCollection <Config>("Config");
            var currentConfig    = configCollection.FindOne();
            var validation       = new Validation();

            if (currentUser == null || !currentConfig.AdminAccounts.Contains(currentUser.Email))
            {
                return(Json(new AjaxResponse {
                    Success = false, Message = "You must be logged in as an Admin to make changes in the app configuration"
                }));
            }

            var invalidEmail = config.AdminAccounts.FindAll(x => !validation.ValidateEmail(x));

            if (invalidEmail.Any())
            {
                return
                    (Json(new AjaxResponse
                {
                    Success = false,
                    Message = string.Format("One or more of the admin emails are invalid ({0})", string.Join(", ", invalidEmail))
                }));
            }

            var nonExistingEmails = config.AdminAccounts.FindAll(x => !validation.UserEmailExists(x));

            if (nonExistingEmails.Any())
            {
                return
                    (Json(new AjaxResponse
                {
                    Success = false,
                    Message = string.Format("One or more of the admin emails do not belong to a user ({0})", string.Join(", ", nonExistingEmails))
                }));
            }

            configCollection.Save(config);
            return(Json(new AjaxResponse {
                Success = true, Message = "Configuration updated", Data = currentConfig
            }));
        }
Exemplo n.º 20
0
        public ActionResult Register(string email, string name, string password)
        {
            var userEmail    = email.ToLower();
            var userName     = name;
            var userPassword = Md5.CalculateMd5(password);
            var validation   = new Validation();

            var ajaxResponse = validation.ValidateNewUserData(userEmail, userName, userPassword);

            if (!ajaxResponse.Success)
            {
                return(Json(ajaxResponse));
            }

            var userCollection = Dbh.GetCollection <User>("Users");
            var newUser        = new User
            {
                Id       = BsonObjectId.GenerateNewId().ToString(),
                Email    = userEmail,
                Name     = userName,
                Password = userPassword,
            };

            var playerCollection = Dbh.GetCollection <Player>("Players");
            var newPlayer        = new Player
            {
                Id       = BsonObjectId.GenerateNewId().ToString(),
                Email    = userEmail,
                Name     = userName,
                Password = userPassword,
            };

            playerCollection.Save(newPlayer);
            userCollection.Save(newUser);


            var accessToken = Main.Session.CreateNewAccessTokenOnUser(newUser);

            Main.Session.SaveAccessToken(accessToken);
            ajaxResponse.Data = new { AccessToken = Main.Session.BuildSessionInfo(accessToken, newUser) };

            return(Json(ajaxResponse));
        }
Exemplo n.º 21
0
        public ActionResult Register(string email, string name, string password)
        {
            var userEmail    = email.ToLower();
            var userName     = name;
            var userPassword = Md5.CalculateMd5(password);
            var validation   = new Validation();

            var response = validation.ValidateNewUserData(userEmail, userName, userPassword);

            if (!response.Success)
            {
                return(Json(response));
            }

            var userCollection = Dbh.GetCollection <User>("Users");
            var newUser        = new User
            {
                Id       = BsonObjectId.GenerateNewId().ToString(),
                Email    = userEmail,
                Name     = userName,
                Password = userPassword,
            };

            var playerCollection = Dbh.GetCollection <Player>("Players");
            var newPlayer        = new Player
            {
                Id       = BsonObjectId.GenerateNewId().ToString(),
                Email    = userEmail,
                Name     = userName,
                Password = userPassword,
            };

            playerCollection.Save(newPlayer);
            userCollection.Save(newUser);
            Login(newUser);
            Events.SubmitEvent(EventType.PlayerCreate, newUser, newUser.Id);

            response.Data = GetSession(refresh: true);

            return(Json(response));
        }
Exemplo n.º 22
0
        public bool Login(User user)
        {
            // Set or remove cookie for future auto-login
            if (user != null)
            {
                if (user.RememberMe)
                {
                    // Save an autologin token as cookie and in the Db
                    var userCollection      = Dbh.GetCollection <User>("Users");
                    var autoLoginCollection = Dbh.GetCollection <AutoLogin>("AutoLogin");
                    var autoLogin           = autoLoginCollection.FindOne(Query.EQ("Email", user.Email));

                    if (autoLogin == null)
                    {
                        autoLogin = new AutoLogin
                        {
                            Email = user.Email,
                            Token = GetAuthToken(user),
                        };
                        autoLoginCollection.Save(autoLogin);
                    }

                    CreateRememberMeCookie(user);
                    user.RememberMe = user.RememberMe;
                    userCollection.Save(user);
                }
                else
                {
                    RemoveRememberMeCookie();
                }

                Session["Admin"]      = Settings.AdminAccounts.Contains(user.Email);
                Session["IsLoggedIn"] = true;
                Session["User"]       = user;

                return(true);
            }

            return(false);
        }
Exemplo n.º 23
0
        public ActionResult CreateLeague(string name)
        {
            var currentUser = (Player)Session["User"];

            if (currentUser == null)
            {
                return(new HttpStatusCodeResult(400, "Access denied - You must be logged in to create a League"));
            }

            if (string.IsNullOrEmpty(name))
            {
                return(new HttpStatusCodeResult(400, "Bad request - Missing a name property"));
            }

            var existingLeague = Dbh.GetCollection <League>("Leagues")
                                 .Find(Query.EQ("Name", name));

            if (existingLeague.Any())
            {
                return(Json(new AjaxResponse {
                    Success = false, Message = "A league with that name already exists"
                }));
            }

            var newLeague = new League
            {
                Name           = name,
                Administrators = new List <string> {
                    currentUser.Id
                },
                CreatedBy = currentUser.Id
            };

            Dbh.GetCollection <League>("Leagues").Save(newLeague);

            return(Json(new AjaxResponse {
                Success = true, Message = "League has been created"
            }));
        }
Exemplo n.º 24
0
        public ActionResult CreateTeamName(TeamName newTeamName)
        {
            var teamNameCollection = Dbh.GetCollection <TeamName>("TeamNames");
            var playerCollection   = Dbh.GetCollection <Player>("Players");
            var player1            = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(newTeamName.Team.Players[0].Id)));
            var player2            = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(newTeamName.Team.Players[1].Id)));

            var teamName = new TeamName()
            {
                Name = newTeamName.Name,
                Team = new Team()
                {
                    Players = new List <Player>()
                    {
                        player1, player2
                    }
                }
            };

            teamNameCollection.Save(teamName);

            return(Json(new { success = true, newTeam = teamName }));
        }
Exemplo n.º 25
0
        public void ReplayMatches()
        {
            var currentUser = (User)Session["User"];

            if (currentUser != null && Settings.AdminAccounts.Contains(currentUser.Email))
            {
                var allMatches = Dbh.GetCollection <Match>("Matches").FindAll().SetSortOrder(SortBy.Ascending("GameOverTime"));
                var allPlayers = Dbh.GetCollection <Player>("Players").FindAll();

                var copyMatches = Dbh.GetCollection <Match>("CopyMatches");
                var copyPlayers = Dbh.GetCollection <Player>("CopyPlayers");

                // Empty the Copies
                copyMatches.RemoveAll();
                copyPlayers.RemoveAll();

                // Reset all Players
                foreach (var player in allPlayers)
                {
                    player.Lost   = 0;
                    player.Won    = 0;
                    player.Played = 0;
                    player.Rating = 1000;

                    copyPlayers.Save(player);
                }

                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                // replay each match in chronological order
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                foreach (var match in allMatches)
                {
                    // Update players from the match with players from the Db.
                    match.RedPlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer1.Id)));

                    if (match.CountRedPlayers() == 2)
                    {
                        match.RedPlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer2.Id)));
                    }

                    match.BluePlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer1.Id)));

                    if (match.CountBluePlayers() == 2)
                    {
                        match.BluePlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer2.Id)));
                    }

                    // Determine the winners and the losers
                    var winners = new Team();
                    var losers  = new Team();

                    if (match.RedScore > match.BlueScore)
                    {
                        winners.Players.Add(match.RedPlayer1);
                        winners.Players.Add(match.RedPlayer2);
                        losers.Players.Add(match.BluePlayer1);
                        losers.Players.Add(match.BluePlayer2);
                    }
                    else
                    {
                        winners.Players.Add(match.BluePlayer1);
                        winners.Players.Add(match.BluePlayer2);
                        losers.Players.Add(match.RedPlayer1);
                        losers.Players.Add(match.RedPlayer2);
                    }

                    // Get the rating modifier
                    match.DistributedRating = Rating.GetRatingModifier(winners.GetTeamRating(), losers.GetTeamRating());

                    // Propagate the rating and stats to the team members of both teams
                    foreach (var member in winners.Players.Where(member => member.Id != null))
                    {
                        member.Rating += match.DistributedRating;
                        member.Won++;
                        member.Played++;
                        copyPlayers.Save(member);
                    }

                    foreach (var member in losers.Players.Where(member => member.Id != null))
                    {
                        member.Rating -= match.DistributedRating;
                        member.Lost++;
                        member.Played++;
                        copyPlayers.Save(member);
                    }

                    // Save the data to Db
                    copyMatches.Save(match);
                }

                // Copy data into Production tables
                var matches = Dbh.GetCollection <Match>("Matches");
                var players = Dbh.GetCollection <Match>("Players");
                matches.RemoveAll();
                players.RemoveAll();

                foreach (var player in copyPlayers.FindAll())
                {
                    players.Save(player);
                }

                foreach (var match in copyMatches.FindAll())
                {
                    matches.Save(match);
                }
            }
        }
Exemplo n.º 26
0
        public JsonResult GetUserEmails()
        {
            var allEmails = Dbh.GetCollection <User>("Users").FindAll().Select(x => x.Email).ToList();

            return(Json(allEmails, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 27
0
        private Match ResolveMatch(Match match)
        {
            var redScore  = match.RedScore;
            var blueScore = match.BlueScore;

            if (redScore != blueScore)
            {
                var playerCollection = Dbh.GetCollection <Player>("Players");

                // Update players from the match with players from the Db.
                if (match.RedPlayer1.Id != null)
                {
                    match.RedPlayer1 =
                        playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer1.Id)));
                }

                if (match.RedPlayer2.Id != null)
                {
                    match.RedPlayer2 =
                        playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer2.Id)));
                }

                if (match.BluePlayer1.Id != null)
                {
                    match.BluePlayer1 =
                        playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer1.Id)));
                }

                if (match.BluePlayer2.Id != null)
                {
                    match.BluePlayer2 =
                        playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer2.Id)));
                }

                var currentUser = (User)Session["User"];
                if (currentUser != null)
                {
                    // Get the scores
                    match.RedScore  = redScore;
                    match.BlueScore = blueScore;

                    // Determine the winners and the losers
                    var winners = new Team();
                    var losers  = new Team();

                    if (match.RedScore > match.BlueScore)
                    {
                        winners.Players.Add(match.RedPlayer1);
                        winners.Players.Add(match.RedPlayer2);
                        losers.Players.Add(match.BluePlayer1);
                        losers.Players.Add(match.BluePlayer2);
                    }
                    else
                    {
                        winners.Players.Add(match.BluePlayer1);
                        winners.Players.Add(match.BluePlayer2);
                        losers.Players.Add(match.RedPlayer1);
                        losers.Players.Add(match.RedPlayer2);
                    }

                    // Get the rating modifier
                    match.DistributedRating = Rating.GetRatingModifier(winners.GetTeamRating(), losers.GetTeamRating());

                    // Propagate the rating and stats to the team members of both teams
                    foreach (var member in winners.Players.Where(member => member.Id != null))
                    {
                        member.Rating += match.DistributedRating;
                        member.Won++;
                        member.Played++;
                        playerCollection.Save(member);
                    }

                    foreach (var member in losers.Players.Where(member => member.Id != null))
                    {
                        member.Rating -= match.DistributedRating;
                        member.Lost++;
                        member.Played++;
                        playerCollection.Save(member);
                    }

                    // Update match time stats
                    match.GameOverTime = DateTime.Now;
                }
            }

            return(match);
        }
Exemplo n.º 28
0
        public ActionResult GetPlayerStatistics(string playerId)
        {
            using (Profiler.Step("Calculating Player Statistics"))
            {
                if (playerId == null)
                {
                    return(new HttpStatusCodeResult(403, "Invalid request"));
                }
                else
                {
                    var playerCollection = Dbh.GetCollection <Player>("Players");
                    var matches          =
                        Dbh.GetCollection <Match>("Matches")
                        .FindAll()
                        .SetSortOrder(SortBy.Ascending("GameOverTime"))
                        .ToList()
                        .Where(match => match.ContainsPlayer(playerId))
                        .Where(match => match.GameOverTime != DateTime.MinValue);

                    var playedMatches = matches as List <Match> ?? matches.ToList();
                    var player        = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(playerId)));
                    var stats         = new PlayerStatsViewModel
                    {
                        Player        = player,
                        PlayedMatches = playedMatches.OrderByDescending(x => x.GameOverTime),
                        LatestMatch   = playedMatches.Last()
                    };

                    if (playedMatches.Count == 0)
                    {
                        return(Json(stats, JsonRequestBehavior.AllowGet));
                    }

                    var bff                  = StatsControllerHelpers.GetBestFriendForever(playerId, playedMatches);
                    var rbff                 = StatsControllerHelpers.GetRealBestFriendForever(playerId, playedMatches);
                    var eae                  = StatsControllerHelpers.GetEvilArchEnemy(playerId, playedMatches);
                    var preferredColor       = StatsControllerHelpers.GetPreferredColor(playerId, playedMatches);
                    var winningColor         = StatsControllerHelpers.GetWinningColor(playerId, playedMatches);
                    var highestRating        = StatsControllerHelpers.GetHighestRating(playerId, playedMatches);
                    var lowestRating         = StatsControllerHelpers.GetLowestRating(playerId, playedMatches);
                    var longestWinningStreak = StatsControllerHelpers.GetPlayersLongestWinningStreak(playerId, playedMatches);
                    var longestLosingStreak  = StatsControllerHelpers.GetPlayersLongestLosingStreak(playerId, playedMatches);

                    foreach (var match in playedMatches)
                    {
                        stats.Played++;
                        stats.Won     = match.WonTheMatch(playerId) ? ++stats.Won : stats.Won;
                        stats.Lost    = !match.WonTheMatch(playerId) ? ++stats.Lost : stats.Lost;
                        stats.Ranking = playerCollection.FindAll()
                                        .SetSortOrder(SortBy.Descending("Rating"))
                                        .Where(x => x.Played > 0 && x.Deactivated == false)
                                        .ToList()
                                        .FindIndex(x => x.Id == playerId) + 1;

                        stats.TotalNumberOfPlayers = (int)playerCollection.Count(Query.GT("Played", 0));
                    }

                    stats.Bff = bff.OrderByDescending(x => x.Value.Occurrences)
                                .Select(x => x.Value)
                                .FirstOrDefault();
                    stats.Rbff = rbff.OrderByDescending(x => x.Value.Occurrences).Select(x => x.Value).FirstOrDefault();
                    stats.Eae  = eae.OrderByDescending(x => x.Value.Occurrences)
                                 .ThenByDescending(x => x.Value.GoalDiff)
                                 .Select(x => x.Value)
                                 .FirstOrDefault();
                    stats.PreferredColor = preferredColor.OrderByDescending(x => x.Value.Occurrences)
                                           .Select(x => x.Value)
                                           .FirstOrDefault();
                    stats.WinningColor = winningColor.OrderByDescending(x => x.Value.Occurrences)
                                         .Select(x => x.Value)
                                         .FirstOrDefault();
                    stats.HighestRating        = highestRating;
                    stats.LowestRating         = lowestRating;
                    stats.LongestWinningStreak = longestWinningStreak;
                    stats.LongestLosingStreak  = longestLosingStreak;

                    return(Json(stats, JsonRequestBehavior.AllowGet));
                }
            }
        }