public void when_same_handler_handles_multiple_commands_then_gets_called_for_all()
        {
            var processor = new CommandProcessor(new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription), new JsonTextSerializer());
            var bus       = new CommandBus(new TopicSender(this.Settings, this.Topic), new StandardMetadataProvider(), new JsonTextSerializer());

            var fooWaiter = new ManualResetEventSlim();
            var barWaiter = new ManualResetEventSlim();
            var handler   = new MultipleHandler(fooWaiter, barWaiter);

            processor.Register(handler);

            processor.Start();

            try
            {
                bus.Send(new FooCommand());
                bus.Send(new BarCommand());

                fooWaiter.Wait(TimeoutPeriod);
                barWaiter.Wait(TimeoutPeriod);

                Assert.True(handler.HandledFooCommand);
                Assert.True(handler.HandledBarCommand);
            }
            finally
            {
                processor.Stop();
            }
        }
Exemple #2
0
        static void Main(string[] args)
        {
            ICommandBus commandBus = new CommandBus();
            IQueryBus   queryBus   = new QueryBus();
            var         cmd        = new ActorInsertCommand
            {
                FirstName = "Mst",
                LastName  = "Scl"
            };

            var result   = commandBus.Send <ActorInsertCommand, LongCommandResult>(cmd);
            var response = queryBus.Send <ActorReadAllQuery, ActorList>(new ActorReadAllQuery());
            //var serviceDetailTypeHandler = new ServiceDetailTypeInsertCommandHandler();

            //var result = serviceDetailTypeHandler.Handle(cmd);
            var id = result.Data.ReturnValue ?? -1L;

            Console.WriteLine("ReturnValue: " + result.Data?.ReturnValue);
            Console.WriteLine("ResponseCode: " + result.ResponseCode);
            Console.WriteLine("ResponseMessage: " + result.ResponseMessage);
            Thread.Sleep(2000);
            //var updateHandler = new ServiceDetailTypeUpdateCommandHandler();
            //result = updateHandler.Handle(
            //    new ServiceDetailTypeUpdateCommand
            //    {
            //        Id = id,
            //        DetailTypeName = "My First Service Updated",
            //        UpdatedBy = 1
            //    });
            result = commandBus.Send <ActorUpdateCommand, LongCommandResult>(new ActorUpdateCommand
            {
                FirstName = "Mst Updated",
                LastName  = "Scl Updated",
                ActorId   = (int)id
            });
            Console.WriteLine("ReturnValue: " + result.Data?.ReturnValue);
            Console.WriteLine("ResponseCode: " + result.ResponseCode);
            Console.WriteLine("ResponseMessage: " + result.ResponseMessage);
            Thread.Sleep(2000);
            //var deleteHandler = new ServiceDetailTypeDeleteCommandHandler();
            //result = deleteHandler.Handle(
            //    new ServiceDetailTypeDeleteCommand
            //    {
            //        Id = id
            //    });
            result = commandBus.Send <ActorDeleteCommand, LongCommandResult>(new ActorDeleteCommand
            {
                Id = (int)id
            });
            Console.WriteLine("ReturnValue: " + result.Data?.ReturnValue);
            Console.WriteLine("ResponseCode: " + result.ResponseCode);
            Console.WriteLine("ResponseMessage: " + result.ResponseMessage);
            Console.ReadKey();
        }
        public void when_sending_multiple_commands_with_delay_then_sets_message_enqueue_time()
        {
            var sender = new Mock <IMessageSender>();
            var bus    = new CommandBus(sender.Object, new StandardMetadataProvider(), new JsonTextSerializer());

            BrokeredMessage message = null;

            sender.Setup(x => x.Send(It.IsAny <Func <BrokeredMessage> >()))
            .Callback <Func <BrokeredMessage> >(mf =>
            {
                var m = mf();
                if (m.ScheduledEnqueueTimeUtc > DateTime.UtcNow.Add(TimeSpan.FromMinutes(4)))
                {
                    message = m;
                }
            });

            bus.Send(new[]
            {
                new Envelope <ICommand>(new FooCommand())
                {
                    Delay = TimeSpan.FromMinutes(5)
                },
                new Envelope <ICommand>(new BarCommand())
            });

            Assert.NotNull(message);
        }
        public void when_sending_multiple_commands_then_calls_all_handlers()
        {
            var processor = new CommandProcessor(new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription), new JsonTextSerializer());
            var bus       = new CommandBus(new TopicSender(this.Settings, this.Topic), new StandardMetadataProvider(), new JsonTextSerializer());

            var fooEvent   = new ManualResetEventSlim();
            var fooHandler = new FooCommandHandler(fooEvent);

            var barEvent   = new ManualResetEventSlim();
            var barHandler = new BarCommandHandler(barEvent);

            processor.Register(fooHandler);
            processor.Register(barHandler);

            processor.Start();

            try
            {
                bus.Send(new ICommand[] { new FooCommand(), new BarCommand() });

                fooEvent.Wait(TimeoutPeriod);
                barEvent.Wait(TimeoutPeriod);

                Assert.True(fooHandler.Called);
                Assert.True(barHandler.Called);
            }
            finally
            {
                processor.Stop();
            }
        }
        public void Invoke(InvestmentPayRequest action)
        {
            var investment = _investmentService.Get(action.InvestmentId);

            if (investment == null)
            {
                throw new BusinessException(BusinessStatusCode.NotFound, "投资不存在。");
            }
            if (investment.Status != Contracts.Enum.InvestmentStatus.Initial)
            {
                throw new BusinessException(BusinessStatusCode.Conflict, "投资已经支付。");
            }
            Project project = _projectService.Get(investment.ProjectId);

            using (UnitOfWork u = new UnitOfWork(EventBus))
            {
                CommandBus
                .Send(new CompleteInvestment(action.InvestmentId))
                .Send(new ChangeProjectAmount(project.ProjectId, 0 - investment.Amount))
                .Send(new ChangeAccountAmount(investment.AccountId, 0 - investment.Amount))
                .Send(new ChangeAccountAmount(project.BorrowerId, investment.Amount))
                .Send(new CreateAccountActivity(investment.AccountId, project.BorrowerId, investment.Amount));
                u.Complete();
            }
        }
        public void when_receiving_not_registered_command_then_ignores()
        {
            var receiver  = new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription);
            var processor = new CommandProcessor(receiver, new BinarySerializer());
            var bus       = new CommandBus(new TopicSender(this.Settings, this.Topic), new MetadataProvider(), new BinarySerializer());

            var e       = new ManualResetEventSlim();
            var handler = new FooCommandHandler(e);

            receiver.MessageReceived += (sender, args) => e.Set();

            processor.Register(handler);

            processor.Start();

            try
            {
                bus.Send(new BarCommand());

                e.Wait();
                // Give the other event handler some time.
                Thread.Sleep(100);

                Assert.False(handler.Called);
            }
            finally
            {
                processor.Stop();
            }
        }
        public void when_receiving_command_then_calls_handler()
        {
            var processor = new CommandProcessor(new SubscriptionReceiver(this.Settings, this.Topic, this.Subscription), new JsonTextSerializer());
            var bus       = new CommandBus(new TopicSender(this.Settings, this.Topic), new StandardMetadataProvider(), new JsonTextSerializer());

            var e       = new ManualResetEventSlim();
            var handler = new FooCommandHandler(e);

            processor.Register(handler);

            processor.Start();

            try
            {
                bus.Send(new FooCommand());

                e.Wait(TimeoutPeriod);

                Assert.True(handler.Called);
            }
            finally
            {
                processor.Stop();
            }
        }
        public void when_receiving_not_registered_command_then_ignores()
        {
            var receiverMock = new Mock <SubscriptionReceiver>(this.Settings, this.Topic, this.Subscription, false);
            var processor    = new CommandProcessor(receiverMock.Object, new JsonTextSerializer());
            var bus          = new CommandBus(new TopicSender(this.Settings, this.Topic), new StandardMetadataProvider(), new JsonTextSerializer());

            var e       = new ManualResetEventSlim();
            var handler = new FooCommandHandler(e);

            receiverMock.Protected().Setup("InvokeMessageHandler", ItExpr.IsAny <BrokeredMessage>()).Callback(() => e.Set());

            processor.Register(handler);

            processor.Start();

            try
            {
                bus.Send(new BarCommand());

                e.Wait(TimeoutPeriod);
                // Give the other event handler some time.
                Thread.Sleep(100);

                Assert.False(handler.Called);
            }
            finally
            {
                processor.Stop();
            }
        }
        public override void Apply(IdentityUser user, UserPropertyChange change)
        {
            var s   = change.ChangeValue as string;
            var cmd = new ChangeCustomerAccountPasswordCommand(user.Id, s);

            CommandBus.Send(cmd);
        }
        public override void PostExit()
        {
            base.PostExit();
            _commandBus.Send(new SaveHighScoreCommand(_resultData.Score, _resultData.ScoreAcquiredTime));

            _resultData = null;
        }
