long.Parse(string, System.Globalization.NumberStyles, System.IFormatProvider)

Here are the examples of the csharp api long.Parse(string, System.Globalization.NumberStyles, System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

643 Examples 7

19 View Source File : GameService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task Move(Game.MoveCommand command, CancellationToken cancellationToken = default)
        {
            var (session, id, move) = command;
            var context = CommandContext.GetCurrent();

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);
            var dbGame = await GetDbGame(dbContext, id, cancellationToken);
            var game = dbGame.ToModel();
            var engine = GameEngines[game.EngineId];

            if (game.Stage != GameStage.Playing)
                throw new InvalidOperationException("Game has already ended or hasn't started yet.");
            var player = game.Players.SingleOrDefault(p => p.UserId == userId);
            if (player == null)
                throw new InvalidOperationException("You aren't a participant of this game.");
            var playerIndex = game.Players.IndexOf(player);
            var now = Clock.Now;
            move = move with {
                PlayerIndex = playerIndex,
                Time = now,
            };

            context.Operation().Items.Set(Box.New(game.Stage)); // Saving prev. stage
            game = engine.Move(game, move) with { LastMoveAt = now };
            if (game.Stage == GameStage.Ended)
                game = game with { EndedAt = now };
            dbGame.UpdateFrom(game);
            await dbContext.SaveChangesAsync(cancellationToken);
            context.Operation().Items.Set(game);
        }

19 View Source File : AccountAppService.cs
License : MIT License
Project Creator : AlphaYu

public async Task<UserInfoDto> GetUserInfoAsync(long id)
        {
            var userProfile = await _userRepository.FetchAsync(u => new UserProfileDto
            {
                Account = u.Account,
                Avatar = u.Avatar,
                Birthday = u.Birthday,
                DeptId = u.DeptId,
                DeptFullName = u.Dept.FullName,
                Email = u.Email,
                Name = u.Name,
                Phone = u.Phone,
                RoleIds = u.RoleIds,
                Sex = u.Sex,
                Status = u.Status
            }, x => x.Id == id);

            if (userProfile == null)
                return null;

            var userInfoDto = new UserInfoDto { Id = id, Profile = userProfile };

            if (userProfile.RoleIds.IsNotNullOrEmpty())
            {
                var roleIds = userProfile.RoleIds.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x));
                var roles = await _roleRepository
                                                .Where(x => roleIds.Contains(x.Id))
                                                .Select(r => new { r.Id, r.Tips, r.Name })
                                                .ToListAsync();
                foreach (var role in roles)
                {
                    userInfoDto.Roles.Add(role.Tips);
                    userInfoDto.Profile.Roles.Add(role.Name);
                }

                var roleMenus = await _menuRepository.GetMenusByRoleIdsAsync(roleIds.ToArray(), true);
                if (roleMenus.IsNotNullOrEmpty())
                    userInfoDto.Permissions.AddRange(roleMenus.Select(x => x.Url).Distinct());
            }

            return userInfoDto;
        }

19 View Source File : HomeActionHandler.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

private static void UpdateAllPortals(GameSession session)
    {
        foreach (IFieldObject<Portal> fieldPortal in session.FieldManager.State.Portals.Values)
        {
            session.FieldManager.RemovePortal(fieldPortal);
        }

        // Re-add cube portals in map
        IEnumerable<IFieldObject<Cube>> fieldCubePortals = session.FieldManager.State.Cubes.Values.Where(x => x.Value.Item.Id == 50400158);
        foreach (IFieldObject<Cube> fieldCubePortal in fieldCubePortals)
        {
            Cube cubePortal = fieldCubePortal.Value;
            Portal portal = new(GuidGenerator.Int())
            {
                IsVisible = true,
                IsEnabled = true,
                IsMinimapVisible = false,
                Rotation = cubePortal.Rotation,
                PortalType = PortalTypes.Home,
                UGCPortalMethod = cubePortal.PortalSettings.Method
            };

            IFieldObject<Portal> fieldPortal = session.FieldManager.RequestFieldObject(portal);
            fieldPortal.Coord = cubePortal.CoordF;
            if (!string.IsNullOrEmpty(cubePortal.PortalSettings.DestinationTarget))
            {
                switch (cubePortal.PortalSettings.Destination)
                {
                    case UGCPortalDestination.PortalInHome:
                        fieldPortal.Value.TargetMapId = (int) Map.PrivateResidence;
                        break;
                    case UGCPortalDestination.SelectedMap:
                        fieldPortal.Value.TargetMapId = int.Parse(cubePortal.PortalSettings.DestinationTarget);
                        break;
                    case UGCPortalDestination.FriendHome:
                        fieldPortal.Value.TargetHomeAccountId = long.Parse(cubePortal.PortalSettings.DestinationTarget);
                        break;
                }
            }
            cubePortal.PortalSettings.PortalObjectId = fieldPortal.ObjectId;
            session.FieldManager.AddPortal(fieldPortal);
        }
    }

19 View Source File : ChatService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<ChatPermission> GetPermissions(
            Session session, string chatId, CancellationToken cancellationToken = default)
        {
            var user = await AuthService.GetUser(session, cancellationToken);
            if (!user.IsAuthenticated)
                return 0;
            var chat = await TryGet(chatId, cancellationToken);
            if (chat == null || chat.Kind == ChatKind.Unknown)
                return 0;

            var userId = long.Parse(user.Id);
            if (chat.OwnerIds.Contains(userId))
                return ChatPermission.Owner;
            if (chat.ParticipantIds.Contains(userId))
                return ChatPermission.Write;
            if (chat.Kind == ChatKind.Game)
                return ChatPermission.Write;
            return 0;
        }

19 View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void EndTransaction()
        {
            Task.Run(async () =>
            {
                Debug.WriteLine("Ending Super Indexer Transaction...");

                var result = this.WaitingOnGroupAndChatListings.WaitOne(TimeSpan.FromSeconds(10));

                if (!result)
                {
                    Debug.WriteLine("No group list available, loading new...");

                    var client = this.GroupsAndChats.FirstOrDefault()?.Client;
                    if (client == null)
                    {
                        return;
                    }

                    await client.GetGroupsAsync();
                    await client.GetChatsAsync();
                    this.GroupsAndChats = Enumerable.Concat<IMessageContainer>(client.Groups(), client.Chats());
                }

                this.OutdatedGroupIdList = this.CheckForOutdatedCache(this.GroupsAndChats);

                Debug.WriteLine("Dirty groups computed, count " + this.OutdatedGroupIdList.Count);

                using (var context = this.CacheManager.OpenNewContext())
                {
                    // Update Group and Chat metadata in cache
                    if (DateTime.Now.Subtract(this.LastMetadataUpdate) > this.SettingsManager.CoreSettings.MetadataCacheInterval)
                    {
                        this.LastMetadataUpdate = DateTime.Now;

                        // Remove old metadata. Doing a removal and addition in the same cycle was causing
                        // OtherUserId foreign key for Chats to be null. Doing true updates with cascading deletes
                        // should be possible, but this can be done easily in SQLite without any further migrations (GMDC 33.0.3)
                        foreach (var metaData in this.GroupsAndChats)
                        {
                            if (metaData is Group groupMetadata)
                            {
                                var existing = context.GroupMetadata
                                    .Include(g => g.Members)
                                    .FirstOrDefault(g => g.Id == groupMetadata.Id);
                                if (existing != null)
                                {
                                    foreach (var member in existing.Members)
                                    {
                                        context.Remove(member);
                                    }

                                    context.GroupMetadata.Remove(existing);
                                }
                            }
                            else if (metaData is Chat chatMetadata)
                            {
                                var existingChat = context.ChatMetadata.FirstOrDefault(c => c.Id == metaData.Id);
                                if (existingChat != null)
                                {
                                    context.Remove(existingChat);
                                }

                                var existingMember = context.Find<Member>(chatMetadata.OtherUser.Id);
                                if (existingMember != null)
                                {
                                    context.Remove(existingMember);
                                }
                            }
                        }

                        context.SaveChanges();

                        foreach (var addMetaData in this.GroupsAndChats)
                        {
                            context.Add(addMetaData);
                        }

                        context.SaveChanges();
                    }

                    // Process updates for each group and chat
                    var fullyUpdatedGroupIds = new List<string>();
                    foreach (var id in this.GroupUpdates.Keys)
                    {
                        var messages = this.GroupUpdates[id];
                        var groupState = context.IndexStatus.Find(id);
                        if (groupState == null)
                        {
                            // No cache status exists for this group. Force a full re-index.
                        }
                        else if (this.OutdatedGroupIdList.Contains(id))
                        {
                            var availableMessageIds = messages.Select(m => long.Parse(m.Id)).ToList();
                            var messageContainer = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);

                            long.TryParse(groupState.LastIndexedId, out var lastIndexId);
                            if (availableMessageIds.Contains(lastIndexId))
                            {
                                // All new messages have already been loaded and are ready to index.
                                var newMessages = new List<Message>();
                                var newLastIndexId = lastIndexId;
                                foreach (var msg in messages)
                                {
                                    if (long.TryParse(msg.Id, out var messageId) && messageId > lastIndexId)
                                    {
                                        newMessages.Add(msg);

                                        if (messageId > newLastIndexId)
                                        {
                                            newLastIndexId = messageId;
                                        }
                                    }
                                }

                                context.AddMessages(newMessages);
                                groupState.LastIndexedId = newLastIndexId.ToString();
                                context.SaveChanges();
                                fullyUpdatedGroupIds.Add(id);
                            }
                        }
                    }

                    Debug.WriteLine("In place deltas applied, resolved " + fullyUpdatedGroupIds.Count);

                    // Preplaced 2, go through all originally outdated chats and run the complete re-index task on them
                    // if they couldn't be automatically updated with available messages.
                    foreach (var id in this.OutdatedGroupIdList)
                    {
                        if (!fullyUpdatedGroupIds.Contains(id))
                        {
                            var container = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
                            var cts = new CancellationTokenSource();

                            Debug.WriteLine("Full index scan required for " + container.Name);

                            // Don't start multiple overlapping indexing tasks.
                            var existingScan = this.TaskManager.RunningTasks.FirstOrDefault(t => t.Tag == id);
                            if (existingScan == null)
                            {
                                this.TaskManager.AddTask(
                                    $"Indexing {container.Name}",
                                    id,
                                    this.IndexGroup(container, cts),
                                    cts);
                            }
                        }
                    }
                }

                this.GroupUpdates.Clear();
                this.WaitingOnGroupAndChatListings.Reset();
            });
        }

19 View Source File : RequestItemUseHandler.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static void HandlePetExtraction(GameSession session, PacketReader packet, Item item)
    {
        long petUid = long.Parse(packet.ReadUnicodeString());
        if (!session.Player.Inventory.Items.ContainsKey(petUid))
        {
            return;
        }

        Item pet = session.Player.Inventory.Items[petUid];

        Item badge = new(70100000)
        {
            PetSkinBadgeId = pet.Id,
            CreationTime = TimeInfo.Now() + Environment.TickCount
        };

        session.Player.Inventory.ConsumeItem(session, item.Uid, 1);
        session.Player.Inventory.AddItem(session, badge, true);
        session.Send(PetSkinPacket.Extract(petUid, badge));
    }

