public void Should_publish_events() { var fakeCommand = new FakeCommand(); var fakeEvent = new FakeEvent(); var commandHandlerMock = new Mock <ICommandHandler <ICommand> >(); commandHandlerMock.Setup(x => x.Handle(fakeCommand)).Returns(new List <IDomainEvent> { fakeEvent }); var resolverMock = new Mock <IResolver>(); resolverMock.Setup(x => x.Resolve <ICommandHandler <ICommand> >()).Returns(commandHandlerMock.Object); var eventPublisherMock = new Mock <IEventPublisher>(); eventPublisherMock.Setup(x => x.Publish(fakeEvent)); var eventStoreMock = new Mock <IEventStore>(); var commandSender = new CommandSender(resolverMock.Object, eventPublisherMock.Object, eventStoreMock.Object); commandSender.Send <ICommand, IAggregateRoot>(fakeCommand); commandHandlerMock.Verify(x => x.Handle(fakeCommand), Times.Once); eventPublisherMock.Verify(x => x.Publish(It.IsAny <IDomainEvent>()), Times.Once); }
public void Send <TCommand>(TCommand command) where TCommand : ICommand <TAuthenticationToken> { Type commandType = typeof(TCommand); bool isRequired; if (!ConfigurationManager.TryGetSetting(string.Format("{0}.IsRequired", commandType.FullName), out isRequired)) { isRequired = true; } RouteHandlerDelegate commandHandler = Routes.GetSingleHandler(command, isRequired); // This check doesn't require an isRequired check as there will be an exception raised above and handled below. if (commandHandler == null) { Logger.LogDebug(string.Format("The command handler for '{0}' is not required.", commandType.FullName)); } else { Type senderType = commandHandler.TargetedType == null ? typeof(IConcurrentAkkaCommandSender <>).MakeGenericType(typeof(TAuthenticationToken)) : typeof(IConcurrentAkkaCommandSender <,>).MakeGenericType(typeof(TAuthenticationToken), commandHandler.TargetedType); var proxy = (IActorRef)ConcurrentEventBusProxy.Resolve(senderType, command.Id); proxy.Tell(command); } command.Framework = FrameworkType.Akka; CommandSender.Send(command); }
static void Main(string[] args) { var publisher = new EventPublisher(); var eventStore = new EventStore(publisher); var sender = new CommandSender(); var calendarDayRepo = new EventSourcedRepository <CalendarDayAggregate>(eventStore); sender.RegisterHandler(new CreateCalendarDayHandler(calendarDayRepo)); sender.RegisterHandler(new RequestAppointmentCommandHandler(calendarDayRepo)); // sender.Send(new CreateCalendarDayCommand(Day.Thursday)); //var read = new Read(publisher.Read()); var read2 = new Read2(publisher.Read()); var calendarDay = read2.GetFirstCalendarDayId(); //sender.Send(new RequestAppointmentCommand(calendarDay, 1, "one")); sender.Send(new RequestAppointmentCommand(calendarDay, 23, "pass")); //sender.Send(new RequestAppointmentCommand(calendarDay, 24, "fail")); read2.PrintFirstAppointmentBook(calendarDay); Console.ReadLine(); }
public void Should_throw_an_exception_when_command_is_null() { var resolverMock = new Mock <IResolver>(); var eventPublisherMock = new Mock <IEventPublisher>(); var eventStoreMock = new Mock <IEventStore>(); var commandSender = new CommandSender(resolverMock.Object, eventPublisherMock.Object, eventStoreMock.Object); Assert.Throws <ArgumentNullException>(() => commandSender.Send <ICommand, IAggregateRoot>(null)); }
public void Should_throw_an_exception_when_command_handler_is_not_found() { var resolverMock = new Mock <IResolver>(); var eventPublisherMock = new Mock <IEventPublisher>(); var eventStoreMock = new Mock <IEventStore>(); var commandSender = new CommandSender(resolverMock.Object, eventPublisherMock.Object, eventStoreMock.Object); Assert.Throws <Exception>(() => commandSender.Send <ICommand, IAggregateRoot>(new FakeCommand())); }
partial void OnCreate(IServiceRequestWithData <ISingleSignOnToken, InventoryItemServiceCreateParameters> serviceRequest, ref IServiceResponse results) { UnitOfWorkService.SetCommitter(this); InventoryItemServiceCreateParameters item = serviceRequest.Data; // The use of Guid.Empty is simply because we use ints as ids var command = new CreateInventoryItemCommand(Guid.Empty, item.name); CommandSender.Send(command); UnitOfWorkService.Commit(this); results = new ServiceResponse(); }
partial void OnRemove(IServiceRequestWithData <ISingleSignOnToken, InventoryItemServiceRemoveParameters> serviceRequest, ref IServiceResponse results) { UnitOfWorkService.SetCommitter(this); InventoryItemServiceRemoveParameters item = serviceRequest.Data; // The use of Guid.Empty is simply because we use ints as ids var command = new RemoveItemsFromInventoryCommand(item.rsn, item.count); CommandSender.Send(command); UnitOfWorkService.Commit(this); results = new ServiceResponse(); }
public void TestAddDataToLocalDbByCmmds() { foreach (var e in _entitiy1000) { _cmmdSender.Send(e); } _cmmdSender.Send(new CompleteEntity()); for (int i = 0; i < 100; i++) { if (!_cmmdReceiver.IsRuning) { break; } System.Threading.Thread.Sleep(100); } Assert.IsFalse(_cmmdReceiver.IsRuning); using var dbContext = new NetCoreSqliteDB.SqliteDBContext(_cmmdTolocalDbFilePath); var addedRowCount = dbContext.Table1.Count(); Assert.AreEqual(1000, addedRowCount); }
public void TestUpdateDataToLocalDbByCmmd() { foreach (var e in _entitiy1000) { _cmmdSender.Send(e); } _cmmdSender.Send(new CompleteEntity()); for (int i = 0; i < 100; i++) { if (!_cmmdReceiver.IsRuning) { break; } System.Threading.Thread.Sleep(100); } Assert.IsFalse(_cmmdReceiver.IsRuning); using var dbContext = new NetCoreSqliteDB.SqliteDBContext(_localDbFilePath); var updateedRowCount = (from e in dbContext.Table1 where e.P3 == "Edited" select e).Count(); Assert.AreEqual(1000, updateedRowCount); }
public IServiceResponseWithResultData <Entities.UserEntity> CreateUser(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.UserEntity> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); UnitOfWorkService.SetCommitter(this); Entities.UserEntity item = serviceRequest.Data; item.Rsn = Guid.NewGuid(); var command = new CreateUserCommand(item.Rsn, item.Name); OnCreateUser(serviceRequest, command); CommandSender.Send(command); OnCreatedUser(serviceRequest, command); UnitOfWorkService.Commit(this); return(CompleteResponse(new ServiceResponseWithResultData <Entities.UserEntity>(item))); }
public async Task SendsCommandToSendEndpoint() { var sendEndPoint = Substitute.For <ISendEndpoint>(); var sendEndpointProvider = Substitute.For <ISendEndpointProvider>(); sendEndpointProvider.GetSendEndpoint(Arg.Is(QueueName)).Returns(Task.FromResult(sendEndPoint)); var commandSendConfiguration = Substitute.For <ICommandSendConfiguration>(); commandSendConfiguration.QueueName.Returns(QueueName); _commandSender = new CommandSender(sendEndpointProvider, commandSendConfiguration); var testCommand = new TestCommand(); await _commandSender.Send(testCommand); await sendEndPoint.Received(1).Send(testCommand); }
/// <summary> /// Logically delete an existing instance of the <see cref="Entities.OrderEntity"/> /// </summary> public IServiceResponse DeleteOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); UnitOfWorkService.SetCommitter(this); Entities.OrderEntity item = serviceRequest.Data; var locatedItem = OrderRepository.Load(item.Rsn, false); if (locatedItem == null) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = ServiceResponseStateType.FailedValidation })); } if (locatedItem.IsLogicallyDeleted) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = ServiceResponseStateType.FailedValidation })); } var command = new DeleteOrderCommand(item.Rsn); ServiceResponseStateType?serviceResponseStateType = null; OnDeleteOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType); if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = serviceResponseStateType.Value })); } CommandSender.Send(command); OnDeletedOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType); if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = serviceResponseStateType.Value })); } UnitOfWorkService.Commit(this); return(CompleteResponse(new ServiceResponse())); }
public void Send <TCommand>(TCommand command) where TCommand : ICommand <TAuthenticationToken> { RouteHandlerDelegate commandHandler; if (!PrepareAndValidateCommand(command, out commandHandler)) { return; } // This could be null if Akka won't handle the command and something else will. if (commandHandler != null) { commandHandler.Delegate(command); } // Let everything else know about the command (usually double handling a command is bad... but sometimes it might be useful... like pushing from AWS to Azure so both systems handle it... although an event really is the proper pattern to use here. CommandSender.Send(command); }
public void Send <TCommand>(TCommand command) where TCommand : ICommand <TAuthenticationToken> { RouteHandlerDelegate commandHandler; if (!PrepareAndValidateCommand(command, out commandHandler)) { return; } Type senderType = commandHandler.TargetedType == null ? typeof(IConcurrentAkkaCommandSender <>).MakeGenericType(typeof(TAuthenticationToken)) : typeof(IConcurrentAkkaCommandSender <,>).MakeGenericType(typeof(TAuthenticationToken), commandHandler.TargetedType); var proxy = (IActorRef)ConcurrentEventBusProxy.Resolve(senderType, command.Id); proxy.Tell(command); CommandSender.Send(command); }
private void Work() { var sender = new CommandSender(); while (!_stopBot) { List <ManagerClientCommand> localPendingCommands = null; lock (PendingCommands) { localPendingCommands = PendingCommands; PendingCommands = new List <ManagerClientCommand>(); } var tasks = new List <Task <bool> >(); foreach (var command in localPendingCommands) { var task = sender.Send(command.IPAddress, TCP_PORT, command.Command, true); } Task <bool> .WaitAll(tasks.ToArray()); } }
/// <summary> /// Create a new instance of the <see cref="Entities.OrderEntity"/> /// </summary> public IServiceResponseWithResultData <Entities.OrderEntity> CreateOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); UnitOfWorkService.SetCommitter(this); Entities.OrderEntity item = serviceRequest.Data; if (item.Rsn == Guid.Empty) { item.Rsn = Guid.NewGuid(); } var command = new CreateOrderCommand(item.Rsn, item.OrderId, item.CustomerId, item.EmployeeId, item.OrderDate, item.RequiredDate, item.ShippedDate, item.ShipViaId, item.Freight, item.ShipName, item.ShipAddress, item.ShipCity, item.ShipRegion, item.ShipPostalCode, item.ShipCountry); OnCreateOrder(serviceRequest, command); CommandSender.Send(command); OnCreatedOrder(serviceRequest, command); UnitOfWorkService.Commit(this); return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity>(item))); }
/// <summary> /// Update an existing instance of the <see cref="Entities.OrderEntity"/> /// </summary> public IServiceResponseWithResultData <Entities.OrderEntity> UpdateOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest) { AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); UnitOfWorkService.SetCommitter(this); Entities.OrderEntity item = serviceRequest.Data; var locatedItem = OrderRepository.Load(item.Rsn); if (locatedItem == null) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = ServiceResponseStateType.FailedValidation })); } var command = new UpdateOrderCommand(item.Rsn, item.OrderId, item.CustomerId, item.EmployeeId, item.OrderDate, item.RequiredDate, item.ShippedDate, item.ShipViaId, item.Freight, item.ShipName, item.ShipAddress, item.ShipCity, item.ShipRegion, item.ShipPostalCode, item.ShipCountry); ServiceResponseStateType?serviceResponseStateType = null; OnUpdateOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType); if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = serviceResponseStateType.Value })); } CommandSender.Send(command); OnUpdatedOrder(serviceRequest, ref command, locatedItem, ref serviceResponseStateType); if (serviceResponseStateType != null && serviceResponseStateType != ServiceResponseStateType.Succeeded) { return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity> { State = serviceResponseStateType.Value })); } UnitOfWorkService.Commit(this); return(CompleteResponse(new ServiceResponseWithResultData <Entities.OrderEntity>(item))); }
/// <summary> /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired. /// </summary> /// <param name="command">The <typeparamref name="TCommand"/> to send.</param> /// <param name="condition">A delegate to be executed over and over until it returns the <typeparamref name="TEvent"/> that is desired, return null to keep trying.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="F:System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param> /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param> public TEvent SendAndWait <TCommand, TEvent>(TCommand command, Func <IEnumerable <IEvent <TAuthenticationToken> >, TEvent> condition, int millisecondsTimeout, IEventReceiver <TAuthenticationToken> eventReceiver = null) where TCommand : ICommand <TAuthenticationToken> { if (eventReceiver != null) { throw new NotSupportedException("Specifying a different event receiver is not yet supported."); } RouteHandlerDelegate commandHandler; if (!PrepareAndValidateCommand(command, out commandHandler)) { return((TEvent)(object)null); } TEvent result = (TEvent)(object)null; EventWaits.Add(command.CorrelationId, new List <IEvent <TAuthenticationToken> >()); Type senderType = commandHandler.TargetedType == null ? typeof(IConcurrentAkkaCommandSender <>).MakeGenericType(typeof(TAuthenticationToken)) : typeof(IConcurrentAkkaCommandSender <,>).MakeGenericType(typeof(TAuthenticationToken), commandHandler.TargetedType); var proxy = (IActorRef)ConcurrentEventBusProxy.Resolve(senderType, command.Id); proxy.Tell(command); CommandSender.Send(command); SpinWait.SpinUntil(() => { IList <IEvent <TAuthenticationToken> > events = EventWaits[command.CorrelationId]; result = condition(events); return(result != null); }, millisecondsTimeout); return(result); }
public void Send <T>(T command) where T : Command { _sender.Send(command); }