private void ExecuteAboutDataCommand(CommandDto commandDto)
        {
            if (commandDto.CommandType == CommandTypes.ADD)
            {
                ICommandAdd command = new AddAboutDataCommand(_loggerFactory, commandDto);
                command.Execute(_context);
                _commandDataAccessProvider.AddCommand(CommandEntity.CreateCommandEntity(commandDto));
                _commandDataAccessProvider.Save();
                command.UpdateIdforNewItems();
                _undocommands.Push(command);
            }

            if (commandDto.CommandType == CommandTypes.UPDATE)
            {
                ICommand command = new UpdateAboutDataCommand(_loggerFactory, commandDto);
                command.Execute(_context);
                _commandDataAccessProvider.AddCommand(CommandEntity.CreateCommandEntity(commandDto));
                _commandDataAccessProvider.Save();
                _undocommands.Push(command);
            }

            if (commandDto.CommandType == CommandTypes.DELETE)
            {
                ICommand command = new DeleteAboutDataCommand(_loggerFactory, commandDto);
                command.Execute(_context);
                _commandDataAccessProvider.AddCommand(CommandEntity.CreateCommandEntity(commandDto));
                _commandDataAccessProvider.Save();
                _undocommands.Push(command);
            }
        }
        public async Task <bool> TryHandlingCustomCommand(ICommandContext context, string message)
        {
            if (message[0] != char.Parse(_botConfig.Prefix))
            {
                return(false);
            }

            string cleanMsg = message.Substring(1, message.Length - 1);

            var command = new CommandDto {
                GuildID = context.Guild.Id, Name = cleanMsg
            };
            var payload = _discordPayloadFactory.CreateDiscordObjectPayload <CommandAPIPayload>(command);

            var result = await _apiService.GetAsync(payload);

            if (result.IsSuccessStatusCode)
            {
                var resultCommand = await result.Content.ReadAsJsonAsync <CommandDto>();

                await context.Channel.SendMessageAsync(resultCommand.Body);

                return(true);
            }

            return(false);
        }
Пример #3
0
        public async Task <string> ExecuteCommand(CommandDto command)
        {
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.Open();
                    Pipeline pipeline = runspace.CreatePipeline();
                    pipeline.Commands.AddScript(command.Argument);
                    pipeline.Commands.Add("Out-String");
                    Collection <PSObject> results = pipeline.Invoke();
                    runspace.CloseAsync();
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var result in results)
                    {
                        stringBuilder.AppendLine(result.ToString());
                    }

                    _logger.LogInformation(stringBuilder.ToString());
                    return(stringBuilder.ToString());
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(e.Message);
            }
        }
Пример #4
0
        public void CanCreateProductWithCommand_CallsRepository()
        {
            var commandRepoMock = new Mock <ICommandStateRepository>();
            var productsMock    = new Mock <IProductService>();
            var commandState    = new Fakes.CommandState();

            commandRepoMock.Setup(t => t.CreateCommandState()).Returns(commandState);

            var guid = Guid.NewGuid();
            var name = "New Project";

            var sut           = new CommandManager(commandRepoMock.Object, new DateTimeProvider());
            var commandConfig = new CommandConfig {
                Assembly = TestGlobals.Assembly, NameSpace = TestGlobals.Namespace, Name = CommandTypes.Create.ToString(), ProcessorName = TestGlobals.Entity, Processor = productsMock.Object
            };

            sut.AddConfig(commandConfig);

            var commandDto = new CommandDto {
                Entity = TestGlobals.Entity, EntityGuid = guid, Name = CommandTypes.Create.ToString(), ParametersJson = @"{name: '" + name + "'}"
            };
            var sutResult = sut.ProcessCommand(commandDto);

            productsMock.Verify(v => v.CreateProduct(guid, name), Times.Once);
        }