19 View Source File : TransferScreen.cs
License : MIT License
Project Creator : allartprotocol

bool CheckInput() {
            if (string.IsNullOrEmpty(ammount_txt.text))
            {
                error_txt.text = "Please input transfer ammount";
                return false;
            }

            if (string.IsNullOrEmpty(toPublic_txt.text))
            {
                error_txt.text = "Please enter receiver public key";
                return false;
            }

            if (transferTokenAccount == null)
            {
                if (long.Parse(ammount_txt.text) > (long)(ownedSolAmmount * 1000000000))
                {
                    error_txt.text = "Not enough funds for transaction.";
                    return false;
                }
            }
            else {
                if (long.Parse(ammount_txt.text) > long.Parse(ownedAmmount_txt.text))
                {
                    error_txt.text = "Not enough funds for transaction.";
                    return false;
                }
            }
            error_txt.text = "";
            return true;
        }

19 View Source File : IntComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX

public byte[] GetValueData()
        {
            switch (_dataType)
            {
                case DataTypeEnum.RegUwpByte:
                    return FromByte(byte.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt16:
                    return FromInt16(short.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint16:
                    return FromUInt16(ushort.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt32:
                    return FromInt32(int.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint32:
                    return FromUInt32(uint.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt64:
                    return FromInt64(long.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint64:
                    return FromUInt64(ulong.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpSingle:
                    return FromSingle(float.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpDouble:
                    return FromDouble(double.Parse(txBox.Text), _timestamp);
                default:
                    return null;
            }
        }

19 View Source File : MenuController.cs
License : MIT License
Project Creator : AlphaYu

[HttpGet("routers")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<ActionResult<List<MenuRouterDto>>> GetMenusForRouterAsync()
        {
            var userValidateInfo = await _accountService.GetUserValidateInfoAsync(_userContext.Id);
            var roleIds = userValidateInfo.RoleIds.Split(",", System.StringSplitOptions.RemoveEmptyEntries).ToList();
            return await _menuService.GetMenusForRouterAsync(roleIds.Select(x => long.Parse(x)));
        }

19 View Source File : MissionParameterParser.cs
License : MIT License
Project Creator : ahydrax

public static (object value, ErrorType error, bool ok) ParseParameter(Type parameterType, string parameterValue)
        {
            switch (parameterType)
            {
                case var t when t == typeof(string):
                    return (parameterValue, ErrorType.No, true);

                case var t when t == typeof(bool):
                    return TryParse(JsonConvert.DeserializeObject<bool>, parameterValue);

                case var t when t == typeof(byte):
                    return TryParse(x => byte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(sbyte):
                    return TryParse(x => sbyte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(char):
                    return TryParse(x => x[0], parameterValue);

                case var t when t == typeof(decimal):
                    return TryParse(x => decimal.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(double):
                    return TryParse(x => double.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(float):
                    return TryParse(x => float.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(int):
                    return TryParse(x => int.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(uint):
                    return TryParse(x => uint.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(long):
                    return TryParse(x => long.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(ulong):
                    return TryParse(x => ulong.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(short):
                    return TryParse(x => short.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(ushort):
                    return TryParse(x => ushort.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(DateTime):
                    return TryParse(
                        x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None)
                            .UtcDateTime,
                        parameterValue);

                case var t when t == typeof(DateTimeOffset):
                    return TryParse(
                        x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None),
                        parameterValue);

                case var t when t == typeof(Guid):
                    return TryParse(Guid.Parse, parameterValue);
                
                case var t when t.IsEnum:
                    return TryParse(x => Enum.Parse(parameterType, x), parameterValue);

                case var pctx when pctx == typeof(PerformContext):
                case var jct when jct == typeof(IJobCancellationToken):
                case var ct when ct == typeof(CancellationToken):
                    return (null, ErrorType.No, true);

                case var t when t.CanBeInstantiated():
                    return TryParse(x => JsonConvert.DeserializeObject(parameterValue, t), parameterValue);

                default:
                    return (null, ErrorType.Unsupported, false);
            }
        }

19 View Source File : AppUserService.cs
License : MIT License
Project Creator : alexyakunin

[CommandHandler(IsFilter = true, Priority = 1)]
        protected virtual async Task OnEditUser(EditUserCommand command, CancellationToken cancellationToken)
        {
            var (session, name) = command;
            var context = CommandContext.GetCurrent();
            if (Computed.IsInvalidating()) {
                await context.InvokeRemainingHandlers(cancellationToken);
                if (name != null)
                    TryGetByName(name, default).Ignore();
                return;
            }
            if (name != null) {
                var error = UserNameService.ValidateName(name);
                if (error != null)
                    throw error;

                var user = await AuthService.GetUser(session, cancellationToken);
                user = user.MustBeAuthenticated();
                var userId = long.Parse(user.Id);

                await using var dbContext = CreateDbContext();
                if (dbContext.Users.Any(u => u.Name == name && u.Id != userId))
                    throw new InvalidOperationException("This name is already used by someone else.");
            }
            await context.InvokeRemainingHandlers(cancellationToken);
        }

19 View Source File : GroupContentsControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task UpdateDisplay(ICollection<Message> messages)
        {
            if (messages.Count == 0)
            {
                return;
            }

            var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
            await uiDispatcher.InvokeAsync(() =>
            {
                var maxTimeDifference = TimeSpan.FromMinutes(15);

                this.AllMessages.Edit(async innerList =>
                {
                    using (var persistContext = this.PersistManager.OpenNewContext())
                    {
                        // Messages retrieved with the before_id parameter are returned in descending order
                        // Reverse iterate through the messages collection to go newest->oldest
                        for (int i = messages.Count - 1; i >= 0; i--)
                        {
                            var msg = messages.ElementAt(i);

                            var oldMsg = innerList.FirstOrDefault(m => m.Id == msg.Id);
                            var messageHidden = persistContext.HiddenMessages.Find(msg.Id);
                            var messageStarred = persistContext.StarredMessages.Find(msg.Id);

                            if (oldMsg == null)
                            {
                                // Skip hidden messages
                                if (messageHidden == null)
                                {
                                    // add new message
                                    var msgVm = new MessageControlViewModel(
                                        msg,
                                        showPreviewsOnlyForMultiImages: this.Settings.UISettings.ShowPreviewsForMultiImages,
                                        isHidden: messageHidden != null,
                                        isStarred: messageStarred != null);
                                    innerList.Add(msgVm);

                                    // add an inline timestamp if needed
                                    if (msg.CreatedAtTime.Subtract(this.LastMarkerTime) > maxTimeDifference)
                                    {
                                        var messageId = long.Parse(msg.Id);
                                        var timeStampId = (messageId - 1).ToString();

                                        innerList.Add(new InlineTimestampControlViewModel(msg.CreatedAtTime, timeStampId, msgVm.DidISendIt));
                                        this.LastMarkerTime = msg.CreatedAtTime;
                                    }
                                }
                            }
                            else
                            {
                                // update an existing one if needed
                                oldMsg.Message = msg;
                            }
                        }
                    }

                    // process read receipt and sent receipts
                    if (this.MessageContainer.ReadReceipt != null)
                    {
                        // Remove old markers
                        var toRemove = innerList.OfType<InlineReadSentMarkerControlViewModel>().ToList();
                        foreach (var marker in toRemove)
                        {
                            innerList.Remove(marker);
                        }

                        // Attach a "Read Receipt" if the read message is displayed.
                        var matchedMessage = innerList.FirstOrDefault(m => m.Id == this.MessageContainer.ReadReceipt.MessageId);
                        if (matchedMessage != null)
                        {
                            var msgId = long.Parse(matchedMessage.Id);

                            var readMarker = new InlineReadSentMarkerControlViewModel(
                                this.MessageContainer.ReadReceipt.ReadAtTime,
                                true,
                                (msgId + 1).ToString(),
                                (matchedMessage as MessageControlViewModel).DidISendIt);

                            innerList.Add(readMarker);
                        }

                        // Attach a "Sent Receipt" to the last message confirmed sent by GroupMe
                        var me = this.MessageContainer.WhoAmI();
                        var lastSentMessage = innerList
                            .OfType<MessageControlViewModel>()
                            .OrderByDescending(m => m.Id)
                            .FirstOrDefault(m => m.Message.UserId == me.Id);

                        if (lastSentMessage != null && lastSentMessage != matchedMessage)
                        {
                            var msgId = long.Parse(lastSentMessage.Id);

                            var sentMarker = new InlineReadSentMarkerControlViewModel(
                                lastSentMessage.Message.CreatedAtTime,
                                false,
                                (msgId + 1).ToString(),
                                lastSentMessage.DidISendIt);

                            innerList.Add(sentMarker);
                        }

                        // Send a Read Receipt for the last message received
                        var lastReceivedMessage = innerList
                            .OfType<MessageControlViewModel>()
                            .OrderByDescending(m => m.Id)
                            .FirstOrDefault(m => m.Message.UserId != me.Id);

                        if (lastReceivedMessage != null && this.MessageContainer is Chat c)
                        {
                            await c.SendReadReceipt(lastReceivedMessage.Message);
                        }
                    }
                });

                if (messages.Count > 0)
                {
                    this.FirstDisplayedMessage = messages.Last();
                }
            });
        }

19 View Source File : MagicPathParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<MagicPathMetadata> Parse()
    {
        List<MagicPathMetadata> magicPathList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);

            XmlNodeList pathTypeList = doreplacedent.SelectNodes("/ms2/type");
            foreach (XmlNode pathType in pathTypeList)
            {
                long id = long.Parse(pathType.Attributes["id"]?.Value ?? "0");

                List<MagicPathMove> pathMoves = new();
                XmlNodeList pathMoveList = pathType.SelectNodes("move");
                foreach (XmlNode pathMove in pathMoveList)
                {
                    int rotation = int.Parse(pathMove.Attributes["rotation"]?.Value ?? "0");

                    CoordF fireOffsetPosition = ParseCoordWithoutLastChar(pathMove.Attributes["fireOffsetPosition"]?.Value ?? "0,0,");
                    CoordF direction = ParseCoordWithDuplicateDot(pathMove.Attributes["direction"]?.Value ?? "0");
                    CoordF controlValue0 = ParseCoordFromString(pathMove.Attributes["controlValue0"]?.Value ?? "0,0,0");
                    CoordF controlValue1 = ParseCoordFromString(pathMove.Attributes["controlValue1"]?.Value ?? "0,0,0");

                    bool ignoreAdjust = pathMove.Attributes["ignoreAdjustCubePosition"] != null;

                    pathMoves.Add(new(rotation, fireOffsetPosition, direction, controlValue0, controlValue1, ignoreAdjust));
                }

                MagicPathMetadata newMagicPath = new(id, pathMoves);
                magicPathList.Add(newMagicPath);
            }
        }
        return magicPathList;
    }

19 View Source File : GameService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task Join(Game.JoinCommand command, CancellationToken cancellationToken = default)
        {
            var (session, id, join) = command;
            var context = CommandContext.GetCurrent();

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);
            var dbGame = await GetDbGame(dbContext, id, cancellationToken);
            var game = dbGame.ToModel();
            var engine = GameEngines[game.EngineId];

            if (game.Stage != GameStage.New)
                throw new InvalidOperationException("Game has already been started.");
            if (join) {
                if (game.Players.Any(p => p.UserId == userId))
                    throw new InvalidOperationException("You've already joined this game.");
                if (game.Players.Count > engine.MaxPlayerCount)
                    throw new InvalidOperationException("You can't join this game: there too many players already.");
                game = game with { Players = game.Players.Add(new GamePlayer(userId)) };
            } else { // Leave
                var leftPlayer = game.Players.SingleOrDefault(p => p.UserId == userId);
                if (leftPlayer == null)
                    throw new InvalidOperationException("You've already left this game.");
                game = game with { Players = game.Players.Remove(leftPlayer) };
                context.Operation().Items.Set(leftPlayer);
            }

            dbGame.UpdateFrom(game);
            await dbContext.SaveChangesAsync(cancellationToken);
            context.Operation().Items.Set(game);

            // Try auto-start
            if (join && engine.AutoStart && game.Players.Count == engine.MaxPlayerCount) {
                await Start(new Game.StartCommand(session, id), cancellationToken);
            }
        }

19 View Source File : AppleAuthProvider.cs
License : MIT License
Project Creator : Accedia

private void SetUserInformation(AuthorizationToken tokenResponse)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var deserializeUserInformation = tokenHandler.ReadJwtToken(tokenResponse.Token);

            if (deserializeUserInformation != null && deserializeUserInformation.Claims.Any())
            {
                var claims = deserializeUserInformation.Claims;

                var email = claims.FirstOrDefault(x => x.Type == ClaimConstants.Email);
                var email_verified = claims.FirstOrDefault(x => x.Type == ClaimConstants.EmailVerified);
                var sub = claims.FirstOrDefault(x => x.Type == ClaimConstants.Sub);
                var auth_time = claims.FirstOrDefault(x => x.Type == ClaimConstants.AuthenticationTime).Value;
                var timeOfAuthentication = DateTimeOffset.FromUnixTimeSeconds(long.Parse(auth_time)).DateTime;

                tokenResponse.UserInformation = new UserInformation
                {
                    Email = email != null ? email.Value : string.Empty,
                    EmailVerified = email_verified != null ? email_verified.Value : "False",
                    UserID = sub != null ? sub.Value : string.Empty,
                    TimeOfAuthentication = timeOfAuthentication
                };
            }
        }

19 View Source File : ConsumeMessageResponseUnmarshaller.cs
License : MIT License
Project Creator : aliyunmq

public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(context.ResponseStream);
            ConsumeMessageResponse consumeMessageResponse = new ConsumeMessageResponse();
            Message message = null;

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case System.Xml.XmlNodeType.Element:
                        switch (reader.LocalName)
                        {
                            case Constants.XML_ROOT_MESSAGE:
                                message = new Message();
                                break;
                            case Constants.XML_ELEMENT_MESSAGE_ID:
                                reader.Read();
                                message.Id = reader.Value;
                                break;
                            case Constants.XML_ELEMENT_RECEIPT_HANDLE:
                                reader.Read();
                                message.ReceiptHandle = reader.Value;
                                break;
                            case Constants.XML_ELEMENT_MESSAGE_BODY_MD5:
                                reader.Read();
                                message.BodyMD5 = reader.Value;
                                break;
                            case Constants.XML_ELEMENT_MESSAGE_BODY:
                                reader.Read();
                                message.Body = reader.Value;
                                break;
                            case Constants.XML_ELEMENT_PUBLISH_TIME:
                                reader.Read();
                                message.PublishTime = long.Parse(reader.Value);
                                break;
                            case Constants.XML_ELEMENT_NEXT_CONSUME_TIME:
                                reader.Read();
                                message.NextConsumeTime = long.Parse(reader.Value);
                                break;
                            case Constants.XML_ELEMENT_FIRST_CONSUME_TIME:
                                reader.Read();
                                message.FirstConsumeTime = long.Parse(reader.Value);
                                break;
                            case Constants.XML_ELEMENT_CONSUMED_TIMES:
                                reader.Read();
                                message.ConsumedTimes = uint.Parse(reader.Value);
                                break;
                            case Constants.XML_ELEMENT_MESSAGE_TAG:
                                reader.Read();
                                message.MessageTag = reader.Value;
                                break;
                            case Constants.XML_ELEMENT_MESSAGE_PROPERTIES:
                                reader.Read();
                                AliyunSDKUtils.StringToDict(reader.Value, message.Properties);
                                break;
                        }
                        break;
                    case System.Xml.XmlNodeType.EndElement:
                        if (reader.LocalName == Constants.XML_ROOT_MESSAGE)
                        {
                            consumeMessageResponse.Messages.Add(message);
                        }
                        break;
                }
            }
            reader.Close();
            return consumeMessageResponse;
        }

19 View Source File : ExpTableParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<ExpMetadata> Parse()
    {
        List<ExpMetadata> expList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/nextexp"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList nodes = doreplacedent.SelectNodes("/ms2/exp");

            foreach (XmlNode node in nodes)
            {
                byte level = byte.Parse(node.Attributes["level"].Value);
                if (level == 0)
                {
                    continue;
                }

                ExpMetadata expTable = new();
                expTable.Level = level;
                expTable.Experience = long.Parse(node.Attributes["value"].Value);
                expList.Add(expTable);
            }
        }

        return expList;
    }

19 View Source File : UserAppService.cs
License : MIT License
Project Creator : AlphaYu

public async Task<List<string>> GetPermissionsAsync(long userId, IEnumerable<string> permissions, string validationVersion = null)
        {
            var userValidateInfo = await _cacheService.GetUserValidateInfoFromCacheAsync(userId);
            if (userValidateInfo.RoleIds.IsNullOrWhiteSpace())
                return default;

            if (userValidateInfo.Status != 1)
                return default;

            if (validationVersion.IsNotNullOrWhiteSpace() && userValidateInfo.ValidationVersion != validationVersion)
                return default;

            var roleIds = userValidateInfo.RoleIds.Trim().Split(",", StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x));

            var allMenuCodes = await _cacheService.GetAllMenuCodesFromCacheAsync();

            var codes = allMenuCodes?.Where(x => roleIds.Contains(x.RoleId)).Select(x => x.Code.ToUpper());
            if (codes.IsNotNullOrEmpty())
            {
                var result = codes.Intersect(permissions.Select(x => x.ToUpper()));
                return result.ToList();
            }

            return default;
        }

19 View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc

private static object ParseDefaultValue(Type type, object value)
        {
			if(true)
            {
                Type tmp = Helpers.GetUnderlyingType(type);
                if (tmp != null) type = tmp;
            }
            switch (Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.Boolean:
                case ProtoTypeCode.Byte:
                case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                case ProtoTypeCode.DateTime:
                case ProtoTypeCode.Decimal:
                case ProtoTypeCode.Double:
                case ProtoTypeCode.Int16:
                case ProtoTypeCode.Int32:
                case ProtoTypeCode.Int64:
                case ProtoTypeCode.SByte:
                case ProtoTypeCode.Single:
                case ProtoTypeCode.String:
                case ProtoTypeCode.UInt16:
                case ProtoTypeCode.UInt32:
                case ProtoTypeCode.UInt64:
                case ProtoTypeCode.TimeSpan:
                case ProtoTypeCode.Uri:
                case ProtoTypeCode.Guid:
                    {
                        value = value + "";
                    }
                    break;
            }
            if (value is string)
            {
                string s = (string)value;
                if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);

                switch (Helpers.GetTypeCode(type))
                {
                    case ProtoTypeCode.Boolean: return bool.Parse(s);
                    case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                        if (s.Length == 1) return s[0];
                        throw new FormatException("Single character expected: \"" + s + "\"");
                    case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.String: return s;
                    case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
                    case ProtoTypeCode.Uri: return s; // Uri is decorated as string
                    case ProtoTypeCode.Guid: return new Guid(s);
                }
            }
#if FEAT_IKVM
            if (Helpers.IsEnum(type)) return value; // return the underlying type instead
            System.Type convertType = null;
            switch(Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
                case ProtoTypeCode.Int16: convertType = typeof(short); break;
                case ProtoTypeCode.Int32: convertType = typeof(int); break;
                case ProtoTypeCode.Int64: convertType = typeof(long); break;
                case ProtoTypeCode.Byte: convertType = typeof(byte); break;
                case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
                case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
                case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
                case ProtoTypeCode.Single: convertType = typeof(float); break;
                case ProtoTypeCode.Double: convertType = typeof(double); break;
                case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
            }
            if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
            throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
            if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
            return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
        }

19 View Source File : UserAppService.cs
License : MIT License
Project Creator : AlphaYu

public async Task<PageModelDto<UserDto>> GetPagedAsync(UserSearchPagedDto search)
        {
            var whereCondition = ExpressionCreator
                                                                            .New<SysUser>()
                                                                            .AndIf(search.Account.IsNotNullOrWhiteSpace(), x => x.Account.Contains(search.Account))
                                                                            .AndIf(search.Name.IsNotNullOrWhiteSpace(), x => x.Name.Contains(search.Name));

            var pagedModel = await _userRepository.PagedAsync(search.PageIndex, search.PageSize, whereCondition, x => x.Id, false);
            var pageModelDto = Mapper.Map<PageModelDto<UserDto>>(pagedModel);

            if (pageModelDto.RowsCount > 0)
            {
                var deptIds = pageModelDto.Data.Where(d => d.DeptId != null)
                                                                        .Select(d => d.DeptId)
                                                                        .Distinct();

                var depts = (await _cacheService.GetAllDeptsFromCacheAsync())
                                                                    .Where(x => deptIds.Contains(x.Id))
                                                                    .Select(d => new { d.Id, d.FullName });

                var roles = (await _cacheService.GetAllRolesFromCacheAsync())
                                                                   .Select(r => new { r.Id, r.Name });

                foreach (var user in pageModelDto.Data)
                {
                    user.DeptName = depts.FirstOrDefault(x => x.Id == user.DeptId)?.FullName;
                    var roleIds = user.RoleIds.IsNullOrWhiteSpace()
                                                                                                ? new List<long>()
                                                                                                : user.RoleIds.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x))
                                                                                                ;

                    user.RoleNames = roles.Where(x => roleIds.Contains(x.Id))
                                                          .Select(x => x.Name)
                                                          .ToString(",");
                }
            }

            pageModelDto.XData = await _cacheService.GetDeptSimpleTreeListAsync();

            return pageModelDto;
        }

19 View Source File : NpcParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<NpcMetadata> Parse()
    {
        // Parse EXP tables
        Dictionary<int, ExpMetadata> levelExp = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/expbasetable"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            foreach (XmlNode node in doreplacedent.DoreplacedentElement.ChildNodes)
            {
                if (node.Name == "table")
                {
                    if (int.Parse(node.Attributes["expTableID"].Value) != 1)
                    {
                        continue;
                    }
                    foreach (XmlNode tableNode in node.ChildNodes)
                    {
                        if (tableNode.Name == "base")
                        {
                            ExpMetadata expTable = new();

                            byte level = byte.Parse(tableNode.Attributes["level"].Value);
                            if (level != 0)
                            {
                                expTable.Level = level;
                                expTable.Experience = long.Parse(tableNode.Attributes["exp"].Value);
                                levelExp[level] = expTable;
                            }
                        }
                    }
                }
            }
        }

        Dictionary<int, string> npcIdToName = new()
        {
        };
        List<NpcMetadata> npcs = new();

        // Parse the NpcId -> Names first.
        foreach (PackFileEntry entry in Resources.XmlReader.Files.Where(entry => entry.Name.Equals("string/en/npcname.xml")))
        {
            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);

            foreach (XmlNode node in doreplacedent.SelectNodes("ms2/key"))
            {
                int id = int.Parse(node.Attributes["id"].Value);
                if (!npcIdToName.ContainsKey(id))
                {
                    npcIdToName.Add(id, node.Attributes["name"].Value);
                }
            }
        }

        // Handle /npc files second, to setup the NpcMetadata
        foreach (PackFileEntry entry in Resources.XmlReader.Files.Where(entry => entry.Name.StartsWith("npc/")))
        {
            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);

            XmlNode npcModelNode = doreplacedent.SelectSingleNode("ms2/environment/model") ?? doreplacedent.SelectSingleNode("ms2/model");
            XmlNode npcBasicNode = doreplacedent.SelectSingleNode("ms2/environment/basic") ?? doreplacedent.SelectSingleNode("ms2/basic");
            XmlNode npcStatsNode = doreplacedent.SelectSingleNode("ms2/environment/stat") ?? doreplacedent.SelectSingleNode("ms2/stat");
            XmlNode npcSpeedNode = doreplacedent.SelectSingleNode("ms2/environment/speed") ?? doreplacedent.SelectSingleNode("ms2/speed");
            XmlNode npcDistanceNode = doreplacedent.SelectSingleNode("ms2/environment/distance") ?? doreplacedent.SelectSingleNode("ms2/distance");
            XmlNode npcSkillNode = doreplacedent.SelectSingleNode("ms2/environment/skill") ?? doreplacedent.SelectSingleNode("ms2/skill");
            XmlNode npcEffectNode = doreplacedent.SelectSingleNode("ms2/environment/additionalEffect") ?? doreplacedent.SelectSingleNode("ms2/additionalEffect");
            XmlNode npcExpNode = doreplacedent.SelectSingleNode("ms2/environment/exp") ?? doreplacedent.SelectSingleNode("ms2/exp");
            XmlNode npcAiInfoNode = doreplacedent.SelectSingleNode("ms2/environment/aiInfo") ?? doreplacedent.SelectSingleNode("ms2/aiInfo");
            XmlNode npcNormalNode = doreplacedent.SelectSingleNode("ms2/environment/normal") ?? doreplacedent.SelectSingleNode("ms2/normal");
            XmlNode npcDeadNode = doreplacedent.SelectSingleNode("ms2/environment/dead") ?? doreplacedent.SelectSingleNode("ms2/dead");
            XmlNode npcDropItemNode = doreplacedent.SelectSingleNode("ms2/environment/dropiteminfo") ?? doreplacedent.SelectSingleNode("ms2/dropiteminfo");
            XmlAttributeCollection statsCollection = npcStatsNode.Attributes;

            // Metadata
            NpcMetadata metadata = new();
            metadata.Id = int.Parse(Path.GetFileNameWithoutExtension(entry.Name));
            metadata.Name = npcIdToName.ContainsKey(metadata.Id) ? npcIdToName[metadata.Id] : "";
            metadata.Model = npcModelNode.Attributes["kfm"].Value;

            // Parse basic attribs.
            metadata.TemplateId = int.TryParse(npcBasicNode.Attributes["illust"]?.Value, out _) ? int.Parse(npcBasicNode.Attributes["illust"].Value) : 0;
            metadata.Friendly = byte.Parse(npcBasicNode.Attributes["friendly"].Value);
            metadata.Level = byte.Parse(npcBasicNode.Attributes["level"].Value);

            metadata.NpcMetadataBasic.NpcAttackGroup = sbyte.Parse(npcBasicNode.Attributes["npcAttackGroup"]?.Value ?? "0");
            metadata.NpcMetadataBasic.NpcDefenseGroup = sbyte.Parse(npcBasicNode.Attributes["npcDefenseGroup"]?.Value ?? "0");
            metadata.NpcMetadataBasic.Difficulty = ushort.Parse(npcBasicNode.Attributes["difficulty"]?.Value ?? "0");
            metadata.NpcMetadataBasic.MaxSpawnCount = byte.Parse(npcBasicNode.Attributes["maxSpawnCount"]?.Value ?? "0");

            metadata.NpcMetadataBasic.GroupSpawnCount = byte.Parse(npcBasicNode.Attributes["groupSpawnCount"]?.Value ?? "0");
            metadata.NpcMetadataBasic.MainTags = npcBasicNode.Attributes["mainTags"]?.Value.Split(",").Select(p => p.Trim()).ToArray() ?? Array.Empty<string>();
            metadata.NpcMetadataBasic.SubTags = npcBasicNode.Attributes["subTags"]?.Value.Split(",").Select(p => p.Trim()).ToArray() ?? Array.Empty<string>();
            metadata.NpcMetadataBasic.Clreplaced = byte.Parse(npcBasicNode.Attributes["clreplaced"].Value);
            metadata.NpcMetadataBasic.Kind = ushort.Parse(npcBasicNode.Attributes["kind"].Value);
            metadata.NpcMetadataBasic.HpBar = byte.Parse(npcBasicNode.Attributes["hpBar"].Value);

            metadata.Stats = GetNpcStats(statsCollection);

            // Parse speed
            metadata.NpcMetadataSpeed.RotationSpeed = float.Parse(npcSpeedNode.Attributes["rotation"]?.Value ?? "0");
            metadata.NpcMetadataSpeed.WalkSpeed = float.Parse(npcSpeedNode.Attributes["walk"]?.Value ?? "0");
            metadata.NpcMetadataSpeed.RunSpeed = float.Parse(npcSpeedNode.Attributes["run"]?.Value ?? "0");

            // Parse distance
            metadata.NpcMetadataDistance.Avoid = int.Parse(npcDistanceNode.Attributes["avoid"]?.Value ?? "0");
            metadata.NpcMetadataDistance.Sight = int.Parse(npcDistanceNode.Attributes["sight"]?.Value ?? "0");
            metadata.NpcMetadataDistance.SightHeightUp = int.Parse(npcDistanceNode.Attributes["sightHeightUP"]?.Value ?? "0");
            metadata.NpcMetadataDistance.SightHeightDown = int.Parse(npcDistanceNode.Attributes["sightHeightDown"]?.Value ?? "0");

            // Parse skill
            metadata.NpcMetadataSkill.SkillIds = npcSkillNode.Attributes["ids"].Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToArray();
            if (metadata.NpcMetadataSkill.SkillIds.Length > 0)
            {
                metadata.NpcMetadataSkill.SkillLevels = npcSkillNode.Attributes["levels"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(byte.Parse).ToArray();
                metadata.NpcMetadataSkill.SkillPriorities = npcSkillNode.Attributes["priorities"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(byte.Parse).ToArray();
                metadata.NpcMetadataSkill.SkillProbs = npcSkillNode.Attributes["probs"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(short.Parse).ToArray();
                metadata.NpcMetadataSkill.SkillCooldown = short.Parse(npcSkillNode.Attributes["coolDown"].Value);
            }

            // Parse Additional Effects (Effect / Buff)
            metadata.NpcMetadataEffect.EffectIds = npcEffectNode.Attributes["codes"].Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToArray();
            if (metadata.NpcMetadataEffect.EffectIds.Length > 0)
            {
                metadata.NpcMetadataEffect.EffectLevels = npcEffectNode.Attributes["levels"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(byte.Parse).ToArray();
            }

            // Parse normal state
            List<(string, NpcAction, short)> normalActions = new();
            string[] normalActionIds = npcNormalNode.Attributes["action"]?.Value.Split(",") ?? Array.Empty<string>();
            if (normalActionIds.Length > 0)
            {
                short[] actionProbs = npcNormalNode.Attributes["prob"]?.Value.Split(",").Select(short.Parse).ToArray();
                for (int i = 0; i < normalActionIds.Length; i++)
                {
                    normalActions.Add((normalActionIds[i], GetNpcAction(normalActionIds[i]), actionProbs[i]));
                }
                metadata.StateActions[NpcState.Normal] = normalActions.ToArray();
            }
            metadata.MoveRange = short.Parse(npcNormalNode.Attributes["movearea"]?.Value ?? "0");

            // HACK: Parse combat/skills state (does not actually exist)
            List<(string, NpcAction, short)> combatActions = new();
            string[] combatActionsIds = new string[] { "Run_A" };
            if (combatActionsIds.Length > 0)
            {
                int equalProb = 10000 / combatActionsIds.Length;
                int remainder = 10000 % (equalProb * combatActionsIds.Length);
                combatActions.Add((combatActionsIds[0], GetNpcAction(combatActionsIds[0]), (short) (equalProb + remainder)));
                metadata.StateActions[NpcState.Combat] = combatActions.ToArray();
            }

            // Parse dead state
            List<(string, NpcAction, short)> deadActions = new();
            string[] deadActionIds = npcDeadNode.Attributes["defaultaction"]?.Value.Split(",") ?? Array.Empty<string>();
            if (deadActionIds.Length > 0)
            {
                int equalProb = 10000 / deadActionIds.Length;
                int remainder = 10000 % (equalProb * deadActionIds.Length);
                deadActions.Add((deadActionIds[0], GetNpcAction(deadActionIds[0]), (short) (equalProb + remainder)));
                for (int i = 1; i < deadActionIds.Length; i++)
                {
                    deadActions.Add((deadActionIds[i], GetNpcAction(deadActionIds[i]), (short) equalProb));
                }
                metadata.StateActions[NpcState.Dead] = deadActions.ToArray();
            }

            metadata.AiInfo = npcAiInfoNode.Attributes["path"].Value;
            int customExpValue = int.Parse(npcExpNode.Attributes["customExp"].Value);
            metadata.Experience = customExpValue >= 0 ? customExpValue : (int) levelExp[metadata.Level].Experience;
            metadata.NpcMetadataDead.Time = float.Parse(npcDeadNode.Attributes["time"].Value);
            metadata.NpcMetadataDead.Actions = npcDeadNode.Attributes["defaultaction"].Value.Split(",");
            metadata.GlobalDropBoxIds = npcDropItemNode.Attributes["globalDropBoxId"].Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToArray();
            metadata.Kind = short.Parse(npcBasicNode.Attributes["kind"].Value);
            metadata.ShopId = int.Parse(npcBasicNode.Attributes["shopId"].Value);
            npcs.Add(metadata);
        }

        return npcs;
    }

19 View Source File : MultiLikeControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.SmallDialogManager.OpenPopup(loadingControl, Guid.Empty);

            foreach (var message in this.GroupContentsControlViewModel.MessagesSorted)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.SmallDialogManager.ClosePopup();
        }

19 View Source File : WebSocketPlayController.cs
License : MIT License
Project Creator : a1q123456

public override async Task OnConnect()
        {
            var publisher = _publisherSessionService.FindPublisher(StreamName);
            if (publisher != null)
            {
                _cleanupActions.Add(() =>
                {
                    publisher.OnAudioMessage -= SendAudio;
                    publisher.OnVideoMessage -= SendVideo;
                });

                var metadata = (Dictionary<string, object>)publisher.FlvMetadata.Data.Last();
                var hasAudio = metadata.ContainsKey("audiocodecid");
                var hasVideo = metadata.ContainsKey("videocodecid");

                await Session.SendFlvHeaderAsync(hasAudio, hasVideo);

                await Session.SendMessageAsync(publisher.FlvMetadata);
                if (hasAudio)
                {
                    await Session.SendMessageAsync(publisher.AACConfigureRecord);
                }
                if (hasVideo)
                {
                    await Session.SendMessageAsync(publisher.AVCConfigureRecord);
                }

                publisher.OnAudioMessage += SendAudio;
                publisher.OnVideoMessage += SendVideo;
            }
            // play record
            else
            {
                _recordFile = new FileStream(_recordService.GetRecordFilename(StreamName) + ".flv", FileMode.Open, FileAccess.Read);
                var fromStr = Query.Get("from");
                long from = 0;
                if (fromStr != null)
                {
                    from = long.Parse(fromStr);
                }
                var toStr = Query.Get("to");
                _playRangeTo = -1;
                if (toStr != null)
                {
                    _playRangeTo = long.Parse(toStr);
                }

                var header = new byte[9];

                await _recordFile.ReadBytesAsync(header);
                await Session.SendRawDataAsync(header);

                from = Math.Max(from, 9);

                _recordFile.Seek(from, SeekOrigin.Begin);

                await PlayRecordFile();
            }
        }

19 View Source File : MultiLikeControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.PopupManager.PopupDialog = loadingControl;

            foreach (var message in this.GroupContentsControlViewModel.SortedMessages)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.PopupManager.PopupDialog = null;
        }

19 View Source File : TechLogFileReader.cs
License : MIT License
Project Creator : akpaevj

private TechLogItem ParseRawItem(ReadOnlySpan<char> rawItem, CancellationToken cancellationToken = default)
        {
            var properties = new Dictionary<string, string>();
            
            var item = new TechLogItem
            {
                FolderName = FolderName,
                FileName = FileName,
                EndPosition = _lastEventEndPosition
            };

            // set event end position no new line
            _lastEventEndPosition = Position;

            var dtd = ReadNextPropertyWithoutName(rawItem);
            var dtEndIndex = dtd.LastIndexOf('-');
            item.DateTime = DateTime.Parse(dtd[..dtEndIndex]);
            item.EndTicks = item.DateTime.Ticks;
            var position = dtEndIndex + 1;

            var duration = ReadNextPropertyWithoutName(rawItem[position..]);
            position += duration.Length + 1;
            item.Duration = long.Parse(duration);
            item.StartTicks = item.EndTicks - item.Duration * (TimeSpan.TicksPerMillisecond / 1000);

            var eventName = ReadNextPropertyWithoutName(rawItem[position..]);
            position += eventName.Length + 1;
            item.EventName = eventName.ToString();

            var level = ReadNextPropertyWithoutName(rawItem[position..]);
            position += level.Length + 1;
            item.Level = int.Parse(level);

            while (!cancellationToken.IsCancellationRequested)
            {
                var propertyName = ReadPropertyName(rawItem[position..]);
                position += propertyName.Length + 1;
                propertyName = propertyName.Trim();

                if (position >= rawItem.Length)
                    break;

                if (propertyName == "")
                    continue;

                var propertyValue = ReadPropertyValue(rawItem[position..]);
                position += propertyValue.Length + 1;
                propertyValue = propertyValue.Trim(new[] { '\'', '"' }).Trim();

                if (!item.AllProperties.TryAdd(propertyName.ToString(), propertyValue.ToString()))
                    item.AllProperties.TryAdd(GetPropertyName(properties, propertyName), propertyValue.ToString());

                if (position >= rawItem.Length)
                    break;
            }

            return item;
        }

19 View Source File : AppUserService.cs
License : MIT License
Project Creator : alexyakunin

[CommandHandler(IsFilter = true, Priority = 1)]
        protected virtual async Task OnSignIn(SignInCommand command, CancellationToken cancellationToken)
        {
            var context = CommandContext.GetCurrent();
            await context.InvokeRemainingHandlers(cancellationToken);
            if (Computed.IsInvalidating()) {
                var invSessionInfo = context.Operation().Items.TryGet<SessionInfo>();
                if (invSessionInfo != null && long.TryParse(invSessionInfo.UserId, out var invUserId))
                    IsOnline(invUserId, default).Ignore();
                return;
            }

            // The code below renames the user if it happens that its name isn't unique.
            // And if you check out how CreateCommandDbContext works,
            // you'll find out this code actually shared the same transaction & connection
            // as the original sign-in command handler!
            await using var dbContext = await CreateCommandDbContext(cancellationToken).ConfigureAwait(false);
            var sessionInfo = context.Operation().Items.Get<SessionInfo>();
            var userId = long.Parse(sessionInfo.UserId);
            var dbUser = await DbUsers.TryGet(dbContext, userId, cancellationToken);
            var newName = await NormalizeName(dbContext, dbUser!.Name, userId, cancellationToken);
            if (newName != dbUser.Name) {
                dbUser.Name = newName;
                await dbContext.SaveChangesAsync(cancellationToken);
            }
        }

19 View Source File : PaginatedMessagesControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task<IEnumerable<Message>> GetFromGroupMeAsync(Message startAt, Message endAt)
        {
            var result = new List<Message>(this.MessagesPerPage);
            long.TryParse(startAt.Id, out var startId);
            long.TryParse(endAt.Id, out var endId);

            // GroupMe only allows before_id searches on Chat's (not after_id), so we have to go backwards...
            // Add 1 to include the endAt message in the returned data.
            long currentId = endId + 1;
            while (currentId > startId)
            {
                var msgs = await this.replacedociateWith.GetMessagesAsync(GroupMeClientApi.MessageRetreiveMode.BeforeId, currentId.ToString());
                result.AddRange(msgs);

                currentId = long.Parse(msgs.Last().Id);
            }

            // Since we went backwards, reverse the list.
            result.Reverse();

            // GroupMe block sizes might not align with the pagination page-sizes.
            // Cut to match the expected page size.
            int startIndex = result.FindIndex(m => m.Id == startAt.Id);
            return result.Skip(startIndex);
        }

19 View Source File : TrophyParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<TrophyMetadata> Parse()
    {
        List<TrophyMetadata> trophyList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("achieve/"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNode trophy = doreplacedent.SelectSingleNode("/ms2/achieves");

            TrophyMetadata newTrophy = new();
            newTrophy.Id = int.Parse(trophy.Attributes["id"].Value);
            newTrophy.Categories = trophy.Attributes["categoryTag"]?.Value.Split(",");
            newTrophy.AccountWide = trophy.Attributes["account"].Value == "1";

            XmlNodeList grades = trophy.SelectNodes("grade");

            foreach (XmlNode grade in grades)
            {
                TrophyGradeMetadata newGrade = new();
                newGrade.Grade = int.Parse(grade.Attributes["value"].Value);

                XmlNode condition = grade.SelectSingleNode("condition");
                newGrade.Condition = long.Parse(condition.Attributes["value"].Value);
                newGrade.ConditionType = condition.Attributes["type"].Value;
                newGrade.ConditionCodes = condition.Attributes["code"].Value.Split(",");
                newGrade.ConditionTargets = condition.Attributes["target"].Value.Split(",");

                XmlNode reward = grade.SelectSingleNode("reward");
                Enum.TryParse(reward.Attributes["type"].Value, true, out RewardType type);
                newGrade.RewardType = type;
                newGrade.RewardCode = int.Parse(reward.Attributes["code"].Value);
                newGrade.RewardValue = int.Parse(reward.Attributes["value"].Value);

                newTrophy.Grades.Add(newGrade);
            }
            trophyList.Add(newTrophy);
        }

        return trophyList;
    }

19 View Source File : ChatService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<ChatMessage> Post(
            Chat.PostCommand command, CancellationToken cancellationToken = default)
        {
            var (session, chatId, text) = command;
            var context = CommandContext.GetCurrent();
            if (Computed.IsInvalidating()) {
                var invChatMessage = context.Operation().Items.Get<ChatMessage>();
                PseudoGetTail(chatId, default).Ignore();
                return null!;
            }

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);
            var cp = await GetPermissions(session, chatId, cancellationToken);
            if ((cp & ChatPermission.Write) != ChatPermission.Write)
                throw new SecurityException("You can't post to this chat.");
            var parsedMessage = await MessageParser.Parse(text, cancellationToken);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);
            var now = Clock.Now;
            var chatMessage = new ChatMessage(Ulid.NewUlid().ToString(), chatId) {
                UserId = userId,
                CreatedAt = now,
                EditedAt = now,
                Text = parsedMessage.Format(),
            };
            var dbChatMessage = new DbChatMessage();
            dbChatMessage.UpdateFrom(chatMessage);
            dbContext.Add(dbChatMessage);
            await dbContext.SaveChangesAsync(cancellationToken);

            context.Operation().Items.Set(chatMessage);
            return chatMessage;
        }

19 View Source File : TokenGenerator.cs
License : MIT License
Project Creator : Accedia

public static void VerifyAppleIDToken(string token, string clientId)
        {
            var deserializedToken = _tokenHandler.ReadJwtToken(token);
            var claims = deserializedToken.Claims;

            SecurityKey publicKey;

            var expClaim = claims.FirstOrDefault(x => x.Type == ClaimConstants.Expiration).Value;
            var expirationTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expClaim)).DateTime;

            if (expirationTime < DateTime.UtcNow)
            {
                throw new SecurityTokenExpiredException("Expired token");
            }

            var applePublicKeys = _httpClient.GetAsync("https://appleid.apple.com/auth/keys");
            var keyset = new JsonWebKeySet(applePublicKeys.Result.Content.ReadreplacedtringAsync().Result);

            publicKey = keyset.Keys.FirstOrDefault(x => x.Kid == deserializedToken.Header.Kid);

            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer = "https://appleid.apple.com",
                IssuerSigningKey = publicKey,
                ValidAudience = clientId
            };

            _tokenHandler.ValidateToken(token, validationParameters, out var _);
        }

