public async Task <ActionResult> Create(CreateSectionModel model) { if (_contextService.GetCurrentAccount(HttpContext).AccountName != "admin") { return(Json(new { success = false, errorMsg = "只有系统管理员才能新建版块。" })); } var result = await _commandService.ExecuteAsync(new CreateSectionCommand(ObjectId.GenerateNewStringId(), model.Name, model.Description)); if (result.Status == CommandStatus.Failed) { return(Json(new { success = false, errorMsg = result.Result })); } return(Json(new { success = true })); }
public async IAsyncEnumerable <PlayerInfo> QueryAsync(PlayerInfoQuery query) { foreach (var sessionId in query.SessionIds) { var getPlayerQuery = new GetPlayerRequest { SessionId = sessionId }; var queryReply = await m_MessageQueueService .RequestAsync("session.get", getPlayerQuery.ToByteArray()) .ConfigureAwait(false); var data = GetPlayerResponse.Parser.ParseFrom(queryReply.Data); if (data.Player == null) { await m_LeaveRoomService .ExecuteAsync(new LeaveRoomCommand { SessionId = sessionId, Room = "test" }) .ConfigureAwait(false); } else { yield return(new PlayerInfo(data.Player.SessionId, data.Player.ConnectorId, data.Player.Name)); } } }
public async ValueTask HandleAsync(Msg msg, CancellationToken cancellationToken) { var request = LeaveRoomRequest.Parser.ParseFrom(msg.Data); await m_LeaveRoomService.ExecuteAsync(new LeaveRoomCommand { SessionId = request.SessionId, Room = request.Room }).ConfigureAwait(false); var roomSessionIds = m_ListRoomSessionsService .QueryAsync(new RoomSessionsQuery { Room = request.Room }) .ToEnumerable(); var refrashPacket = new SendPacket { Subject = "room.player.refrash" }; refrashPacket.SessionIds.AddRange(roomSessionIds); await m_MessageQueueService.PublishAsync( "connect.send", refrashPacket.ToByteArray()).ConfigureAwait(false); await m_MessageQueueService.PublishAsync(msg.Reply, Array.Empty <byte>()).ConfigureAwait(false); m_Logger.LogInformation($"({request.SessionId}, {request.Room}) leaved."); }
public async Task <ActionResult> Register(RegisterModel model, CancellationToken token) { string pwd = PasswordHash.PasswordHash.CreateHash(model.Password); var result = await _commandService.ExecuteAsync(new RegisterNewAccountCommand(ObjectId.GenerateNewStringId(), model.AccountName, pwd), CommandReturnType.EventHandled); if (result.Status != AsyncTaskStatus.Success) { return(Json(new { success = false, errorMsg = result.ErrorMessage })); } var commandResult = result.Data; if (commandResult.Status == CommandStatus.Failed) { if (commandResult.ResultType == typeof(DuplicateAccountException).Name) { return(Json(new { success = false, errorMsg = "该账号已被注册,请用其他账号注册。" })); } return(Json(new { success = false, errorMsg = commandResult.Result })); } await SignInAsync(commandResult.AggregateRootId, model.AccountName, false); return(Json(new { success = true })); }
public async Task <ActionResult> Create(CreateReplyModel model) { AsyncTaskResult <CommandResult> asyncTaskResult = await _commandService.ExecuteAsync( new CreateReplyCommand( model.PostId, model.ParentId, model.Body, _contextService.CurrentAccount.AccountId), CommandReturnType.EventHandled); var result = asyncTaskResult.Data; if (result.Status == CommandStatus.Failed) { return(Json(new { success = false, errorMsg = result.ErrorMessage })); } return(Json(new { success = true })); }
public async Task <ActionResult> Create(CreateReplyModel model) { var currentAccount = _contextService.GetCurrentAccount(HttpContext); var result = await _commandService.ExecuteAsync( new CreateReplyCommand( ObjectId.GenerateNewStringId(), model.PostId, model.ParentId, model.Body, currentAccount.AccountId), CommandReturnType.EventHandled); if (result.Status == CommandStatus.Failed) { return(Json(new { success = false, errorMsg = result.Result })); } return(Json(new { success = true })); }
public async Task <ActionResult> Create(CreateSectionModel model) { if (_contextService.CurrentAccount.AccountName != "admin") { return(Json(new { success = false, errorMsg = "只有系统管理员才能新建版块。" })); } AsyncTaskResult <CommandResult> asyncTaskResult = await _commandService.ExecuteAsync(new CreateSectionCommand(model.Name), CommandReturnType.EventHandled); var result = asyncTaskResult.Data; if (result.Status == CommandStatus.Failed) { return(Json(new { success = false, errorMsg = result.ErrorMessage })); } return(Json(new { success = true })); }
protected CommandResult ExecuteCommand(ICommand command) { var result = _commandService.ExecuteAsync(command, CommandReturnType.EventHandled).WaitResult <AsyncTaskResult <CommandResult> >(10000); if (result.Status != AsyncTaskStatus.Success) { _logger.ErrorFormat("Command execute failed, errorMessage: " + result.ErrorMessage); } return(result.Data); }
static void create_and_update_aggregate_test() { Console.WriteLine(""); Console.WriteLine("----create_and_update_aggregate_test start."); var noteId = ObjectId.GenerateNewStringId(); var command = new CreateNoteCommand { AggregateRootId = noteId, Title = "Sample Note" }; //执行创建聚合根的命令 var asyncResult = _commandService.ExecuteAsync(command).Result; Assert.NotNull(asyncResult); Assert.AreEqual(AsyncTaskStatus.Success, asyncResult.Status); var commandResult = asyncResult.Data; Assert.NotNull(commandResult); Assert.AreEqual(CommandStatus.Success, commandResult.Status); var note = _memoryCache.Get <Note>(noteId); Assert.NotNull(note); Assert.AreEqual("Sample Note", note.Title); Assert.AreEqual(1, ((IAggregateRoot)note).Version); //执行修改聚合根的命令 var command2 = new ChangeNoteTitleCommand { AggregateRootId = noteId, Title = "Changed Note" }; asyncResult = _commandService.ExecuteAsync(command2).Result; Assert.NotNull(asyncResult); Assert.AreEqual(AsyncTaskStatus.Success, asyncResult.Status); commandResult = asyncResult.Data; Assert.NotNull(commandResult); Assert.AreEqual(CommandStatus.Success, commandResult.Status); note = _memoryCache.Get <Note>(noteId); Assert.NotNull(note); Assert.AreEqual("Changed Note", note.Title); Assert.AreEqual(2, ((IAggregateRoot)note).Version); Console.WriteLine("----create_and_update_aggregate_test end."); }
public async ValueTask HandleAsync(Msg msg, CancellationToken cancellationToken) { var registration = UnregisterRequest.Parser.ParseFrom(msg.Data); await m_UnregisterSessionService.ExecuteAsync(new UnregisterSessionCommand { SessionId = registration.SessionId }).ConfigureAwait(false); await m_MessageQueueService.PublishAsync(msg.Reply, Array.Empty <byte>()).ConfigureAwait(false); m_Logger.LogInformation($"({registration.SessionId}) unregistered."); }
public async Task <ActionResult> Create(CreatePostModel model) { var result = await _commandService.ExecuteAsync( new CreatePostCommand( ObjectId.GenerateNewStringId(), model.Subject, model.Body, model.SectionId, _contextService.CurrentAccount.AccountId)); if (result.Status != AsyncTaskStatus.Success) { return(Json(new { success = false, errorMsg = result.ErrorMessage })); } var commandResult = result.Data; if (commandResult.Status == CommandStatus.Failed) { return(Json(new { success = false, errorMsg = commandResult.Result })); } return(Json(new { success = true })); }
public async Task <ActionResult> Register(RegisterModel model, CancellationToken token) { var result = await _commandService.ExecuteAsync(new RegisterNewAccountCommand(model.AccountName, model.Password), CommandReturnType.EventHandled); var commandResult = result.Data; if (commandResult.Status == CommandStatus.Failed) { if (commandResult.ExceptionTypeName == typeof(DuplicateAccountException).Name) { return(Json(new { success = false, errorMsg = "该账号已被注册,请用其他账号注册。" })); } return(Json(new { success = false, errorMsg = result.ErrorMessage })); } _authenticationService.SignIn(commandResult.AggregateRootId, model.AccountName, false); return(Json(new { success = true })); }
private async Task HandleMessageReceived(SocketMessage rawMessage) { // Ignore system messages and messages from bots if (!(rawMessage is SocketUserMessage message)) { return; } if (message.Source != MessageSource.User) { return; } var commandContext = new SocketCommandContext(client, message); var argumentPosition = 0; if (!message.HasMentionPrefix(client.CurrentUser, ref argumentPosition)) { // The message @Bot will come as <@{Id}> but client.CurrentUser.Mention is <@!{Id}> // So to be safe check for both in case it is changed... if (message.Content.Equals(client.CurrentUser.Mention) || message.Content.Equals(client.CurrentUser.Mention.Replace("!", string.Empty))) { IResult defaultResponseResult = await commandService.ExecuteDefaultResponse(commandContext, argumentPosition); await LogResult(commandContext, defaultResponseResult); } argumentPosition = 0; if (!message.HasCharPrefix('!', ref argumentPosition)) { // Not going to respond return; } } IResult result = await commandService.ExecuteAsync(commandContext, argumentPosition); await LogResult(commandContext, result); }
private Task <AsyncTaskResult <CommandResult> > ExecuteCommandAsync(ICommand command, int millisecondsDelay = 50000) { return(_commandService.ExecuteAsync(command, CommandReturnType.EventHandled).TimeoutAfter(millisecondsDelay)); }
protected CommandResult ExecuteCommand(ICommand command) { return(_commandService.ExecuteAsync(command, CommandReturnType.EventHandled).Result); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string token; int errorCode; string errorMessage; if ("OPTIONS".Equals(request.Method.Method.ToUpper())) { return(await base.SendAsync(request, cancellationToken)); } //determine whether a jwt exists or not if (!TryRetrieveToken(request, out token)) { return(await base.SendAsync(request, cancellationToken)); } try { var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(LotteryConstants.JwtSecurityKey)); SecurityToken securityToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = LotteryConstants.ValidAudience, // LotteryConstants.ValidAudience, ValidIssuer = LotteryConstants.ValidIssuer, // LotteryConstants.ValidIssuer, ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey, }; var principal = handler.ValidateToken(token, validationParameters, out securityToken); Thread.CurrentPrincipal = principal; HttpContext.Current.User = principal; var conLog = _conLogQueryService.GetUserConLog(_lotterySession.UserId, _lotterySession.SystemTypeId, _lotterySession.ClientNo, securityToken.ValidTo.ToLocalTime()); if (conLog != null && conLog.LogoutTime.HasValue) { throw new LotteryAuthorizationException("您已经登出,请重新登录"); } var okResponse = await base.SendAsync(request, cancellationToken); //extract and assign the user of the jwt if ((securityToken.ValidTo - DateTime.UtcNow).TotalMinutes <= 3) { DateTime invalidTime; var refreshToken = _userManager.UpdateToken(_lotterySession.UserId, _lotterySession.SystemTypeId, _lotterySession.ClientNo, out invalidTime); okResponse.Headers.Add("access-token", refreshToken); await _commandService.ExecuteAsync( new UpdateTokenCommand(conLog.Id, invalidTime, _lotterySession.UserId)); } return(okResponse); } catch (SecurityTokenInvalidLifetimeException ex) { try { var tokenInfo = ex.GetTokenInfo(); var conLog = _conLogQueryService.GetUserConLog(tokenInfo.NameId, tokenInfo.SystemTypeId, tokenInfo.ClientNo, tokenInfo.Exp); if (conLog != null) { await _commandService.ExecuteAsync(new LogoutCommand(conLog.Id, tokenInfo.NameId)); } errorCode = ErrorCode.OvertimeToken; errorMessage = "登录超时,请重新登录"; } catch (Exception e) { errorCode = ErrorCode.InvalidToken; errorMessage = e.Message; } } catch (SecurityTokenValidationException ex) { errorCode = ErrorCode.InvalidToken; errorMessage = "无效的Token" + ex.Message; } catch (LotteryAuthorizationException ex) { errorCode = ErrorCode.AuthorizationFailed; errorMessage = ex.Message; } catch (NullReferenceException) { errorCode = ErrorCode.InvalidToken; errorMessage = "无效的Token,原因:该Token已失效"; } catch (Exception ex) { errorCode = ErrorCode.InvalidToken; errorMessage = "无效的Token,原因:" + ex.Message; } var errorResponse = request.CreateResponse(HttpStatusCode.OK, new ResponseMessage(new ErrorInfo(errorCode, errorMessage), true)); // 对无效token,错误的请求解决无法跨域的问题 errorResponse.Headers.Add("Access-Control-Allow-Origin", "*"); return(await Task <HttpResponseMessage> .Factory.StartNew(() => errorResponse)); }
/// <summary> /// Execute a delayed command asynchronously with the specified command return type. /// </summary> /// <param name="commandService"></param> /// <param name="command"></param> /// <param name="commandReturnType"></param> /// <returns></returns> public static Task ExecuteDelayedCommandAsync(this ICommandService commandService, DelayedCommand command, CommandReturnType commandReturnType) { return(commandService.ExecuteAsync(command, commandReturnType)); }
public async Task ReceiveMessageAsync(SocketMessage incomingMessage) { if (!(incomingMessage is SocketUserMessage message) || message.Author is SocketWebhookUser || message.Author.IsBot) { return; } if (!(message.Channel is SocketGuildChannel)) { await message.Channel.TrySendMessageAsync( "Sorry, but I can only respond to commands in servers. Please try using your command in any of the servers that I share with you!") .ConfigureAwait(false); _failedCommandsTracking.LogError(LoggingEventIds.UserDirectMessaged, $"Received direct message from {message.Author}, ignoring."); return; } var argPos = 0; if (!message.HasStringPrefix(_config.CommandPrefix, ref argPos) && !message.HasMentionPrefix(_discordClient.CurrentUser, ref argPos)) { return; } var context = new AbyssRequestContext(message, _services); var requestString = message.Content.Substring(argPos); try { var result = await _commandService.ExecuteAsync(requestString, context, context.Services).ConfigureAwait(false); if (result.IsSuccessful) { if (!(result is SuccessfulResult)) { CommandSuccesses++; // SuccessfulResult indicates a RunMode.Async } return; } switch (result) { case CommandResult _: return; case CommandNotFoundResult cnfr: _failedCommandsTracking.LogWarning(LoggingEventIds.UnknownCommand, $"No command found matching {requestString} (message {message.Id} - channel {message.Channel.Name}/{message.Channel.Id} - guild {context.Guild.Name}/{context.Guild.Id})"); await context.Message.AddReactionAsync(UnknownCommandReaction).ConfigureAwait(false); return; case ExecutionFailedResult _: return; case ChecksFailedResult cfr: _failedCommandsTracking.LogWarning(LoggingEventIds.ChecksFailed, $"{cfr.FailedChecks.Count} checks ({string.Join(", ", cfr.FailedChecks.Select(c => c.Check.GetType().Name))}) " + $"failed for command {cfr.Command.Name} (message {message.Id} - channel {message.Channel.Name}/{message.Channel.Id} - guild {context.Guild.Name}/{context.Guild.Id})"); if (cfr.FailedChecks.Count == 1 && cfr.FailedChecks.FirstOrDefault().Check.GetType() .CustomAttributes.Any(a => a.AttributeType == typeof(SilentCheckAttribute))) { break; } await context.Channel.SendMessageAsync(embed : new EmbedBuilder() .WithTitle( $"No can do.") .WithDescription("Can't do that, because: \n" + string.Join("\n", cfr.FailedChecks.Where(a => a.Check.GetType().CustomAttributes.All(b => b.AttributeType != typeof(SilentCheckAttribute))) .Select(a => $"- {a.Result.Reason}"))) .WithColor(Color.Red) .WithFooter( $"{(cfr.Command == null ? $"Module {cfr.Module.Name}" : $"Command {cfr.Command.Name} in module {cfr.Command.Module.Name}")}, " + $"executed by {context.Invoker.Format()}") .WithCurrentTimestamp() .Build()).ConfigureAwait(false); break;
protected Task <CommandResult> ExecuteCommandAsync(ICommand command) { return(_commandService.ExecuteAsync(command, CommandReturnType.EventHandled)); }
public async ValueTask HandleAsync(Msg msg, CancellationToken cancellationToken) { var packet = QueuePacket.Parser.ParseFrom(msg.Data); var joinRoomData = JoinRoom.Parser.ParseFrom(packet.Payload); var roomSessionIds = m_ListRoomSessionsService .QueryAsync(new RoomSessionsQuery { Room = joinRoomData.Room }) .ToEnumerable() .ToArray(); try { await m_JoinRoomService.ExecuteAsync(new JoinRoomCommand { SessionId = packet.SessionId, Room = joinRoomData.Room, Password = joinRoomData.Password }).ConfigureAwait(false); var response = new SendPacket { Subject = "room.join.reply" }; response.SessionIds.Add(packet.SessionId); var responseContent = new JoinRoomReply { Status = JoinRoomStatus.Accpet }; response.Payload = responseContent.ToByteString(); await m_MessageQueueService.PublishAsync( "connect.send", response.ToByteArray()).ConfigureAwait(false); if (roomSessionIds.Length > 0) { var broadcast = new SendPacket { Subject = "chat.receive" }; broadcast.SessionIds.AddRange(roomSessionIds); var chatMessage = new ChatMessage { Scope = Scope.System, From = "System", Message = $"New player joined!" }; broadcast.Payload = chatMessage.ToByteString(); await m_MessageQueueService.PublishAsync( "connect.send", broadcast.ToByteArray()).ConfigureAwait(false); var refrashPacket = new SendPacket { Subject = "room.player.refrash" }; refrashPacket.SessionIds.AddRange(roomSessionIds); await m_MessageQueueService.PublishAsync( "connect.send", refrashPacket.ToByteArray()).ConfigureAwait(false); } m_Logger.LogInformation($"({packet.SessionId}, {joinRoomData.Room}) joined."); } catch (Exception ex) { m_Logger.LogError(ex, string.Empty); var response = new SendPacket { Subject = "room.join.reply" }; response.SessionIds.Add(packet.SessionId); var responseContent = new JoinRoomReply { Status = JoinRoomStatus.Reject, Reason = "進房失敗" }; response.Payload = responseContent.ToByteString(); await m_MessageQueueService.PublishAsync( "connect.send", response.ToByteArray()).ConfigureAwait(false); } }
protected CommandResult ExecuteCommand(ICommand command) { return(_commandService.ExecuteAsync(command, CommandReturnType.EventHandled).WaitResult <AsyncTaskResult <CommandResult> >(10000).Data); }