Beispiel #1
0
        public ActionResult Leaderboard()
        {
            var sessionId = Request.Cookies["sessionId"];
            var model     = new LeaderboardModel(sessionId);

            return(View(model));
        }
Beispiel #2
0
        // GET: api/Leaderboard
        public List <LeaderboardModel> Get()
        {
            List <LeaderboardModel> lbm = new List <LeaderboardModel>();

            foreach (User user in db.Users.ToList())
            {
                LeaderboardModel userBoard = new LeaderboardModel();
                userBoard.name        = user.name;
                userBoard.totalPoints = 0;
                userBoard.gameCount   = 0;

                foreach (UserTeam ut in db.UserTeams.Where(u => u.userID.Equals(user.id)))
                {
                    foreach (TeamAnswer ta in db.TeamAnswers.Where(d => d.teamID.Equals(ut.teamID)))
                    {
                        if (ta.points != null)
                        {
                            userBoard.totalPoints += (int)ta.points;
                        }
                    }
                    userBoard.gameCount++;
                }

                lbm.Add(userBoard);
            }

            return(lbm);
        }
        public static List <LeaderboardModel> GetLeaderboard(string type = null)
        {
            using (IDbConnection con = new SQLiteConnection(SQLiteDataAccess.GetConnectionString()))
            {
                SQLiteDataAccess.InstanceDB();

                LeaderboardModel        vehicleData = new LeaderboardModel();
                List <LeaderboardModel> result      = new List <LeaderboardModel>();
                var allVehicles = con.Query <VehicleModel>("SELECT * FROM vehicletable").ToList();

                if (!string.IsNullOrEmpty(type))
                {
                    allVehicles.RemoveAll(x => !x.Model.Equals(type));
                }

                foreach (VehicleModel v in allVehicles)
                {
                    vehicleData             = new LeaderboardModel();
                    vehicleData.VehicleName = v.TeamName;
                    vehicleData.VehicleType = v.Model;
                    vehicleData.Distance    = v.Distance;
                    vehicleData.Time        = v.Time;
                    vehicleData.Status      = v.VehicleStatus;
                    result.Add(vehicleData);
                }
                return(result);
            }
        }
 public Leaderboard(LeaderboardModel leaderboardModel)
 {
     LeaderboardID          = leaderboardModel.LeaderboardID;
     LeaderBoardName        = leaderboardModel.LeaderBoardName;
     LeaderBoardDescription = leaderboardModel.LeaderBoardDescription;
     UserID = leaderboardModel.UserID;
 }
Beispiel #5
0
 public static UserLeaderboard Create(ApplicationUser user, LeaderboardModel board)
 => new UserLeaderboard
 {
     Id = System.Guid.NewGuid().ToString(),
     // User = user,
     UserId = user.Id,
     // Leaderboard = board,
     LeaderboardId = board.Id,
 };
        public async Task <bool> UpdateParticipantAsync(LeaderboardModel leaderboard, ParticipantModel participant)
        {
            if (participant == null | leaderboard == null)
            {
                return(false);
            }

            return(await _httpManager.PostAsync <bool>(ApiConstants.LeaderboardsURL, participant, ApiConstants.TrainerExtension, leaderboard.ID.ToString()));
        }
        public async Task <bool> RemoveTrainerAsync(LeaderboardModel leaderboard, ParticipantModel participant)
        {
            if (participant == null || leaderboard == null)
            {
                return(false);
            }

            return(await _httpManager.DeleteAsync <bool>(ApiConstants.LeaderboardsURL + ApiConstants.LeagueExtension + leaderboard.ID.ToString() + "/" + ApiConstants.TrainerExtension + participant.Username));
        }
        // GET: Home/ViewLeaderboard
        public ActionResult ViewLeaderboard()
        {
            LeaderboardModel data = new LeaderboardModel()
            {
                users       = db.Users.OrderByDescending(item => item.totDistanceTravelled).Take(10).ToList(),
                leaderboard = db.RouteLeaderboards.OrderByDescending(item => item.participantDistance).Take(10).ToList()
            };

            return(View(data));
        }
        private static void SaveLeaderboardData(LeaderboardModel model)
        {
            string json = JsonUtility.ToJson(model);

            StreamWriter sw = File.CreateText(SavePath());

            sw.Close();

            File.WriteAllText(SavePath(), json);
        }
        public bool AddLeaderBoard(LeaderboardModel model)
        {
            List <string[]> param = new List <string[]>()
            {
                new string[] { "@LeaderBoardName", model.LeaderBoardName },
                new string[] { "@LeaderBoardDescription", model.LeaderBoardDescription }
            };

            sqlConnection.ExecuteNonSearchQueryParameters(" INSERT INTO LeaderBoards (`LeaderBoardName`,`LeaderBoardDescription`) VALUES ( @LeaderBoardName, @LeaderBoardDescription )", param);
            return(true);
        }
        public async Task <bool> InputMatch(LeaderboardModel leaderboard, MatchModel match)
        {
            if (leaderboard == null || match == null)
            {
                return(false);
            }

            var response = await _httpManager.PutAsync <bool>(ApiConstants.LeaderboardsURL, match, extension : ApiConstants.MatchExtension, parameter : leaderboard.ID.ToString());

            return(response);
        }
    public void ShowScores(LeaderboardModel model)
    {
        string nombre;
        string puntos;

        foreach (LeaderboardModel.PlayerScore s in lbm.leaderboard)
        {
            nombre = s.playername;
            puntos = s.score;
            print(nombre + " - " + puntos);
        }
    }