19 View Source File : GameService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<Game> Create(Game.CreateCommand command, CancellationToken cancellationToken = default)
        {
            var (session, engineId) = command;
            var engine = GameEngines[engineId]; // Just to check it exists
            var context = CommandContext.GetCurrent();

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);

            var game = new Game() {
                Id = Ulid.NewUlid().ToString(),
                EngineId = engineId,
                UserId = userId,
                Intro = "",
                CreatedAt = Clock.Now,
                Stage = GameStage.New,
                Players = ImmutableList<GamePlayer>.Empty.Add(new GamePlayer(userId))
            };
            game = engine.Create(game);
            var dbGame = new DbGame();
            dbGame.UpdateFrom(game);
            dbContext.Add(dbGame);
            await dbContext.SaveChangesAsync(cancellationToken);
            context.Operation().Items.Set(game);
            return game;
        }

19 View Source File : SkillParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<SkillMetadata> Parse()
    {
        List<SkillMetadata> skillList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            // Parsing Skills
            if (entry.Name.StartsWith("skill"))
            {
                XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
                XmlNode ui = doreplacedent.SelectSingleNode("/ms2/basic/ui");
                XmlNode kinds = doreplacedent.SelectSingleNode("/ms2/basic/kinds");
                XmlNode stateAttr = doreplacedent.SelectSingleNode("/ms2/basic/stateAttr");
                XmlNodeList levels = doreplacedent.SelectNodes("/ms2/level");

                int skillId = int.Parse(Path.GetFileNameWithoutExtension(entry.Name));
                string skillState = kinds.Attributes["state"]?.Value ?? "";
                byte skillAttackType = byte.Parse(ui.Attributes["attackType"]?.Value ?? "0");
                byte skillType = byte.Parse(kinds.Attributes["type"].Value);
                byte skillSubType = byte.Parse(kinds.Attributes["subType"]?.Value ?? "0");
                byte skillElement = byte.Parse(kinds.Attributes["element"].Value);
                byte skillSuperArmor = byte.Parse(stateAttr.Attributes["superArmor"].Value);
                bool skillRecovery = int.Parse(kinds.Attributes["spRecoverySkill"]?.Value ?? "0") == 1;

                List<SkillLevel> skillLevels = new();
                foreach (XmlNode level in levels)
                {
                    // Getting all skills level
                    string feature = level.Attributes["feature"]?.Value ?? "";
                    int levelValue = int.Parse(level.Attributes["value"].Value ?? "0");
                    // We prevent duplicates levels from older balances.
                    if (skillLevels.Exists(level => level.Level == levelValue))
                    {
                        continue;
                    }
                    int spirit = int.Parse(level.SelectSingleNode("consume/stat").Attributes["sp"]?.Value ?? "0");
                    int stamina = int.Parse(level.SelectSingleNode("consume/stat").Attributes["ep"]?.Value ?? "0");
                    float damageRate = float.Parse(level.SelectSingleNode("motion/attack/damageProperty")?.Attributes["rate"].Value ?? "0");
                    string sequenceName = level.SelectSingleNode("motion/motionProperty")?.Attributes["sequenceName"].Value ?? "";
                    string motionEffect = level.SelectSingleNode("motion/motionProperty")?.Attributes["motionEffect"].Value ?? "";

                    SkillUpgrade skillUpgrade = new();
                    if (level.SelectSingleNode("motion/upgrade")?.Attributes != null)
                    {
                        int upgradeLevel = int.Parse(level.SelectSingleNode("motion/upgrade").Attributes["level"].Value ?? "0");
                        int[] upgradeSkills = level.SelectSingleNode("motion/upgrade").Attributes["skillIDs"].Value.Split(",").Select(int.Parse).ToArray();
                        short[] upgradeSkillsLevel = level.SelectSingleNode("motion/upgrade").Attributes["skillLevels"].Value.Split(",").Select(short.Parse).ToArray();

                        skillUpgrade = new(upgradeLevel, upgradeSkills, upgradeSkillsLevel);
                    }

                    // Getting all Attack attr in each level.
                    List<SkillAttack> skillAttacks = new();
                    List<SkillCondition> skillConditions = new();

                    XmlNodeList conditionSkills = level.SelectNodes("motion/attack/conditionSkill") ?? level.SelectNodes("conditionSkill");
                    foreach (XmlNode conditionSkill in conditionSkills)
                    {
                        int conditionSkillId = int.Parse(conditionSkill.Attributes["skillID"]?.Value ?? "0");
                        short conditionSkillLevel = short.Parse(conditionSkill.Attributes["level"]?.Value ?? "0");
                        bool splash = conditionSkill.Attributes["splash"]?.Value == "1";
                        byte target = byte.Parse(conditionSkill.Attributes["skillTarget"].Value ?? "0");
                        byte owner = byte.Parse(conditionSkill.Attributes["skillOwner"]?.Value ?? "0");
                        SkillCondition skillCondition = new(conditionSkillId, conditionSkillLevel, splash, target, owner);

                        skillConditions.Add(skillCondition);
                    }

                    XmlNodeList attackListAttr = level.SelectNodes("motion/attack");
                    foreach (XmlNode attackAttr in attackListAttr)
                    {
                        // Many skills has a condition to proc another skill.
                        // We capture that as a list, since each Attack attr has one at least.
                        byte attackPoint = byte.Parse(Regex.Match(attackAttr.Attributes["point"]?.Value, @"\d").Value);
                        short targetCount = short.Parse(attackAttr.Attributes["targetCount"].Value);
                        long magicPathId = long.Parse(attackAttr.Attributes["magicPathID"]?.Value ?? "0");
                        long cubeMagicPathId = long.Parse(attackAttr.Attributes["cubeMagicPathID"]?.Value ?? "0");
                        SkillAttack skillAttack = new(attackPoint, targetCount, magicPathId, cubeMagicPathId);

                        skillAttacks.Add(skillAttack);
                    }

                    SkillMotion skillMotion = new(sequenceName, motionEffect);
                    SkillLevel skillLevel = new(levelValue, spirit, stamina, damageRate, feature, skillMotion, skillAttacks, skillConditions, skillUpgrade);
                    skillLevels.Add(skillLevel);
                }
                skillList.Add(new(skillId, skillLevels, skillState, skillAttackType, skillType, skillSubType, skillElement, skillSuperArmor, skillRecovery));
                continue;
            }

            // Parsing SubSkills
            if (entry.Name.StartsWith("table/job"))
            {
                XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
                XmlNodeList jobs = doreplacedent.SelectNodes("/ms2/job");
                foreach (XmlNode job in jobs)
                {
                    // Grabs all the skills and them the jobCode.
                    XmlNodeList skills = job.SelectNodes("skills/skill");
                    int jobCode = int.Parse(job.Attributes["code"].Value);
                    foreach (XmlNode skill in skills)
                    {
                        int id = int.Parse(skill.Attributes["main"].Value);
                        short maxLevel = short.Parse(skill.Attributes["maxLevel"]?.Value ?? "1");
                        skillList.Find(x => x.SkillId == id).Job = jobCode;
                        skillList.Find(x => x.SkillId == id).MaxLevel = maxLevel;

                        // If it has subSkill, add as well.
                        if (skill.Attributes["sub"] == null)
                        {
                            continue;
                        }

                        int[] sub = skill.Attributes["sub"].Value.Split(",").Select(int.Parse).ToArray();
                        skillList.Find(x => x.SkillId == id).SubSkills = sub;
                        for (int n = 0; n < sub.Length; n++)
                        {
                            if (skillList.Select(x => x.SkillId).Contains(sub[n]))
                            {
                                skillList.Find(x => x.SkillId == sub[n]).Job = jobCode;
                            }
                        }
                    }
                    XmlNodeList learnSkills = job.SelectNodes("learn/skill");
                    foreach (XmlNode learnSkill in learnSkills)
                    {
                        int id = int.Parse(learnSkill.Attributes["id"].Value);
                        skillList.Find(x => x.SkillId == id).CurrentLevel = 1;
                    }
                }
            }
        }

        // Parsing Additional Data
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("additionaleffect"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList levels = doreplacedent.SelectNodes("/ms2/level");
            int skillId = int.Parse(Path.GetFileNameWithoutExtension(entry.Name));

            List<SkillLevel> skillLevels = new();
            if (skillList.Select(x => x.SkillId).Contains(skillId))
            {
                foreach (XmlNode level in levels)
                {
                    int currentLevel = int.Parse(level.SelectSingleNode("BasicProperty").Attributes["level"]?.Value ?? "0");
                    skillLevels = skillList.Find(x => x.SkillId == skillId).SkillLevels;

                    if (skillLevels.Select(x => x.Level).Contains(currentLevel))
                    {
                        skillLevels.Find(x => x.Level == currentLevel).SkillAdditionalData = ParseSkillData(level);
                    }
                }
                continue;
            }

            // Adding missing skills from additionaleffect.
            // Since they are many skills that are called by another skill and not from player directly.
            foreach (XmlNode level in levels)
            {
                int currentLevel = int.Parse(level.SelectSingleNode("BasicProperty").Attributes["level"]?.Value ?? "0");
                skillLevels.Add(new(currentLevel, ParseSkillData(level)));
            }
            skillList.Add(new(skillId, skillLevels));

        }
        return skillList;
    }

