Beispiel #1
0
        public static string NewString(string prefix = default)
        {
            const int randomGuidStringMaxLength = 8;
            const int randomGuidMaxByteLength   = 3;

            //
            if (string.IsNullOrEmpty(prefix))
            {
                return(GuidUtilities.NewGuidString(count: randomGuidMaxByteLength));
            }
            else
            {
                var prefixLastChar   = prefix.LastChar().Value;
                var randomGuidLength = Math.Min(MaxLength - prefix.Length - (prefixLastChar == '-' ? 0 : 1), randomGuidStringMaxLength);
                if (randomGuidLength > 0)
                {
                    EnsureValid(id: prefix.Arg(nameof(prefix)));
                    var randomStringSeed = GuidUtilities.NewGuidString(count: randomGuidMaxByteLength);
                    return
                        (prefixLastChar == '-'
                                                ? prefix + randomStringSeed.Left(length: randomGuidLength)
                                                : prefix + "-" + randomStringSeed.Left(length: randomGuidLength));
                }
                else
                {
                    throw
                        new ArgumentException(
                            message: FormatXResource(typeof(string), "TooLong/MaxLength", (MaxLength - 2).ToString()),
                            paramName: nameof(prefix));
                }
            }
        }
Beispiel #2
0
 private static List <DivisionCategory> GenerateDivisionCategories(List <Division> divisions, string categoryId)
 => divisions.Select(d => new DivisionCategory
 {
     Id         = GuidUtilities.Create($"dc_{d.Id}{categoryId}").ToString(),
     CategoryId = categoryId,
     DivisionId = d.Id
 }).ToList();
Beispiel #3
0
 private static IEnumerable <UserCategory> GenerateUserCategories(string categoryId, params ApplicationUser[] users)
 => users.Select(u => new UserCategory
 {
     Id         = GuidUtilities.Create($"uc{u.Id}{categoryId}").ToString(),
     UserId     = u.Id,
     CategoryId = categoryId
 });
Beispiel #4
0
        private static IEnumerable <ScoreModel> GenerateScores(List <UserLeaderboard> userBoards)
        {
            // sudo random number generation. Always seed with 1, so the calls to Next are predictable
            var rand = new Random(1);
            var now  = DateTime.UtcNow;

            foreach (var board in userBoards)
            {
                for (var i = 0; i < 10; i++)
                {
                    var createdDaysSeed         = rand.Next(1, 500);
                    var createdMillisecondsSeed = rand.Next(1, 1439999);
                    var created      = now.AddDays(-createdDaysSeed).AddMilliseconds(-createdMillisecondsSeed);
                    var approvedDate = i % 2 == 0 ? (DateTime?)created.AddDays(1) : null;
                    yield return(new ScoreModel
                    {
                        Id = GuidUtilities.Create($"score_{board.UserId}{board.LeaderboardId}{i}").ToString(),
                        ApprovedDate = approvedDate,
                        UserId = board.UserId,
                        BoardId = board.LeaderboardId,
                        CreatedDate = created,
                        Value = Convert.ToDecimal(rand.NextDouble() * rand.Next(200, 1500))
                    });
                }
            }
        }
        public void TestVariant1GuidEncoding()
        {
            var guid          = Guid.Parse("00112233-4455-6677-8899-aabbccddeeff");
            var variant1Bytes = guid.ToVariant1ByteArray();

            variant1Bytes.ShouldBe(new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff });

            var decodedGuid = GuidUtilities.CreateFromVariant1ByteArray(variant1Bytes);

            decodedGuid.ShouldBe(guid);
        }
Beispiel #6
0
        private static async IAsyncEnumerable <ApplicationRole> GetOrCreateRoles(this AppRoleManager manager, params string[] roleNames)
        {
            foreach (var roleName in roleNames)
            {
                var role = new ApplicationRole(roleName)
                {
                    Id = GuidUtilities.Create($"role_{roleName}").ToString()
                };
                await manager.TryCreateByNameAsync(role).ConfigureAwait(false);

                yield return(role);
            }
        }
Beispiel #7
0
        private static async IAsyncEnumerable <ApplicationUser> GetOrCreateUsers(this AppUserManager manager, GenderValue?gender, params string[] userNames)
        {
            foreach (var userName in userNames)
            {
                var user = new ApplicationUser(userName)
                {
                    Id       = GuidUtilities.Create($"u_{userName}").ToString(),
                    Gender   = gender,
                    IsActive = true
                };
                await manager.CreateOrUpdateByNameAsync(user, "Password123").ConfigureAwait(false);

                yield return(user);
            }
        }