Beispiel #13
0
        public void ClearDatabase()
        {
            using (var context = new SystemDBContext())
            {
                var felixHash = GetFelixHashId();
                // Delete all Maps
                foreach (var id in context.Maps.Where(x => x.CreatorhashId != felixHash).Select(e => e.Id))
                {
                    var entity = new MapModel()
                    {
                        Id = id
                    };
                    context.Maps.Attach(entity);
                    context.Maps.Remove(entity);
                }


                // Delete all Dailies
                foreach (var id in context.Daylies.Where(x => x.UserHashId != felixHash).Select(e => e.Id))
                {
                    var entity = new DailyModel()
                    {
                        Id = id
                    };
                    context.Daylies.Attach(entity);
                    context.Daylies.Remove(entity);
                }

                // Delete all Leaderboards
                foreach (var id in context.Leaderboards.Select(e => e.Id))
                {
                    var entity = new LeaderboardModel()
                    {
                        Id = id
                    };
                    context.Leaderboards.Attach(entity);
                    context.Leaderboards.Remove(entity);
                }

                // Delete all Friends
                foreach (var id in context.Friends.Select(e => e.Id))
                {
                    var entity = new FriendModel()
                    {
                        Id = id
                    };
                    context.Friends.Attach(entity);
                    context.Friends.Remove(entity);
                }

                context.SaveChanges();
            }
        }
Beispiel #14
0
        private LeaderboardModel RecalculatePositions(LeaderboardModel leaderboard)
        {
            var orderedParticipants = leaderboard.Participants.OrderByDescending((participant) => participant.Points);
            int i = 1;

            foreach (ParticipantModel participant in orderedParticipants)
            {
                participant.Position = i++;
            }
            leaderboard.Participants = new ObservableCollection <ParticipantModel>(orderedParticipants);
            return(leaderboard);
        }
Beispiel #15
0
        public IActionResult CreateLeaderboard([FromBody] LeaderboardModel leaderboard)
        {
            var response = _leaderboards.AddLeaderboard(leaderboard);

            switch (response)
            {
            case CreateLeaderboardResponseCode.CreatedSuccessfully:
                return(Ok(response));

            default:
                return(BadRequest(response));
            }
        }