19 View Source File : GameService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task Start(Game.StartCommand command, CancellationToken cancellationToken = default)
        {
            var (session, id) = command;
            var context = CommandContext.GetCurrent();

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);
            var dbGame = await GetDbGame(dbContext, id, cancellationToken);
            var game = dbGame.ToModel();
            var engine = GameEngines[game.EngineId];

            if (game.Stage != GameStage.New)
                throw new InvalidOperationException("Game has already been started.");
            if (game.UserId != userId && !engine.AutoStart)
                throw new InvalidOperationException("Only the creator of the game can start it.");
            if (game.Players.Count < engine.MinPlayerCount)
                throw new InvalidOperationException(
                    $"{engine.MinPlayerCount - game.Players.Count} more player(s) must join to start the game.");
            if (game.Players.Count > engine.MaxPlayerCount)
                throw new InvalidOperationException(
                    $"Too many players: {engine.MaxPlayerCount - game.Players.Count} player(s) must leave to start the game.");

            context.Operation().Items.Set(Box.New(game.Stage)); // Saving prev. stage
            var now = Clock.Now;
            game = game with {
                StartedAt = now,
                LastMoveAt = now,
                Stage = GameStage.Playing,
            };
            game = engine.Start(game);
            dbGame.UpdateFrom(game);
            await dbContext.SaveChangesAsync(cancellationToken);
            context.Operation().Items.Set(game);
        }