Пример #5
0
        private Command CreateCommand(CommandDto commandDto) // TODO: Move to a command factory class
        {
            if (commandDto == null)
            {
                throw new CommandParseException("Unknown command");
            }
            switch (commandDto.Type)
            {
            case CommandType.StartGame:
                return(new StartGameCommand());

            case CommandType.RedrawCard:
                if (!commandDto.CardId.HasValue)
                {
                    throw new CommandParseException();
                }
                return(new RedrawCardCommand
                {
                    CardId = commandDto.CardId.Value
                });

            case CommandType.EndRedrawCard:
                return(new EndRedrawCardCommand());

            case CommandType.ForfeitGame:
                return(new ForfeitGameCommand());

            case CommandType.Pass:
                return(new PassCommand());

            case CommandType.PickStartingPlayer:
                if (!commandDto.StartingPlayerUserId.HasValue)
                {
                    throw new CommandParseException();
                }
                return(new PickStartingPlayerCommand
                {
                    StartingPlayerUserId = commandDto.StartingPlayerUserId.Value
                });

            case CommandType.PlayCard:
                if (!commandDto.CardId.HasValue || !commandDto.Slot.HasValue)
                {
                    throw new CommandParseException();
                }
                return(new PlayCardCommand
                {
                    CardId = commandDto.CardId.Value,
                    TargetCardId = commandDto.ResurrectCardId,
                    Slot = commandDto.Slot.Value
                });

            case CommandType.UseBattleKingCard:
                return(new UseBattleKingCardCommand());

            default:
                throw new CommandParseException("Unknown command");
            }
        }
Пример #6
0
        public async Task Post(CommandDto commandDto)
        {
            _logger.LogInformation($"Started to execute command:{commandDto.CommandName}, for device:{commandDto.DeviceName}");

            await _commandInvoker.InvokeAsync(commandDto.CommandName, commandDto.DeviceName);

            _logger.LogInformation($"Command executed");
        }
Пример #7
0
 public void ExecuteCommand(CommandDto command)
 {
     _netMQManage.ExecuteCommand(command);
     _opertionRepository.InsertAsync(new OperationInfo()
     {
         Type = OperationType.Command, Remark = "直播云端命令:" + command.CommandType.ToEnumDesc(), ParamValue = command.ToJson()
     });
 }
Пример #8
0
        public ActionResult <CommandDto> CreateCommand(CommandDto commandDto)
        {
            var commandModel = _mapper.Map <Command>(commandDto);

            _repository.CreateCommand(commandModel);
            _repository.SaveChanges();

            return(CreatedAtRoute(nameof(GetCommandById), new { commandDto.Id }, commandDto));
        }
Пример #9
0
        public void Restart()
        {
            _isPaused = true;
            var dto = new CommandDto(DtoType.Restart);

            _timer.Dispose();
            _objectStateTimer.Dispose();
            _client.Send(JsonConvert.SerializeObject(dto));
        }
Пример #10
0
        public async Task <IRpcMethodResult> ExecuteWithCorrelationAndHeaders(
            string routingKey,
            CommandDto command,
            string authorizationToken,
            string correlationId,
            Dictionary <string, string> headers
            )
        {
            if (string.IsNullOrWhiteSpace(routingKey))
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Routing Key must be provided."));
            }
            if (command == null)
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Command must be provided."));
            }
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Command Name must be provided."));
            }
            if (command.Data == null)
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Command Data must be provided."));
            }
            if (string.IsNullOrWhiteSpace(authorizationToken))
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Authorization Token must be provided."));
            }
            if (string.IsNullOrWhiteSpace(correlationId))
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Correlation ID must be provided."));
            }
            if (headers == null)
            {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InvalidParams, "Headers must be provided."));
            }
            headers[CommandMessageHeaderNames.RoutingKey]         = routingKey;
            headers[CommandMessageHeaderNames.AuthorizationToken] = authorizationToken;
            headers[CommandMessageHeaderNames.CorrelationId]      = correlationId;
            CommandMessage commandMessage = new CommandMessage(
                new CommandMessageBody(command.Name, command.Data),
                new HeaderCollection(headers)
                );

            try {
                await _commandGateway.Send(commandMessage);
            } catch (Exception exception) {
                return(new RpcMethodErrorResult((int)RpcErrorCode.InternalError, exception.Message));
            }
            return(new RpcMethodSuccessResult(new ExecuteResponseDto()
            {
                CorrelationId = correlationId
            }));
        }
Пример #11
0
 public void ExecuteCommand(CommandDto command)
 {
     try
     {
         netMQService.Publish(command.FactoryCode, command);
         LogHelper.Debug("命令已发送:" + command.ToJson());
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex);
     }
 }
        public CommandDto ActualCommandDtoForNewState(string commandType)
        {
            var aboutData  = _commandDto.Payload.ToObject <AboutData>();
            var commandDto = new CommandDto();

            commandDto.ActualClientRoute = _commandDto.ActualClientRoute;
            commandDto.CommandType       = _commandDto.CommandType;
            commandDto.PayloadType       = _commandDto.PayloadType;
            aboutData.Deleted            = _aboutData.Deleted;

            commandDto.Payload = JObject.FromObject(aboutData);
            return(commandDto);
        }