Exemple #11
0
        private void OnEnemiesWaveCleared()
        {
            Data.ClearWave();
            _commandBus.Send(new SubmitWaveClearedCommand());

            Data.CreateWave();
        }
Exemple #12
0
        public async Task <ActionResult> SecurityLogin(UserValidationRequest model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Email = model.Email;
                return(View("ValidateError"));
            }

            var cmd = new SecureLoginCommand(0, model);
            await CommandBus.Send(cmd);

            var isOk = cmd.Response.ResponseObj;

            if (!isOk)
            {
                ViewBag.Email = model.Email;
                return(View("ValidateError"));
            }

            var user = await UserManager.FindAsync(model.Email, model.Email);

            if (user?.UserStatus == SysStatus.Activated)
            {
                await SignInAsync(user, model.Remember);

                return(RedirectToDashboard());
            }

            ViewBag.Email = model.Email;
            return(View("ValidateError"));
        }
Exemple #13
0
 public void Create(string itemId, string description)
 {
     CommandBus.Send(new NewShopItemCommand(
                         itemId,
                         description
                         ));
 }
Exemple #14
0
        public override void Apply(IdentityUser user, UserPropertyChange change)
        {
            var claim = change.ChangeValue as Claim;
            var cmd   = new AppendCustomerAccountClaimCommand(user.Id, claim);

            CommandBus.Send(cmd);
        }
 protected void Send(params ICommand[] commands)
 {
     foreach (var command in commands)
     {
         command.Metadata.UserId = UserId;
     }
     CommandBus.Send(commands);
 }