19 View Source File : RedisStreamCommand.cs
License : MIT License
Project Creator : 2881099

public override (long count, string minId, string maxId, (string consumer, long count)[] pendings) Parse(RedisReader reader)
        {
            reader.ExpectType(RedisMessage.MultiBulk);
            long count = reader.ReadInt(false);
            if (count != 4) throw new RedisProtocolException("XPedding 返回数据格式 1级 MultiBulk 长度应该为 4");

            var retCount = reader.ReadInt();
            var minId = reader.ReadBulkString();
            var maxId = reader.ReadBulkString();

            reader.ExpectType(RedisMessage.MultiBulk);
            var lvl2Count = reader.ReadInt(false);
            var pendings = new (string consumer, long count)[lvl2Count];

            for (var a = 0; a < lvl2Count; a++)
            {
                reader.ExpectType(RedisMessage.MultiBulk);
                var lvl3Count = reader.ReadInt(false);
                if (lvl3Count != 2) throw new RedisProtocolException("XPedding 返回数据格式 3级 MultiBulk 长度应该为 2");

                pendings[a] = (reader.ReadBulkString(), long.Parse(reader.ReadBulkString()));
            }

            return (retCount, minId, maxId, pendings);
        }

19 View Source File : GameService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<ImmutableList<Game>> ListOwn(
            string? engineId, GameStage? stage, int count, Session session,
            CancellationToken cancellationToken = default)
        {
            if (count < 1)
                throw new ArgumentOutOfRangeException(nameof(count));

            var user = await AuthService.GetUser(session, cancellationToken);
            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);
            await PseudoListOwn(user.Id, cancellationToken);

            await using var dbContext = CreateDbContext();
            var games = dbContext.Games.AsQueryable().Where(g => g.Players.Any(p => p.DbUserId == userId));
            if (engineId != null)
                games = games.Where(g => g.EngineId == engineId);
            if (stage != null) {
                games = games.Where(g => g.Stage == stage.GetValueOrDefault());
                switch (stage.GetValueOrDefault()) {
                case GameStage.New:
                    games = games.OrderByDescending(g => g.CreatedAt);
                    break;
                case GameStage.Playing:
                    games = games.OrderByDescending(g => g.StartedAt);
                    break;
                case GameStage.Ended:
                    games = games.OrderByDescending(g => g.EndedAt);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else {
                games = games.OrderByDescending(g => g.CreatedAt);
            }
            var gameIds = await games.Select(g => g.Id).Take(count)
                .ToListAsync(cancellationToken);
            return await GetMany(gameIds, cancellationToken);
        }

19 View Source File : MesoMarketPacket.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static PacketWriter LoadMarket()
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.MESO_MARKET);
        pWriter.Write(MesoMarketPacketMode.LoadMarket);
        pWriter.WriteFloat(float.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketTax")));
        pWriter.WriteFloat(float.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketPriceRange")));
        pWriter.WriteLong(long.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketAveragePrice"))); // TODO: Calculate average price
        pWriter.WriteInt(int.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketTotaListingsLimit")));
        pWriter.WriteInt(int.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketDailyListingsLimit")));
        pWriter.WriteInt(int.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketMonthlyPurchaseLimit")));
        pWriter.WriteInt(int.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketListingDayDuration")));
        pWriter.WriteInt(int.Parse(ConstantsMetadataStorage.GetConstant("MesoMarketListingsDisplayCount")));
        pWriter.WriteInt(100); // unk
        pWriter.WriteInt(1000); // unk
        return pWriter;
    }

19 View Source File : TransferScreen.cs
License : MIT License
Project Creator : allartprotocol

private async void TransferSol()
        {
            RequestResult<string> result = await SimpleWallet.instance.TransferSol(toPublic_txt.text, long.Parse(ammount_txt.text));
            HandleResponse(result);
        }

19 View Source File : BaiduCloudUser.cs
License : MIT License
Project Creator : Accelerider

public override async Task<bool> RefreshAsync()
        {
            try
            {
                var homePage = await Api.GetHomePageAsync();
                Token = homePage.GetMatch("\"bdstoken\":\"", "\",");
                UserId = long.Parse(homePage.GetMatch("\"uk\":", ",\"t"));
                Username = Regex.Unescape(homePage.GetMatch("\"username\":\"", "\","));

                return true;
            }
            catch
            {
                return false;
            }
        }

19 View Source File : TransferScreen.cs
License : MIT License
Project Creator : allartprotocol

private async void TransferToken()
        {
            RequestResult<string> result = await SimpleWallet.instance.TransferToken(
                                transferTokenAccount.pubkey,
                                toPublic_txt.text,
                                SimpleWallet.instance.wallet.GetAccount(0),
                                transferTokenAccount.Account.Data.Parsed.Info.Mint,
                                long.Parse(ammount_txt.text));

            HandleResponse(result);
        }

19 View Source File : FieldManager.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

(int) Map.PrivateResidence)
        {
            Home home = GameServer.HomeManager.GetHomeById(player.VisitingHomeId);
            if (home != null)
            {
                // Add cubes to state
                Dictionary<long, Cube> cubes = home.FurnishingInventory;
                foreach (Cube cube in cubes.Values.Where(x => x.PlotNumber == 1))
                {
                    IFieldObject<Cube> ugcCube = RequestFieldObject(cube);
                    ugcCube.Coord = cube.CoordF;
                    ugcCube.Rotation = cube.Rotation;
                    State.AddCube(ugcCube);
                }

                // Add portals to state
                IEnumerable<Cube> cubePortals = cubes.Values.Where(x => x.Item.Id == 50400158);
                foreach (Cube cubePortal in cubePortals)
                {
                    Portal portal = new(GuidGenerator.Int())
                    {
                        IsVisible = true,
                        IsEnabled = true,
                        IsMinimapVisible = false,
                        Rotation = cubePortal.Rotation,
                        PortalType = PortalTypes.Home
                    };

                    IFieldObject<Portal> fieldPortal = RequestFieldObject(portal);
                    fieldPortal.Coord = cubePortal.CoordF;
                    fieldPortal.Value.UGCPortalMethod = cubePortal.PortalSettings.Method;
                    if (!string.IsNullOrEmpty(cubePortal.PortalSettings.DestinationTarget))
                    {
                        switch (cubePortal.PortalSettings.Destination)
                        {
                            case UGCPortalDestination.PortalInHome:
                                fieldPortal.Value.TargetMapId = (int) Map.PrivateResidence;
                                break;
                            case UGCPortalDestination.SelectedMap:
                                fieldPortal.Value.TargetMapId = int.Parse(cubePortal.PortalSettings.DestinationTarget);
                                break;
                            case UGCPortalDestination.FriendHome:
                                fieldPortal.Value.TargetHomeAccountId = long.Parse(cubePortal.PortalSettings.DestinationTarget);
                                break;
                        }
                    }
                    cubePortal.PortalSettings.PortalObjectId = fieldPortal.ObjectId;
                    AddPortal(fieldPortal);
                }
            }
        }

19 View Source File : PermissionHandler.cs
License : MIT License
Project Creator : AlphaYu

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (!context.User.Idenreplacedy.IsAuthenticated)
            {
                context.Fail();
                return;
            }

            var userId = long.Parse(context.User.Claims.First(x => x.Type == JwtRegisteredClaimNames.Sub).Value);
            var validationVersion = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Version).Value;
            //var roles = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role).Value;
            //if (string.IsNullOrWhiteSpace(roles))
            //{
            //    context.Fail();
            //    return;
            //}

            //var roleIds = roles.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x));
            //if (roleIds.Contains(1))
            //{
            //    context.Succeed(requirement);
            //    return;
            //}
            //else
            //{
            if (context.Resource is HttpContext httpContext)
            {
                var codes = httpContext.GetEndpoint().Metadata.GetMetadata<PermissionAttribute>().Codes;
                var result = await CheckUserPermissions(userId, codes, validationVersion);
                if (result)
                {
                    context.Succeed(requirement);
                    return;
                }
            }
            context.Fail();
        }

19 View Source File : RedisDate.cs
License : MIT License
Project Creator : 2881099

public override DateTime Parse(RedisReader reader)
            {
                reader.ExpectType(RedisMessage.MultiBulk);
                reader.ExpectSize(2);

                var timestamp = Int32.Parse(reader.ReadBulkString());
                var microseconds = long.Parse(reader.ReadBulkString());

                return FromTimestamp(timestamp, microseconds);
            }

19 View Source File : RoleAppService.cs
License : MIT License
Project Creator : AlphaYu

public async Task<RoleTreeDto> GetRoleTreeListByUserIdAsync(long userId)
        {
            RoleTreeDto result = null;
            IEnumerable<ZTreeNodeDto<long, dynamic>> treeNodes = null;

            var user = await _cacheService.GetUserValidateInfoFromCacheAsync(userId);

            if (user == null)
                return null;

            var roles = await _cacheService.GetAllRolesFromCacheAsync();
            var roleIds = user.RoleIds?.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x)) ?? new List<long>();
            if (roles.Any())
            {
                treeNodes = roles.Select(x => new ZTreeNodeDto<long, dynamic>
                {
                    Id = x.Id,
                    PID = x.Pid ?? 0,
                    Name = x.Name,
                    Open = !(x.Pid.HasValue && x.Pid.Value > 0),
                    Checked = roleIds.Contains(x.Id)
                });

                result = new RoleTreeDto
                {
                    TreeData = treeNodes.Select(x => new Node<long>
                    {
                        Id = x.Id,
                        PID = x.PID,
                        Name = x.Name,
                        Checked = x.Checked
                    }),
                    CheckedIds = treeNodes.Where(x => x.Checked).Select(x => x.Id)
                };
            }

            return result;
        }

19 View Source File : Inventory.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public void ExpandInventory(GameSession session, InventoryTab tab)
    {
        long meretPrice = long.Parse(ConstantsMetadataStorage.GetConstant("InventoryExpandPrice1Row"));
        short expansionAmount = 6;

        if (session.Player.Account.RemoveMerets(meretPrice))
        {
            ExtraSize[tab] += expansionAmount;
            session.Send(ItemInventoryPacket.LoadTab(tab, ExtraSize[tab]));
            session.Send(ItemInventoryPacket.Expand());
        }
    }

19 View Source File : AEDPoSAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // ITriggerInformationProvider is for generating some necessary information
            // to trigger consensus hints from consensus contract.
            context.Services.AddSingleton<ITriggerInformationProvider, AEDPoSTriggerInformationProvider>();

            // IConsensusExtraDataExtractor is for extracting consensus data from extra data in Block Header.
            context.Services.AddTransient<IConsensusExtraDataExtractor, AEDPoSExtraDataExtractor>();

            // IBroadcastPrivilegedPubkeyListProvider is just a helper for network module
            // to broadcast blocks to nodes of higher priority.
            context.Services
                .AddSingleton<IBroadcastPrivilegedPubkeyListProvider, AEDPoSBroadcastPrivilegedPubkeyListProvider>();

            context.Services.AddSingleton<IBlocksExecutionSucceededLogEventProcessor, IrreversibleBlockFoundLogEventProcessor>();
            context.Services
                .AddSingleton<IBlockAcceptedLogEventProcessor, IrreversibleBlockHeightUnacceptableLogEventProcessor>();
            context.Services.AddSingleton<IBlocksExecutionSucceededLogEventProcessor, SecretSharingInformationLogEventProcessor>();
            context.Services.AddSingleton<IBlockTimeProvider, AEDPoSBlockTimeProvider>();
            
            // Our purpose is that other modules won't sense which consensus protocol are using, 
            // thus we read the configuration of ConsensusOption here.
            // (ConsensusOption itself can support all kinds of consensus protocol via adding more properties.)
            var configuration = context.Services.GetConfiguration();
            Configure<ConsensusOptions>(option =>
            {
                var consensusOptions = configuration.GetSection("Consensus");
                consensusOptions.Bind(option);

                var startTimeStamp = consensusOptions["StartTimestamp"];
                option.StartTimestamp = new Timestamp
                {
                    Seconds = string.IsNullOrEmpty(startTimeStamp) ? 0 : long.Parse(startTimeStamp)
                };

                if (option.InitialMinerList == null || option.InitialMinerList.Count == 0 ||
                    string.IsNullOrWhiteSpace(option.InitialMinerList[0]))
                {
                    // If InitialMinerList isn't configured yet, then read AccountService and config current user as single initial miner.
                    AsyncHelper.RunSync(async () =>
                    {
                        var accountService = context.Services.GetRequiredServiceLazy<IAccountService>().Value;
                        var publicKey = (await accountService.GetPublicKeyAsync()).ToHex();
                        option.InitialMinerList = new List<string> {publicKey};
                    });
                }
            });
        }