Beispiel #16
0
        private async void RefreshLeaderboard(string resultsId)
        {
            var sw = new Stopwatch();

            sw.Start();

            var leaderboardUpdated = false;

            while (!leaderboardUpdated && sw.ElapsedMilliseconds < 5000)
            {
                var aux = await App.MobileService.GetTable <Result>().Where(r => r.Id == resultsId).ToEnumerableAsync();

                var resultsItem = aux.Single();
                leaderboardUpdated = resultsItem.LeaderboardUpdated;
            }

            sw.Stop();

            if (leaderboardUpdated)
            {
                var leaderboardItems = await App.MobileService.GetTable <Leaderboard>().ToEnumerableAsync();

                leaderboardItems = leaderboardItems.OrderBy(item => item.Position).Take(5);

                var model = new LeaderboardModel();
                foreach (var item in leaderboardItems)
                {
                    model.Items.Add(new LeaderboardItemModel
                    {
                        Player   = item.PlayerName,
                        Position = item.Position,
                        Score    = item.Score
                    });
                }

                this.DataContext = model;

                this.LoadingLeaderboardLegend.Visibility       = Windows.UI.Xaml.Visibility.Collapsed;
                this.LoadingLeaderboardProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.LeaderboardGridView.Visibility            = Windows.UI.Xaml.Visibility.Visible;
            }
            else
            {
                this.LoadingLeaderboardLegend.Visibility       = Windows.UI.Xaml.Visibility.Collapsed;
                this.LoadingLeaderboardProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                var msg = new MessageDialog("The leaderboard could not be retrieved, please check if the server-side script is properly configured on the mobile service.");
                await msg.ShowAsync();
            }
        }
        public bool EditLeaderBoard(LeaderboardModel model)
        {
            List <string[]> param = new List <string[]>()
            {
                new string[] { "@LeaderBoardID", model.LeaderboardID },
                new string[] { "@OwnerID", model.UserID },

                new string[] { "@LeaderBoardName", model.LeaderBoardName },
                new string[] { "@LeaderBoardDescription", model.LeaderBoardDescription }
            };

            sqlConnection.ExecuteNonSearchQueryParameters(" UPDATE LeaderBoards SET `LeaderBoardID` = @LeaderboardID,`OwnerID`= @OwnerID ,`LeaderBoardType` = @LeaderboardType ,`LeaderBoardName` =  @LeaderBoardName ,`LeaderBoardDescription` = @LeaderBoardDescription WHERE `LeaderBoardID` = @LeaderBoardID", param);
            return(true);
        }
Beispiel #18
0
        /*DAVID
         * When a player completes a quiz, they are given the option to view the leaderboard or
         *  add their score to it by entering their name. If the name is entered, it goes to a
         *  player model and stores the name. The rest of the stats are copied from the quiz model.
         *
         *  If they do not enter a name, this method will bypass
         *  adding a player, and just show the current leaderboard.
         */
        public ActionResult AddScore(LeaderboardModel Player)
        {
            if (Player.Name != null)
            {
                //ctrl+click on Leaderboard to see the Model. Inside Model1.edmx/Model1.tt/Leaderboard.cs
                leader = new Leaderboard();

                leader.Name = Player.Name;
                if ((int)Session["Difficulty"] == 3)
                {
                    leader.Difficulty = "Easy";
                }
                else if ((int)Session["Difficulty"] == 5)
                {
                    leader.Difficulty = "Medium";
                }
                else if ((int)Session["Difficulty"] == 10)
                {
                    leader.Difficulty = "Hard";
                }
                leader.Genre      = Session["Genre"].ToString();
                leader.Questions  = Convert.ToInt32(Session["QuestionCount"]);
                leader.Correct    = Convert.ToInt32(Session["AnswersCorrect"]);
                leader.Percentage = Convert.ToDouble(Session["Percent"]);
                leader.Score      = (Convert.ToInt32(Session["AnswersCorrect"]) * Convert.ToInt32(Session["Difficulty"]));
                try
                {
                    //DAVID
                    //tries to pass the leader object to the addscores() action result in the
                    //leaderboard controller.
                    return(RedirectToAction("AddScores", "Leaderboards", leader));
                }
                catch
                {
                    return(RedirectToAction("Index"));
                }
            }
            //DAVID  -- if no name is given by the player then this
            //tries to redirect to LeaderboardController/Index, if it fails go to Home
            try
            {
                return(RedirectToAction("Index", "LeaderboardsController"));
            }
            catch
            {
                return(RedirectToAction("Index"));
            }
        }
    public void ShowLeaderboard(LeaderboardModel leaderboardModel)
    {
        var playerResultModels = leaderboardModel.GetResults();

        foreach (var resultModel in playerResultModels)
        {
            var panel   = Instantiate(_resultPanelPrefab, _content.transform);
            var lbPanel = panel.GetComponent <LeaderboardPanel>();

            lbPanel.TextID.text    = resultModel.id;
            lbPanel.TextWins.text  = resultModel.answerCount.ToString();
            lbPanel.TextTimes.text = TimeSpan.FromSeconds(resultModel.gameTime).ToString();

            _resultPanels.Add(panel);
        }
    }
        public async Task <AddTrainerResponseCode> AddTrainerAsync(LeaderboardModel leaderboard, TrainerModel trainer)
        {
            if (trainer == null || leaderboard == null)
            {
                return(AddTrainerResponseCode.UnknownError);
            }

            var participant = new ParticipantModel()
            {
                Username = trainer.Username,
                Level    = trainer.Level
            };
            var response = await _httpManager.PutAsync <AddTrainerResponseCode>(ApiConstants.LeaderboardsURL, trainer, extension : ApiConstants.TrainerExtension, parameter : leaderboard.ID.ToString());

            return(response);
        }
