Beispiel #1
0
 private static void CheckIfCurrentCellPositionIsLadderStart(Player player)
 {
     if (Ladders.CheckIfCurrentCellPositionIsLadderStart(player.GetCurrentCellPosition()))
     {
         player.SetCurrentCellPosition(Ladders.GetLadderEndForLadderStart(player.GetCurrentCellPosition()));
     }
 }
 public async Task <IList <Ladder> > GetLaddersAsync()
 {
     return(await Ladders.Include(x => x.LadderPlayers)
            .ThenInclude(x => x.Player)
            .Include(x => x.Matches)
            .ThenInclude(x => x.MatchTeams)
            .ThenInclude(x => x.Team.TeamPlayers)
            .ThenInclude(x => x.Player)
            .ToListAsync());
 }
 public async Task <Ladder> GetLadderAsync(int id)
 {
     return(await Ladders.Include(x => x.LadderPlayers)
            .ThenInclude(x => x.Player)
            .Include(x => x.Matches)
            .ThenInclude(x => x.MatchTeams)
            .ThenInclude(x => x.Team.TeamPlayers)
            .ThenInclude(x => x.Player)
            .SingleOrDefaultAsync(x => x.Id == id));
 }
Beispiel #4
0
        private static void ParseLaddersFromInput()
        {
            int numberOfLadders = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfLadders; i++)
            {
                var laddersStartAndEndPositionAsString      = Console.ReadLine();
                var laddersStartAndEndPositionAsStringArray = laddersStartAndEndPositionAsString.Split(' ');
                Ladders.PopulateLaddersStartAndEndPostions(int.Parse(laddersStartAndEndPositionAsStringArray[0]), int.Parse(laddersStartAndEndPositionAsStringArray[1]));
            }
        }
        void HandleUserRankUpdated(Task <RequestWrapper <UserRank> > updateTask, Ladders userRankMode, UserGameProfileId userGameProfileId)
        {
            Dictionary <string, object> logProperties = null;

            //unahndled exception inside task scope
            if (updateTask.IsFaulted || updateTask.IsCanceled)
            {
                if (updateTask.Exception != null)
                {
                    logProperties = new Dictionary <string, object>
                    {
                        { "exception", updateTask.Exception.ToString() },
                        { "stack", updateTask.Exception.StackTrace }
                    };
                }

                LogService.Error("HandleUserDataUpdated: Internal task processing exception", logProperties ?? null);
                return;
            }

            //handled exception
            if (!updateTask.Result.IsSuccess)
            {
                if (updateTask.Exception != null)
                {
                    logProperties = new Dictionary <string, object>
                    {
                        { "exception", updateTask.Exception.ToString() },
                        { "stack", updateTask.Exception.StackTrace }
                    };
                }

                LogService.Warning("HandleUserDataUpdated: Unable to complete task successfully", logProperties);
                return;
            }

            if (updateTask.Exception != null)
            {
                LogService.Warning("Error while updating user rating: ");
                return;
            }

            UserData userRankData = new UserData();

            userRankData.UserRatings.Add(userRankMode, updateTask.Result.Value);

            //publish rating change event
            EventAggregator.GetEvent <UserRatingChangedEvent>().Publish(Tuple.Create(userGameProfileId, userRankData));
        }
        private void SetLaddersOnGame(List <List <int> > ladderIndices)
        {
            foreach (var ladderIndex in ladderIndices)
            {
                if (Ladders.Any(x => x.Start == ladderIndex[0]))
                {
                    //Skipping two Ladder starts at same point
                    continue;
                }

                Ladders.Add(new Ladder()
                {
                    Start = ladderIndex[0],
                    End   = ladderIndex[1]
                });
            }
        }