Пример #13
0
 public Task <IRpcMethodResult> Execute(
     string routingKey,
     CommandDto command,
     string authorizationToken
     )
 {
     return(ExecuteWithCorrelationAndHeaders(
                routingKey,
                command,
                authorizationToken,
                Guid.NewGuid().ToString(),
                new Dictionary <string, string>()
                ));
 }
Пример #14
0
        public void StopPush(CommandDto commandDto)
        {
            ChannelPusher channelPusher = ChannelPusherService.GetChannelPusherById(commandDto);

            if (channelPusher != null)
            {
                channelPusher.CTS.Cancel();
                PushAMsgIn(commandDto.ChanneId, commandDto.Id, $"推流日志:发送停止命令完毕.", LiveStateType.Stoped);

                ChannelPusherService.RemoveChannelPusher(channelPusher);
                //重新序列化命令组
                SerializationCommangs();
            }
        }
Пример #15
0
        public ActionResult UpdateCommand(int id, CommandDto commandUpdateDto)
        {
            var commandModelFromRepo = _repository.GetCommandById(id);

            if (commandModelFromRepo == null)
            {
                return(NotFound());
            }
            _mapper.Map(commandUpdateDto, commandModelFromRepo);
            _repository.UpdateCommand(commandModelFromRepo);
            _repository.SaveChanges();

            return(NoContent());
        }
Пример #16
0
 public CommandDto ActualCommandDtoForNewState(string commandType)
 {
     if (commandType == CommandTypes.UNDO)
     {
         var commandDto = new CommandDto();
         commandDto.ActualClientRoute = _commandDto.ActualClientRoute;
         commandDto.CommandType       = _commandDto.CommandType;
         commandDto.PayloadType       = _commandDto.PayloadType;
         commandDto.Payload           = JObject.FromObject(_previousHomeData);
         return(commandDto);
     }
     else
     {
         return(_commandDto);
     }
 }
Пример #17
0
        public void CreatePostReturnsCreatedCommandAsync()
        {
            // Arrange
            var testGuid = Guid.NewGuid();
            var newIdea  = new CommandDto {
                Entity = "Product", Name = "Create", EntityGuid = testGuid, ParametersJson = @"{ Name: 'Test Project'}"
            };

            // Act
            var response = _client.PostAsJsonAsync("/api/commands", newIdea).Result;

            // Assert
            response.EnsureSuccessStatusCode();
            var returnedSession = response.Content.ReadAsJsonAsync <CommandDto>().Result;

            Assert.Equal(testGuid, returnedSession.EntityGuid);
        }
Пример #18
0
        public void CommandManager_CanMergeCommandsWithNoExistingState()
        {
            Guid entityGuid            = Guid.NewGuid();
            var  existingCreateCommand = new Fakes.CommandState {
                CommandTypeId = "CreateContactCommand", EntityGuid = entityGuid, Guid = Guid.NewGuid(), CreatedOn = DateTime.Now, ExecutedOn = DateTime.Now, ReceivedOn = DateTime.Now, ParametersJson = "{'Name': 'John Smith'}"
            };
            var existingChangeEmailCommand = new Fakes.CommandState {
                CommandTypeId = "ChangeEmailForContactCommand", EntityGuid = entityGuid, Guid = Guid.NewGuid(), CreatedOn = DateTime.Now, ExecutedOn = DateTime.Now, ReceivedOn = DateTime.Now, ParametersJson = "{'Email': '*****@*****.**'}"
            };
            var existingCommands = new List <ICommandState> {
                existingCreateCommand, existingChangeEmailCommand
            };
            DateTimeProvider dateTimeProvider = new DateTimeProvider();
            var repo = new Mock <ICommandStateRepository>();

            repo.Setup(s => s.CreateCommandState()).Returns(new Fakes.CommandState());
            repo.Setup(s => s.GetCommandStates(entityGuid)).Returns(existingCommands);
            var contactRepo = new EventSourcedMainRepository();
            var processor   = new ContactService(contactRepo, dateTimeProvider);
            // todo: make builder
            var sut = new CommandManager(repo.Object, dateTimeProvider);

            var processorConfig = new ProcessorConfig();

            processorConfig.Assembly  = "SoftwareManagementCore";
            processorConfig.NameSpace = "ContactsShared";
            processorConfig.Entity    = "Contact";
            processorConfig.Processor = processor;
            sut.AddConfig(processorConfig);

            // todo: make builder
            var updateEmailCommandDto = new CommandDto {
                CreatedOn = DateTime.Now.AddTicks(1), Entity = "Contact", EntityGuid = entityGuid, Guid = Guid.NewGuid(), Name = "ChangeEmailFor", ParametersJson = @"{Email: '*****@*****.**', OriginalEmail:'*****@*****.**'}"
            };
            //            var updateNameCommandDto = new CommandDto { CreatedOn = DateTime.Now.AddTicks(2), Entity = "Contact", EntityGuid = entityGuid, Guid = Guid.NewGuid(), Name = "Rename", ParametersJson = @"{ Name: 'James Smith', OriginalName: 'John Smith'}" };
            var commandDtos = new List <CommandDto> {
                updateEmailCommandDto
            };

            sut.MergeCommands(commandDtos);

            var contact = processor.GetContact(entityGuid);

            Assert.Equal("John Smith", contact.Name);
            Assert.Equal("*****@*****.**", contact.Email);
        }