Exemple #16
0
 private void OnEnemyEntityDestroyed(Guid enemyGuid, int score)
 {
     Manager.SignalBus.Fire(new EnemyDestroyedSignal(enemyGuid));
     if (score != 0)
     {
         _commandBus.Send(new ChangeGameScoreCommand(score));
     }
 }
        public void AddUser()
        {
            EventBus.Instance.SubscribeAll();


            CommandBus.Send(new EditUserCommand {
                UserName = "******", Email = "Test", UserID = 1
            });
        }
Exemple #18
0
        // GET: Dashboard
        public async Task <ActionResult> Index()
        {
            var cmd = new GetKetQuaXoSoCommand(0);
            await CommandBus.Send(cmd);

            ViewBag.Content = cmd.Response.ResponseObj;

            return(View());
        }
        public async Task gets_single_result()
        {
            await CommandBus.Send(new CreateFlightReservation("passenger", "local", "flight"));

            var result = await Repository.QueryMany(new SearchReservationsByFlight("flight"));

            result.Should().NotBeNull();
            result.Should().HaveCount(1);
            result.Single().Localizer.Should().Be("local");
        }
Exemple #20
0
        public async Task <long> Command([FromBody] CommandModel commandModel)
        {
            var type = _types.TypeFor(commandModel.Type);
            //log.LogInformation($"Processing command of type {typeName}.");
            var writeVersion = await _bus.Send(
                (Command)JsonConvert.DeserializeObject(commandModel.Command,
                                                       type));

            //log.LogInformation($"{typeName} processed successfully.");
            return(writeVersion);
        }
        public void ThrowCommandHandlersExceptionWhenHandlerThrowsException()
        {
            var handler1Mock = new Mock <ICommandHandler <CommandFake1> >();

            handler1Mock.Setup(x => x.Handle(It.IsAny <CommandFake1>())).Throws(new CommandHandlerException("Error"));

            var commandBus = new CommandBus();

            commandBus.RegisterHandler(handler1Mock.Object);

            Check.ThatCode(() => commandBus.Send(new CommandFake1())).Throws <CommandHandlerException>();
        }
        public override void Apply(IdentityUser user, UserPropertyChange change)
        {
            if (change == null || change.ChangeValue == null)
            {
                return;
            }

            var login = change.ChangeValue as UserLoginInfo;
            var cmd   = new AppendCustomerAccountSocialLoginCommand(user.Id, login.LoginProvider, login.ProviderKey);

            CommandBus.Send(cmd);
        }