Beispiel #7
0
 public void AddLadder(Ladder L)
 {
     Ladders.Add(L);
 }
 public void SetupLadders(int down, int up)
 {
     Ladders.Add(down, up);
 }
        public static UserRank GetUserRank(this IEnumerable <UserMatchData> userMatchDatas, UserGameProfileId userGameProfileId, Ladders userRankMode)
        {
            var userMatchData = userMatchDatas.First
                                    (umd => umd.UserGameProfileId.ProfileId == userGameProfileId.ProfileId);

            if (userMatchData == null)
            {
                return(null);
            }

            if (!(userMatchData.UserRankData.UserRatings.ContainsKey(userRankMode)))
            {
                return(null);
            }

            return(userMatchData.UserRankData.UserRatings[userRankMode]);
        }
        async Task UpdateUsersRank()
        {
            var logProperties = new Dictionary <string, object>
            {
                { "threadId", Thread.CurrentThread }
            };

            LogService.Debug("Starting user rank update tasks", logProperties);

            List <Task> updateTasks = new List <Task>();

            Ladders userRankModeToUpadte = Ladders.RandomMap;

            switch (matchType)
            {
            //if game is 1v1 then all data is processed from match request, so we don't have to update anything
            case MatchType.RandomMap:
                LogService.Debug("Skiping update", logProperties);
                return;

            case MatchType.Deathmatch:
                LogService.Debug("skiping update", logProperties);
                return;

            //update 1v1 ratings for team matches
            case MatchType.TeamdeathMatch:
                userRankModeToUpadte = Ladders.Deathmatch;
                break;

            case MatchType.TeamRandomMap:
                userRankModeToUpadte = Ladders.RandomMap;
                break;

            //update 1v1
            case MatchType.Unranked:
                userRankModeToUpadte = Ladders.RandomMap;
                break;

            //if match is custom game (any unraked, includes all "quick match" types) then use Random map rating (most reliable type across rating types)
            default:
                //userRankModeToUpadte = UserRankMode.RandomMap;
                break;
            }

            int userELOUpdateTimeout = AppConfigurationService.DefaultRequestTimeout;

            foreach (var user in UserMatchData)
            {
                //update primary/secondary ELO
                LogService.Info($"Starting user ELO update: for user id: {user.UserGameProfileId} user rank mode to update: {userRankModeToUpadte}, operation timeout: {userELOUpdateTimeout}");

                var userDataUpdateTask = UserRankService.GetUserRankFromLadder(user.UserGameProfileId, userRankModeToUpadte, userELOUpdateTimeout);

                updateTasks.Add(
                    userDataUpdateTask.ContinueWith(
                        t => HandleUserRankUpdated(userDataUpdateTask, userRankModeToUpadte, user.UserGameProfileId)
                        )
                    );
            }

            await Task.WhenAll(updateTasks);

            LogService.Trace("All rank updates has been completed", logProperties);
        }
        UserRank IUserDataProcessingService.ProcessUserRankFromLadder(string jsonResponse, Ladders ladder, AoeNetAPIStringResources apiStringResources)
        {
            var ratingResponse = JsonConvert.DeserializeObject <UserLadderDataResponse>(jsonResponse);

            //response to UserRank model
            var userRank = new UserRank
            {
                //we always want to use .First() becouse api don't allow for multiple requests between multiple leadboards
                Elo    = ratingResponse.Leaderboard.First().Rating,
                Ladder = ratingResponse.Leaderboard.First().Rank
            };

            var userRankData = new UserData();

            userRankData.UserRatings.Add(ladder, userRank);

            return(userRank);
        }
        public async Task <RequestWrapper <UserLadderData> > GetUserDataFromLadder(UserGameProfileId userGameProfileId, Ladders ladder, int timeout)
        {
            ValidateCacheState();

            RequestWrapper <UserLadderData> requestWrapper = new RequestWrapper <UserLadderData>();
            Dictionary <string, object>     logProperties  = new Dictionary <string, object>
            {
                { "timeout", timeout },
                { "game-profile-id", userGameProfileId.ProfileId },
                { "ladder", ladder.ToString() }
            };

            RequestState requestState = null;

            try
            {
                if (!StorageService.Has("stringResources"))
                {
                    throw new InvalidOperationException("App resources unaviable while sending request");
                }

                if (string.IsNullOrEmpty(userGameProfileId.ProfileId))
                {
                    throw new InvalidOperationException("Missing user id");
                }

                var stringResources = StorageService.Get <AoeNetAPIStringResources>("stringResources");

                //preapare query
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["profile_id"]     = HttpUtility.UrlEncode(userGameProfileId.ProfileId);
                query["leaderboard_id"] = HttpUtility.UrlEncode(((int)ladder).ToString());
                query["game"]           = HttpUtility.UrlEncode("aoe2de"); //only aviable for DE at this moment, https://aoe2.net/#api

                var finallQuery = "https://aoe2.net/api/leaderboard?" + query.ToString();
                logProperties.Add("query", finallQuery);

                //create cts
                var cts = new CancellationTokenSource();
                //create timeout handler for current query
                requestState = AddTimeoutHandler(cts, timeout);

                requestState.isRunning    = true;
                requestWrapper.RequestUrl = finallQuery;
                //sumbit query via query cache service
                requestWrapper.RequestResponseWrapper = await QueryCacheService.GetOrUpdate(
                    finallQuery,
                    cts.Token,
                    DateTime.UtcNow.AddHours(1.5)
                    );

                if (!requestWrapper.RequestResponseWrapper.IsSuccess)
                {
                    throw new AggregateException("Request failed", requestWrapper.RequestResponseWrapper.Exception);
                }

                requestWrapper.Value = (this as IUserDataProcessingService).ProcessUserDataFromLadder(requestWrapper.RequestResponseWrapper.ResponseContent, stringResources);
            }
            catch (Exception e) // request timedout
            {
                if (
                    e is StackOverflowException ||
                    e is ThreadAbortException ||
                    e is AccessViolationException
                    )
                {
                    throw e;
                }

                string responseContent = "";
                string responseCode    = "";

                if (requestWrapper != null) //to make sure this will not conflict with test cases
                {
                    if (requestWrapper.RequestResponseWrapper != null)
                    {
                        if (requestWrapper.RequestResponseWrapper.ResponseContent != null)
                        {
                            responseContent = requestWrapper.RequestResponseWrapper.ResponseContent;
                        }

                        if (requestWrapper.RequestResponseWrapper.Response != null) //to make sure this will not conflict with test cases
                        {
                            responseCode = requestWrapper.RequestResponseWrapper.Response.StatusCode.ToString();
                        }
                    }
                }

                logProperties.Add("stack", e.StackTrace);
                logProperties.Add("response-code", responseCode);
                logProperties.Add("response-raw", responseContent);
                LogService.Error($"Error while requesting ladder: {e.ToString()}", logProperties);

                requestWrapper.Exception = e;
            }
            finally
            {
                if (requestState != null)
                {
                    requestState.isRunning = false; //prevent cancelling operation by timeout handler
                }
            }

            return(requestWrapper);
        }