Beispiel #21
0
        public ActionResult FilterBoard(LeaderboardModel model)
        {
            var cacheKey = string.Format(CacheKeys.ChallengerTierLeagueKey, model.Region, model.GameQueueType);

            var challengers = _cacheManager.Get(cacheKey, DateTime.UtcNow.AddMinutes(60),
                                                () =>
                                                _riotClient.League.GetChallengerTierLeagues(model.Region, model.GameQueueType));

            //get top 40 leaderboard using LINQ
            var top40 = challengers.Entries.OrderByDescending(x => x.LeaguePoints).Take(40).ToList();

            model.LeagueDto = challengers;
            PrepareModel(model.Region, model.GameQueueType, model, top40);
            //top 100 leaderboard
            return(View("Index", model));
        }
Beispiel #22
0
        private LeaderboardModel RecalculatePoints(LeaderboardModel leaderboard, ParticipantModel winner, ParticipantModel loser)
        {
            double pointsDifference   = winner.Points - loser.Points;
            double compensationPoints = (int)Math.Round(pointsDifference / 30);

            compensationPoints = Math.Clamp(compensationPoints, -10, 2);
            var resultPoints = (int)(5 - compensationPoints);

            var winnerIndex = leaderboard.Participants.IndexOf(winner);

            leaderboard.Participants[winnerIndex] = AddWin(winner, resultPoints);

            var loserIndex = leaderboard.Participants.IndexOf(loser);

            leaderboard.Participants[loserIndex] = AddLoss(loser, resultPoints);
            return(leaderboard);
        }
Beispiel #23
0
    private IEnumerator GetLeaderboard(string level)
    {
        UnityWebRequest www = UnityWebRequest.Get(URL + API_VERSION + "leaderboard/" + level);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            // some method to cath error (pending)
            Debug.LogError(www.error);
        }
        else
        {
            // Show results as text
            leaderboardModel = LeaderboardModel.CreateFromJSON(www.downloadHandler.text);
            FillLeaderboard();
        }
    }
        private void PrepareLeaderboardModel(List <LeaderboardModel> model, IList <Leaderboard> leaderboard)
        {
            var previousPosition = 0;
            var previousScore    = 0;

            foreach (var row in leaderboard)
            {
                var item = new LeaderboardModel
                {
                    Position = previousScore != row.Score ? (previousPosition += 1) : previousPosition,
                    Username = row.Student.Username,
                    Score    = row.Score
                };

                previousScore = item.Score;

                model.Add(item);
            }
        }
        public List <LeaderboardModel> GetLeaderBoards()
        {
            List <LeaderboardModel> Leaderboards = new List <LeaderboardModel>();
            List <string[]>         result       = sqlConnection.ExecuteSearchQueryWithArrayReturn("SELECT * FROM LeaderBoards", new List <string[]>());

            foreach (string[] row in result)
            {
                LeaderboardModel leaderboards = new LeaderboardModel();
                leaderboards.LeaderboardID = row[0].ToString();
                leaderboards.UserID        = row[1].ToString();

                leaderboards.LeaderBoardDescription = row[3].ToString();
                leaderboards.LeaderBoardName        = row[4].ToString();


                Leaderboards.Add(leaderboards);
            }

            return(Leaderboards);
        }