Exemple #23
0
        public void when_sending_then_sets_command_id_as_messageid()
        {
            var sender = new MessageSenderMock();
            var sut    = new CommandBus(sender, Mock.Of <IMetadataProvider>(), new JsonTextSerializer());

            var command = new FooCommand {
                Id = Guid.NewGuid()
            };

            sut.Send(command);

            Assert.IsTrue(command.Id.ToString() == sender.Sent.Single().MessageId);
        }
        static void TestSendCommand()
        {
            TopicClient commandClient = TopicClient.CreateFromConnectionString(serviceBusConnectionString, commandTopicPath);
            TopicSender sender        = new TopicSender(commandClient);
            //sender.Send( () => { return new BrokeredMessage( "Hello CQRS" ); } );
            ITextSerializer serializer = new JsonTextSerializer();
            CommandBus      bus        = new CommandBus(sender, serializer);

            bus.Send(new Envelope <ICommand>(new PlaceOrder()
            {
                ProductId = 1, Quantity = 10
            }));
        }
Exemple #25
0
        public void when_specifying_delay_then_sets_in_message()
        {
            var sender = new MessageSenderMock();
            var sut    = new CommandBus(sender, Mock.Of <IMetadataProvider>(), new JsonTextSerializer());

            var command = new Envelope <ICommand>(new FooCommand {
                Id = Guid.NewGuid()
            })
            {
                Delay = TimeSpan.FromMinutes(15)
            };

            sut.Send(command);
            Assert.IsTrue(sender.Sent.Single().TimeToLive > TimeSpan.FromMinutes(14.9) && sender.Sent.Single().TimeToLive < TimeSpan.FromMinutes(15.1));
        }
        public void SendCommandToCorrectCommandHandler()
        {
            var handler1Mock = new Mock <ICommandHandler <CommandFake1> >();
            var handler2Mock = new Mock <ICommandHandler <CommandFake2> >();

            var commandBus = new CommandBus();

            commandBus.RegisterHandler(handler1Mock.Object);
            commandBus.RegisterHandler(handler2Mock.Object);

            commandBus.Send(new CommandFake1());

            handler1Mock.Verify(x => x.Handle(It.IsAny <CommandFake1>()), Times.Once);
            handler2Mock.Verify(x => x.Handle(It.IsAny <CommandFake2>()), Times.Never);
        }
 public void UserEvt()
 {
     CommandBus.RegisterAll();
     // 发布添加用户命令
     CommandBus.Send(new AddUserCommand {
         UserName = "******", Email = "*****@*****.**"
     });
     // 发布编辑用户命令
     CommandBus.Send(new EditUserCommand {
         UserName = "******", UserID = 1
     });
     // 发布刪除用户命令
     CommandBus.Send(new DelUserCommand {
         UserID = 1
     });
 }
Exemple #28
0
        public string AddTest()
        {
            CM_Account dataEntity = new CM_Account();

            dataEntity.AccountCode = "asdfsd";
            dataEntity.CreateTime  = DateTime.Now;

            AddAccountCommand cmd = new AddAccountCommand(dataEntity);

            CommandBus.Send <AddAccountCommand>(cmd);
            if (cmd.SimpleResult != null)
            {
                //  BusinessID = DataTypeConvert.ToInt32(cmd.SimpleResult.Message);
            }
            return("");
        }
Exemple #29
0
        public void when_specifying_delay_then_sets_in_message()
        {
            var sender = new MessageSenderMock();
            var sut    = new CommandBus(sender, Mock.Of <IMetadataProvider>(), new JsonTextSerializer());

            var command = new Envelope <ICommand>(new FooCommand {
                Id = Guid.NewGuid()
            })
            {
                Delay = TimeSpan.FromMinutes(15)
            };

            sut.Send(command);

            Assert.InRange(sender.Sent.Single().ScheduledEnqueueTimeUtc, DateTime.UtcNow.AddMinutes(14.9), DateTime.UtcNow.AddMinutes(15.1));
        }
Exemple #30
0
        public async Task <ActionResult> Login(EmailValidationRequest model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var cmd = new ValidateCustomerEmailCommand(0, model.Email);
            await CommandBus.Send(cmd);

            var isOk = cmd.Response.ResponseObj;

            if (!isOk)
            {
                ModelState.AddModelError("Account", cmd.Response.Message);
                return(View(model));
            }
            ViewBag.Email = model.Email;
            return(View("ValidateSuccess"));
        }