Пример #19
0
 public void PausePlay()
 {
     if (_isPaused)
     {
         _isPaused = false;
         var dto = new CommandDto(DtoType.Play);
         _timer = new Timer(Tick, null, DateTime.Now.Second, _syncInterval);
         _client.Send(JsonConvert.SerializeObject(dto));
     }
     else
     {
         _isPaused = true;
         var dto = new CommandDto(DtoType.Pause);
         _timer.Dispose();
         _objectStateTimer.Dispose();
         _client.Send(JsonConvert.SerializeObject(dto));
     }
 }
Пример #20
0
        public GameHubResult <GameDto> RecieveClientCommand(CommandDto commandDto)
        {
            try
            {
                Command command      = CreateCommand(commandDto);
                long    senderUserId = UserId;
                command.SenderUserId = senderUserId;

                int retryCount = Constants.RetryExecuteCommandCount;
                while (retryCount > 0)
                {
                    try
                    {
                        return(ExecuteClientCommand(command));
                    }
                    catch (OptimisticConcurrencyException)
                    {
                        retryCount--;
                    }
                }

                return(new GameHubResult <GameDto>
                {
                    Error = string.Format("Hub: Unable to execute command after {0} tries", Constants.RetryExecuteCommandCount)
                });
            }
            catch (Exception e)
            {
                GwintException gwintException = e as GwintException;
                if (gwintException != null)
                {
                    return(new GameHubResult <GameDto>
                    {
                        Error = e.Message
                    });
                }

                return(new GameHubResult <GameDto>
                {
                    Error = "Hub: Internal server error"
                });
            }
        }
        public async Task <IActionResult> Post([FromBody] CommandDto command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string connectionString = this.configuration["ConnectionStrings:EventHub"];
            string deviceId         = "MyFirstIoTHubDevice";

            using (var serviceClient = ServiceClient.CreateFromConnectionString(connectionString))
            {
                var commandMessage = new Message();
                commandMessage.Properties.Add(new KeyValuePair <string, string>("Command", command.Command));
                commandMessage.Ack = DeliveryAcknowledgement.Full;
                await serviceClient.SendAsync(deviceId, commandMessage);
            }

            return(Ok());
        }
        public void Execute(CommandDto commandDto)
        {
            if (commandDto.PayloadType == PayloadTypes.ABOUT)
            {
                ExecuteAboutDataCommand(commandDto);
                return;
            }

            if (commandDto.PayloadType == PayloadTypes.HOME)
            {
                ExecuteHomeDataCommand(commandDto);
                return;
            }

            if (commandDto.PayloadType == PayloadTypes.NONE)
            {
                ExecuteNoDataCommand(commandDto);
                return;
            }
        }