Beispiel #26
0
        public CreateLeaderboardResponseCode AddLeaderboard(LeaderboardModel leaderboard)
        {
            if (leaderboard == null || leaderboard.Participants == null)
            {
                return(CreateLeaderboardResponseCode.UnknownError);
            }

            if (_database.GetLeaderboards().Any(board => board.Name == leaderboard.Name))
            {
                return(CreateLeaderboardResponseCode.NameAlreadyUsed);
            }

            if (_database.AddLeaderboard(leaderboard))
            {
                return(CreateLeaderboardResponseCode.CreatedSuccessfully);
            }
            else
            {
                return(CreateLeaderboardResponseCode.UnknownError);
            }
        }
        public async Task <CreateLeaderboardResponseCode> CreateLeaderboardAsync(string name, LeagueTypesEnum leagueType, ParticipantModel creator)
        {
            if (creator == null)
            {
                return(CreateLeaderboardResponseCode.UnknownError);
            }

            creator.IsAdmin = true;
            var leaderboard = new LeaderboardModel()
            {
                LeagueType   = leagueType,
                Name         = name,
                Participants = new ObservableCollection <ParticipantModel>()
                {
                    creator
                }
            };
            var response = await _httpManager.PutAsync <CreateLeaderboardResponseCode>(ApiConstants.LeaderboardsURL, leaderboard);

            return(response);
        }
        /// <summary>
        /// Create a new map in database and return it's hashid
        /// </summary>
        /// <param name="mapModel"></param>
        /// <returns></returns>
        public string CreateNewMap(MapModel mapModel)
        {
            if (!IsValid(mapModel))
            {
                throw HttpResponseExceptionHelper.Create("Invalid map model information", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                // set hash
                mapModel.CreatorhashId = UserToken.UserId;
                mapModel.HashId        = GetMapHash(mapModel);

                if (db.Maps.FirstOrDefault(x => x.HashId == mapModel.HashId) != null)
                {
                    throw HttpResponseExceptionHelper.Create(
                              "Map already exist with name : " + mapModel.Name + "  From user : " + UserToken.Username,
                              HttpStatusCode.BadRequest);
                }

                mapModel.CreationDate = TimeHelper.CurrentCanadaTimeString();
                mapModel.UpdateTime   = TimeHelper.CurrentCanadaTime();

                // save database
                db.Maps.Add(mapModel);
                db.SaveChanges();

                // create leaderboard for map
                var leaderboard = new LeaderboardModel()
                {
                    ZoneHashId = mapModel.HashId,
                    Leaders    = LeaderboardModelHelper.GetLeaderString(new List <LeaderModel>())
                };

                db.Leaderboards.Add(leaderboard);
                db.SaveChanges();

                return(mapModel.HashId);
            }
        }
        public async Task TestModifyAndDelete(LeaderboardModel leaderboard)
        {
            using var _ = CreateScope(out var scope);
            var ctx = scope.GetRequiredService <ApplicationDbContext>();
            var set = ctx.Leaderboards;

            // we don't care which division/uom we use for the purpose of this test
            leaderboard.DivisionId = (await ctx.Divisions.AsQueryable().SingleAsync(d => d.Id == "11a38bd5-49f1-4718-bd65-ab795da6fe26").ConfigureAwait(false)).Id;
            leaderboard.UOMId      = (await ctx.UnitsOfMeasure.FirstAsync().ConfigureAwait(false)).Id;

            // add board
            await set.AddAsync(leaderboard).ConfigureAwait(false);

            await ctx.SaveChangesAsync().ConfigureAwait(false);

            Assert.Contains(leaderboard, set.WhereActive());

            // modify board
            leaderboard.Name = $"{leaderboard.Name} 2";
            set.Update(leaderboard);
            await ctx.SaveChangesAsync().ConfigureAwait(false);

            Assert.True(leaderboard.IsActive);

            // remove and refresh from the database.
            set.Remove(leaderboard);
            await ctx.SaveChangesAsync().ConfigureAwait(false);

            // IDbActive should set it to inactive rather than actually deleting it
            ctx.Entry(leaderboard).State = EntityState.Detached;
            leaderboard = await set.FindAsync(leaderboard.Id).ConfigureAwait(false);

            Assert.False(leaderboard.IsActive);

            // Sinces it's inactive, this should return nothing
            ctx.Entry(leaderboard).State = EntityState.Detached;
            leaderboard = await set.FindActiveAsync(leaderboard.Id).ConfigureAwait(false);

            Assert.Null(leaderboard);
        }
Beispiel #30
0
        // GET: Leaderboard
        public ActionResult Index()
        {
            var cacheKey = string.Format(CacheKeys.ChallengerTierLeagueKey, RiotApiConfig.Regions.EUNE,
                                         Enums.GameQueueType.RANKED_SOLO_5x5);

            var challengers = _cacheManager.Get(cacheKey, DateTime.UtcNow.AddMinutes(60),
                                                () =>
                                                _riotClient.League.GetChallengerTierLeagues(RiotApiConfig.Regions.EUNE,
                                                                                            Enums.GameQueueType.RANKED_SOLO_5x5));
            //get top 40 leaderboard using LINQ
            var top40 = challengers.Entries.OrderByDescending(x => x.LeaguePoints).Take(40).ToList();
            LeaderboardModel model = new LeaderboardModel
            {
                Region        = RiotApiConfig.Regions.EUNE,
                GameQueueType = Enums.GameQueueType.RANKED_SOLO_5x5,
                LeagueDto     = challengers
            };

            PrepareModel(model.Region, model.GameQueueType, model, top40);
            //top 100 leaderboard
            return(View(model));
        }