19 View Source File : ExprPlainReader.cs
License : MIT License
Project Creator : 0x1000000

public bool TryGetInt64(IPlainItem node, string propertyName, out long value)
        {
            value = default;
            if (this.TryGetSubNode(node.Id, propertyName, null, out var prop) && prop.Value != null)
            {
                value = long.Parse(prop.Value, CultureInfo.InvariantCulture);
                return true;
            }
            return false;
        }

19 View Source File : RedisScanCommand.cs
License : MIT License
Project Creator : 2881099

public override RedisScan<T> Parse(RedisReader reader)
        {
            reader.ExpectType(RedisMessage.MultiBulk);
            if (reader.ReadInt(false) != 2)
                throw new RedisProtocolException("Expected 2 items");

            long cursor = Int64.Parse(reader.ReadBulkString());
            T[] items = _command.Parse(reader);

            return new RedisScan<T>(cursor, items);
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

public static long DeserializeInt64(Slice slice)
		{
			if (slice.IsNullOrEmpty) return 0L; //TODO: fail ?

			int type = slice[0];
			if (type <= FdbTupleTypes.IntPos8)
			{
				if (type >= FdbTupleTypes.IntNeg8) return FdbTupleParser.ParseInt64(type, slice);

				switch (type)
				{
					case FdbTupleTypes.Nil: return 0;
					case FdbTupleTypes.Bytes: return long.Parse(FdbTupleParser.ParseAscii(slice), CultureInfo.InvariantCulture);
					case FdbTupleTypes.Utf8: return long.Parse(FdbTupleParser.ParseUnicode(slice), CultureInfo.InvariantCulture);
				}
			}

			throw new FormatException(String.Format("Cannot convert tuple segment of type 0x{0:X} into a signed integer", type));
		}

19 View Source File : RecipeParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<RecipeMetadata> Parse()
    {
        List<RecipeMetadata> recipeList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/masteryreceipe"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList recipes = doreplacedent.SelectNodes("/ms2/receipe");

            foreach (XmlNode recipe in recipes)
            {
                string locale = recipe.Attributes["locale"]?.Value ?? "";
                if (locale != "NA" && locale != "")
                {
                    continue;
                }

                if (string.IsNullOrEmpty(recipe.Attributes["id"]?.Value))
                {
                    continue;
                }

                RecipeMetadata newRecipe = new();
                newRecipe.Id = int.Parse(recipe.Attributes["id"]?.Value ?? "0");

                newRecipe.MasteryType = short.Parse(recipe.Attributes["masteryType"]?.Value ?? "0");
                newRecipe.ExceptRewardExp = int.Parse(recipe.Attributes["exceptRewardExp"].Value) == 1;
                newRecipe.RequireMastery = long.Parse(recipe.Attributes["requireMastery"]?.Value ?? "0");
                newRecipe.RequireQuest = recipe.Attributes["requireQuest"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToList();
                newRecipe.RewardMastery = long.Parse(recipe.Attributes["rewardMastery"]?.Value ?? "0");
                newRecipe.GatheringTime = recipe.Attributes["gatheringTime"].Value;

                _ = long.TryParse(recipe.Attributes["requireMeso"]?.Value ?? "0", out newRecipe.RequireMeso);
                _ = long.TryParse(recipe.Attributes["rewardExp"]?.Value ?? "0", out newRecipe.RewardExp);
                _ = int.TryParse(recipe.Attributes["highPropLimitCount"]?.Value ?? "0", out newRecipe.HighPropLimitCount);
                _ = int.TryParse(recipe.Attributes["normalPropLimitCount"]?.Value ?? "0", out newRecipe.NormalPropLimitCount);

                for (int i = 1; i < 6; i++) // 6 being the max amount of required items there can be
                {
                    if (recipe.Attributes["requireItem" + i.ToString()].Value != "")
                    {
                        RecipeItem requiredItem = new();
                        List<int> itemMetadata = recipe.Attributes["requireItem" + i.ToString()].Value.Split(",").Select(int.Parse).ToList();
                        requiredItem.ItemId = itemMetadata[0];
                        requiredItem.Rarity = itemMetadata[1];
                        requiredItem.Amount = itemMetadata[2];
                        newRecipe.RequiredItems.Add(requiredItem);
                    }
                }

                for (int i = 1; i < 6; i++) // 6 being the max amount of reward items there can be
                {
                    if (recipe.Attributes["rewardItem" + i.ToString()].Value != "")
                    {
                        RecipeItem rewardItem = new();
                        List<int> itemMetadata = recipe.Attributes["rewardItem" + i.ToString()].Value.Split(",").Select(int.Parse).ToList();
                        rewardItem.ItemId = itemMetadata[0];
                        rewardItem.Rarity = itemMetadata[1];
                        rewardItem.Amount = itemMetadata[2];
                        newRecipe.RewardItems.Add(rewardItem);
                    }
                }

                _ = int.TryParse(recipe.Attributes["habitatMapId"]?.Value ?? "0", out newRecipe.HabitatMapId);
                recipeList.Add(newRecipe);
            }
        }
        return recipeList;
    }

19 View Source File : GroupContentsControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void UpdateDisplay(ScrollViewer scrollViewer, ICollection<Message> messages)
        {
            if (messages.Count == 0)
            {
                return;
            }

            Avalonia.Threading.Dispatcher.UIThread.Post(() =>
            {
                // Run on UI thread since the ScrollViewer is being directly manipulated.
                double originalHeight = scrollViewer?.GetValue(ScrollViewer.VerticalScrollBarMaximumProperty) ?? 0.0;
                if (originalHeight != 0)
                {
                    // Prevent the At Top event from firing while we are adding new messages
                    scrollViewer.SetValue(ScrollViewer.VerticalScrollBarValueProperty, 1);
                }

                var maxTimeDifference = TimeSpan.FromMinutes(15);

                // Messages retrieved with the before_id parameter are returned in descending order
                // Reverse iterate through the messages collection to go newest->oldest
                for (int i = messages.Count - 1; i >= 0; i--)
                {
                    var msg = messages.ElementAt(i);

                    var oldMsg = this.Messages.Items.FirstOrDefault(m => m.Id == msg.Id);

                    if (oldMsg == null)
                    {
                        // add new message
                        var msgVm = new MessageControlViewModel(
                            msg,
                            showPreviewsOnlyForMultiImages: this.Settings.UISettings.ShowPreviewsForMultiImages);
                        this.Messages.Add(msgVm);

                        // add an inline timestamp if needed
                        if (msg.CreatedAtTime.Subtract(this.LastMarkerTime) > maxTimeDifference)
                        {
                            var messageId = long.Parse(msg.Id);
                            var timeStampId = (messageId - 1).ToString();

                            this.Messages.Add(new InlineTimestampControlViewModel(msg.CreatedAtTime, timeStampId, msgVm.DidISendIt));
                            this.LastMarkerTime = msg.CreatedAtTime;
                        }
                    }
                    else
                    {
                        // update an existing one if needed
                        oldMsg.Message = msg;
                    }
                }

                // process read receipt and sent receipts
                if (this.MessageContainer.ReadReceipt != null)
                {
                    // Remove old markers
                    var toRemove = this.Messages.Items.OfType<InlineReadSentMarkerControlViewModel>().ToList();
                    foreach (var marker in toRemove)
                    {
                        this.Messages.Remove(marker);
                    }

                    // Attach a "Read Receipt" if the read message is displayed.
                    var matchedMessage = this.Messages.Items.FirstOrDefault(m => m.Id == this.MessageContainer.ReadReceipt.MessageId);
                    if (matchedMessage != null)
                    {
                        var msgId = long.Parse(matchedMessage.Id);

                        var readMarker = new InlineReadSentMarkerControlViewModel(
                            this.MessageContainer.ReadReceipt.ReadAtTime,
                            true,
                            (msgId + 1).ToString(),
                            (matchedMessage as MessageControlViewModel).DidISendIt);

                        this.Messages.Add(readMarker);
                    }

                    // Attach a "Sent Receipt" to the last message confirmed sent by GroupMe
                    var me = this.MessageContainer.WhoAmI();
                    var lastSentMessage = this.Messages.Items
                        .OfType<MessageControlViewModel>()
                        .OrderByDescending(m => m.Id)
                        .FirstOrDefault(m => m.Message.UserId == me.Id);

                    if (lastSentMessage != null && lastSentMessage != matchedMessage)
                    {
                        var msgId = long.Parse(lastSentMessage.Id);

                        var sentMarker = new InlineReadSentMarkerControlViewModel(
                            lastSentMessage.Message.CreatedAtTime,
                            false,
                            (msgId + 1).ToString(),
                            (lastSentMessage as MessageControlViewModel).DidISendIt);

                        this.Messages.Add(sentMarker);
                    }

                    // Send a Read Receipt for the last message received
                    var lastReceivedMessage = this.Messages.Items
                        .OfType<MessageControlViewModel>()
                        .OrderByDescending(m => m.Id)
                        .FirstOrDefault(m => m.Message.UserId != me.Id);

                    if (lastReceivedMessage != null && this.MessageContainer is Chat c)
                    {
                        var result = Task.Run(async () => await c.SendReadReceipt(lastReceivedMessage.Message)).Result;
                    }
                }

                if (originalHeight != 0)
                {
                    // Calculate the offset where the last message the user was looking at is
                    // Scroll back to there so new messages appear on top, above screen
                    scrollViewer?.GetObservable(ScrollViewer.VerticalScrollBarMaximumProperty).Take(2).Skip(1).Subscribe(newMax =>
                    {
                        double difference = newMax - originalHeight;
                        scrollViewer.SetValue(ScrollViewer.VerticalScrollBarValueProperty, difference);
                    });
                }

                if (messages.Count > 0)
                {
                    this.FirstDisplayedMessage = messages.Last();
                }
            });
        }

See More Examples