Пример #23
0
 /// 将一个频道压入工作列表
 /// </summary>
 /// <param name="liveChannel"></param>
 /// <returns></returns>
 public static ChannelPusher PushChannelIntoWorkingList(CommandDto commandDto)
 {
     lock (_lockObj)
     {
         if (!IsChannelExistingInWorkingList(commandDto))
         {
             var channelPusher = new ChannelPusher
             {
                 CommandDto = commandDto
             };
             //所有压入到工作表的状态都会修改为开始
             channelPusher.CommandDto.CommandType = CommandTypeEnum.Start;
             ChannelPushers.Add(channelPusher);
             return(channelPusher);
         }
         else
         {
             return(null);
         }
     }
 }
Пример #24
0
        public void ExecuteCommand(CommandDto command)
        {
            switch (command.CommandType)
            {
            case CommandTypeEnum.Start:
                StartPush(command);
                break;

            case CommandTypeEnum.Stop:
                StopPush(command);
                break;

            case CommandTypeEnum.Switch:
            case CommandTypeEnum.ReStart:
                RestartPush(command);
                break;

            default:
                PushAMsgIn(Guid.Empty, Guid.Empty, $"服务日志: 错误的命令类型,请检查!{command.ToString()}", LiveStateType.Error);
                break;
            }
        }
Пример #25
0
        public async Task InitializePublisher(ClientConfiguration configuration)
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(configuration.ClientId)
                          .WithCleanSession(false)
                          .WithTcpServer(configuration.Host, configuration.Port)
                          .WithCredentials(configuration.Username, configuration.Password)
                          .WithKeepAlivePeriod(TimeSpan.FromMilliseconds(configuration.KeepAlivePeriod))
                          .WithCommunicationTimeout(TimeSpan.FromMilliseconds(configuration.CommunicationTimeout)).Build();

            var mqttClient    = new MqttFactory().CreateMqttClient();
            var connectResult = await mqttClient.ConnectAsync(options);

            Console.WriteLine($"Publisher connection result : {connectResult.ResultCode}");

            var rpcOptions = new MqttRpcClientOptions()
            {
                TopicGenerationStrategy = new DefaultMqttRpcClientTopicGenerationStrategy()
            };

            var rpcClient = new MqttRpcClient(mqttClient, rpcOptions);

            var command = new CommandDto
            {
                Id      = 1,
                Message = "Say Hello world!"
            };

            var payload = JsonConvert.SerializeObject(command);

            Console.WriteLine($"Publisher requesting work \"DoWork\" with Id : 1");

            var responseMqtt = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(50), "DoWork", payload, MqttQualityOfServiceLevel.AtLeastOnce);

            var response = Encoding.Default.GetString(responseMqtt);

            Console.WriteLine($"Publisher got response : {response}");
        }
Пример #26
0
        public ActionResult UpdateCommand(int id, CommandDto command)
        {
            try
            {
                var model = _repository.GetCommandById(id);

                if (model == null)
                {
                    return(NotFound());
                }

                _mapper.Map(command, model);
                _repository.UpdateCommand(model);
                _repository.SaveChanges();


                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        // TODO add return object for UI
        public CommandDto Redo()
        {
            var commandDto = new CommandDto();

            commandDto.CommandType       = CommandTypes.REDO;
            commandDto.PayloadType       = PayloadTypes.NONE;
            commandDto.ActualClientRoute = "NONE";

            if (_redocommands.Count > 0)
            {
                ICommand command;
                if (_redocommands.TryPop(out command))
                {
                    _undocommands.Push(command);
                    command.Execute(_context);
                    commandDto.Payload = command.ActualCommandDtoForNewState(CommandTypes.REDO).Payload;
                    _commandDataAccessProvider.AddCommand(CommandEntity.CreateCommandEntity(commandDto));
                    _commandDataAccessProvider.Save();
                    return(command.ActualCommandDtoForNewState(CommandTypes.REDO));
                }
            }

            return(commandDto);
        }
 public AddHomeDataCommand(ILoggerFactory loggerFactory, CommandDto commandDto)
 {
     _logger     = loggerFactory.CreateLogger("AddHomeDataCommand");
     _commandDto = commandDto;
 }
 public DeleteAboutDataCommand(ILoggerFactory loggerFactory, CommandDto commandDto)
 {
     _logger     = loggerFactory.CreateLogger("DeleteAboutDataCommand");
     _commandDto = commandDto;
 }
Пример #30
0
 public void RestartPush(CommandDto commandDto)
 {
     StopPush(commandDto);
     Thread.Sleep(commandDto.CommandType == CommandTypeEnum.Switch ? 500 : 2000);
     StartPush(commandDto);
 }