Beispiel #8
0
 private static async IAsyncEnumerable <UserLeaderboard> GenerateUserLeaderboards(
     IAsyncEnumerable <ValueTuple <ApplicationUser, List <LeaderboardModel> > > users)
 {
     await foreach ((var user, var boards) in users)
     {
         foreach (var board in boards)
         {
             yield return new UserLeaderboard
                    {
                        Id            = GuidUtilities.Create($"ub_{board.Id}{user.Id}").ToString(),
                        UserId        = user.Id,
                        LeaderboardId = board.Id
                    }
         }
     }
     ;
 }
Beispiel #9
0
        /// <summary>
        /// If either divisions/weightclasses are null, will add a single board with a null value for that property
        /// </summary>
        /// <param name="uomId"></param>
        /// <param name="divisions"></param>
        /// <param name="weightClasses"></param>
        /// <param name="boardNames"></param>
        /// <returns></returns>
        private static IEnumerable <LeaderboardModel> GenerateLeaderboards(
            string uomId,
            List <Division> divisions,
            List <WeightClass> weightClasses,
            params string[] boardNames)
        {
            divisions ??= new List <Division> {
                null
            };
            weightClasses ??= new List <WeightClass> {
                null
            };

            var allCombinations = from d in divisions
                                  from wc in weightClasses
                                  select(d, wc);

            var count = allCombinations.Count();

            LeaderboardModel generateBoard(
                string name,
                string divisionId,
                string weightClassId
                ) => new LeaderboardModel
            {
                Id            = GuidUtilities.Create($"lb_{weightClassId}{divisionId}{name}").ToString(),
                Name          = name,
                IsActive      = true,
                WeightClassId = weightClassId,
                DivisionId    = divisionId,
                UOMId         = uomId
            };

            foreach ((var division, var weightClass) in allCombinations.Distinct())
            {
                foreach (var boardName in boardNames)
                {
                    yield return(generateBoard(boardName, division?.Id, weightClass?.Id));
                }
            }
        }
Beispiel #10
0
    public void OnLogin(IMinecraftUser user, IMinecraftPacket packet)
    {
        string username = packet.ReadString();

        _logger.LogInformation($"{user.Username} trying to log-in");

        if (_serverConfiguration.Value.Mode == ServerModeType.Offline)
        {
            if (_serverConfiguration.Value.AllowMultiplayerDebug)
            {
                int count = _server.ConnectedPlayers.Count(x => x.Username.StartsWith(username));

                if (count > 0 && _server.ConnectedPlayers.Any(x => x.Username.Equals(username)))
                {
                    username = $"{username} ({count})";
                }
            }
            else
            {
                if (_server.HasUser(username))
                {
                    user.Disconnect($"A player with the same name '{username}' is already connected.");
                    return;
                }
            }

            Guid playerId = GuidUtilities.GenerateGuidFromString($"OfflinePlayer:{username}");

            // TODO: initialize current player
            // TODO: Read player data from storage (DB or file-system)
            user.LoadPlayer(playerId, username);

            // DEBUG
            user.Player.Position.X = 8;
            user.Player.Position.Y = 2;
            user.Player.Position.Z = 8;

            SendLoginSucess(user);
            user.UpdateStatus(MinecraftUserStatus.Play);
            _server.Events.OnPlayerJoinGame(new PlayerJoinEventArgs(user.Player));

            SendJoinGame(user);
            SendServerBrand(user);
            // TODO: held item changed
            // TODO: declare recipes
            // TODO: Tags
            // TODO: Entity status
            // TODO: declare commands
            // TODO: Unlock recipes
            SendPlayerPositionAndLook(user, user.Player.Position);
            SendPlayerInfo(user, PlayerInfoActionType.Add);
            SendPlayerInfo(user, PlayerInfoActionType.UpdateLatency);
            SendUpdateViewPosition(user);
            // TODO: Update light
            SendChunkData(user);
            SendUpdateViewPosition(user);
            // TODO: World border
            SendSpawnPosition(user, Position.Zero);
            SendPlayerPositionAndLook(user, user.Player.Position);

            user.Player.IsSpawned = true;
        }
        else
        {
            // TODO: login to Mojang API
        }
    }