コード例 #1
0
        public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> request,
                                             RequestHandlerDelegate <TResponse> next)
        {
            await Task.Delay(_options.Delay);

            return(await next());
        }
コード例 #2
0
        public void PipeOrderIsPreserved()
        {
            Module
            .RevealFor <object>()
            .Pipe(next =>
                  (e, ct) =>
            {
                Assert.Equal(1, GetStep(e.Metadata));
                return(next(e.SetMetadata(SetStep(e.Metadata, 2)), ct));
            })
            .Pipe(next =>
                  (e, ct) =>
            {
                Assert.Equal(2, GetStep(e.Metadata));
                return(next(e.SetMetadata(SetStep(e.Metadata, 3)), ct));
            })
            .Handle(
                (e, ct) =>
            {
                Assert.Equal(3, GetStep(e.Metadata));
                return(Task.CompletedTask);
            });

            var envelope = new CommandEnvelope()
                           .SetCommand(new object())
                           .SetMetadata(Metadata.None.With(new Metadatum("step", "1")));

            new CommandHandlerInvoker(Module).Invoke(envelope);
        }
コード例 #3
0
        public static void OnCreateOrderCommand(
            [ServiceBusTrigger("commands")] CommandEnvelope <CreateOrder> envelope,
            TextWriter log)
        {
            var command    = envelope.Command as CreateOrder;
            var repository = Container.Resolve <IRepository <CommandingOrder, Guid> >();
            var client     = Container.Resolve <ICommandHandler>();

            var order  = repository.GetById(command.CommandId);
            var events = new List <EventEnvelope <OrderCreated> >();

            order.Event += (s, e) =>
            {
                if (e is OrderCreated)
                {
                    events.Add(new EventEnvelope <OrderCreated>
                    {
                        Event = (OrderCreated)e
                        ,
                        Timestamp = DateTime.UtcNow
                        ,
                        Username = envelope.Username
                    });
                }
            };
            order.Apply(command);
            repository.Set(order);
            client.Handle(events.ToArray());
        }
コード例 #4
0
        public async Task <Unit> Handle(CommandEnvelope <JoinRoomCommand, Unit> message)
        {
            var context = message.Context;
            var command = message.Command;
            await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            return(Unit.Value);
        }
コード例 #5
0
        public async Task <IRoomData> Handle(CommandEnvelope <GetRoomStateCommand, IRoomData> message)
        {
            var context = message.Context;
            var command = message.Command;
            var player  = await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            return(await player.GetState());
        }
コード例 #6
0
            public void CanSerializeToBson()
            {
                var aggregateId = Guid.Parse("61296B2F-F040-472D-95DF-B1C3A32A7C7E");
                var envelope    = new CommandEnvelope(aggregateId, new FakeCommand("My Command"));
                var bson        = WriteBson(envelope);

                Validate(bson, "vQAAAAVhABAAAAAEL2spYUDwLUeV37HDoyp8fgNjAJ0AAAACJHR5cGUAdAAAAFRlc3QuU3BhcmsuU2VyaWFsaXphdGlvbi5Db252ZXJ0ZXJzLlVzaW5nQ29tbWFuZEVudmVsb3BlQ29udmVydGVyLkZha2VDb21tYW5kLCBTcGFyay5TZXJpYWxpemF0aW9uLk5ld3RvbnNvZnQuVGVzdHMAAlByb3BlcnR5AAsAAABNeSBDb21tYW5kAAAA");
            }
コード例 #7
0
        public Task PostScheduled(CommandEnvelope envelope, IObserver<LogEntry> log)
        {
            var req = CreatePostCommandRequest(envelope);
            return _client.PostScheduled(req)
                .ContinueWith(x =>
                {
                    var resp = x.Result;
                    var id = resp.Id;

                    Action<string> traceStatus = m => log.OnNext(new LogEntry
                    {
                        Message = m,
                        Severity = LogEntrySeverity.Trace,
                        Timestamp = DateTime.Now
                    });

                    traceStatus("Start waiting for execution command " + id);

                    var token = DateTime.MinValue;

                    while (true)
                    {
                        var resp2 = _client.GetScheduled(id, token);

                        // Write user log
                        var serverLog = resp2.Log.OrEmpty().ToList();
                        foreach (var entry in serverLog)
                        {
                            log.OnNext(entry);
                        }

                        // Take maximum available timestamp
                        token = serverLog.Select(xx => xx.Timestamp).Union(new[] { token }).Max();

                        switch (resp2.Status)
                        {
                            case ScheduledCommandStatus.Pending:
                                traceStatus("Command(" + id + ") is still pending.");
                                break;

                            case ScheduledCommandStatus.InProgress:
                                traceStatus("Command(" + id + ") is in progress.");
                                break;

                            case ScheduledCommandStatus.Success:
                                traceStatus("Command(" + id + ") completed success.");
                                return;

                            case ScheduledCommandStatus.Failure:
                                traceStatus("Command(" + id + ") failed.");
                                return;
                        }

                        Thread.Sleep(300);
                    }
                });
        }
コード例 #8
0
        public async Task <Unit> Handle(CommandEnvelope <LaunchFleetCommand, Unit> message)
        {
            var context = message.Context;
            var command = message.Command;
            var player  = await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            await player.LaunchFleet(command.Fleet);

            return(Unit.Value);
        }
コード例 #9
0
        public async Task <Unit> Handle(CommandEnvelope <UpdateGameOptionsCommand, Unit> message)
        {
            var context = message.Context;
            var command = message.Command;
            var player  = await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            await player.UpdateGameOptions(command.Options);

            return(Unit.Value);
        }
コード例 #10
0
        public async Task <Unit> Handle(CommandEnvelope <CancelFleetCommand, Unit> message)
        {
            var command = message.Command;
            var context = message.Context;
            var player  = await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            var cancelation = _mapper.Map <CancelFleetCommand, FleetCancelationData>(command);
            await player.CancelFleet(cancelation);

            return(Unit.Value);
        }
コード例 #11
0
        public void NewReturnsExpectedInstance()
        {
            var sut = new CommandEnvelope();

            Assert.Null(sut.Command);
            Assert.Equal(Guid.Empty, sut.CommandId);
            Assert.Equal(Guid.Empty, sut.CorrelationId);
            Assert.Null(sut.SourceId);
            Assert.Null(sut.Principal);
            Assert.Same(ReactiveDomain.Metadata.None, sut.Metadata);
        }
コード例 #12
0
        public async Task <Unit> Handle(CommandEnvelope <SendMessageCommand, Unit> message)
        {
            var context = message.Context;
            var command = message.Command;
            var player  = await context.User.JoinRoom(command.RoomId, context.Connection.Id);

            var textMessage = _mapper.Map <SendMessageCommand, TextMessageData>(command);
            await player.SendMessage(textMessage);

            return(Unit.Value);
        }
コード例 #13
0
        public Task ContinueWith(CommandEnvelope command)
        {
            var commandType = command.GetType();
            var useCase     = _useCases.FirstOrDefault(uc => uc.CanTell(command.Payload));

            if (null == useCase)
            {
                throw new NoStoryException(command.Payload.GetType().Name);
            }
            return(useCase.Tell(command));
        }
コード例 #14
0
        public void SetMetadataReturnsExpectedInstance()
        {
            var sut = new CommandEnvelope().SetMetadata(Metadata);

            Assert.Same(Metadata, sut.Metadata);

            Assert.Null(sut.Command);
            Assert.Equal(Guid.Empty, sut.CommandId);
            Assert.Equal(Guid.Empty, sut.CorrelationId);
            Assert.Null(sut.Principal);
            Assert.Null(sut.SourceId);
        }
コード例 #15
0
ファイル: FileClient.cs プロジェクト: greydmar/InEngine.NET
        void PublishToQueue(CommandEnvelope commandEnvelope, string queuePath)
        {
            if (!Directory.Exists(queuePath))
            {
                Directory.CreateDirectory(queuePath);
            }

            File.WriteAllText(
                Path.Combine(queuePath, Guid.NewGuid().ToString()),
                commandEnvelope.SerializeToJson()
                );
        }
コード例 #16
0
ファイル: LoginHandler.cs プロジェクト: smolyakoff/conreign
        public async Task <LoginCommandResponse> Handle(CommandEnvelope <LoginCommand, LoginCommandResponse> message)
        {
            var context = message.Context;
            var command = message.Command;
            var result  = await context.Connection.Login(command.AccessToken);

            var response = new LoginCommandResponse {
                AccessToken = result.AccessToken
            };

            return(response);
        }
コード例 #17
0
        public void TypedAsThrowsIfCommandIsNotAssignableToType()
        {
            var sut = new CommandEnvelope()
                      .SetCommand(Command)
                      .SetCommandId(CommandId)
                      .SetCorrelationId(CorrelationId)
                      .SetSourceId(SourceId)
                      .SetMetadata(Metadata)
                      .SetPrincipal(Principal);

            Assert.Throws <InvalidCastException>(() => sut.TypedAs <Message>());
        }
コード例 #18
0
        public Task<string> PostAsync(CommandEnvelope envelope)
        {
            var req = CreatePostCommandRequest(envelope);
            return _client.Post(req)
                .ContinueWith(x =>
                {
                    if (!x.Result.IsSuccessStatusCode)
                        throw new ZazTransportException("An error occurred while sending request.", x.Result);

                    var log = x.Result.Content.ReadAsStringAsync().Result;
                    return log;
                });
        }
コード例 #19
0
            public void DoNotSaveAggregateOnSuccessIfNoEventsRaised()
            {
                var aggregate      = new FakeAggregate();
                var envelope       = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { });

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                    commandHandler.Handle(context);

                AggregateStore.Verify(mock => mock.Save(aggregate, It.IsAny <CommandContext>()), Times.Never);
            }
コード例 #20
0
ファイル: AdvancedCommandBus.cs プロジェクト: wortexx/zaz
 public Task Post(CommandEnvelope envelope)
 {
     var req = CreatePostCommandRequest(envelope);
     return _client.Post(req)
         .ContinueWith(x =>
         {
             if (!x.Result.IsSuccessStatusCode)
             {
                 throw new InvalidOperationException("Command was not successfully posted. Server response: "
                     + x.Result.ReasonPhrase);
             }
             return;
         });
 }
コード例 #21
0
            public void RetrieveCommandHandlerBasedOnCommandType()
            {
                var command   = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope  = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message   = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);

                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { }));
                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                Processor.Process(message);

                HandlerRegistry.Verify(mock => mock.GetHandlerFor(command), Times.Once());
            }
コード例 #22
0
            public void RetrieveCommandHandlerBasedOnCommandType()
            {
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);

                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { }));
                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                Processor.Process(message);

                HandlerRegistry.Verify(mock => mock.GetHandlerFor(command), Times.Once());
            }
コード例 #23
0
            public void CanSerializeToJson()
            {
                var aggregateId = Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb");
                var envelope    = new CommandEnvelope(aggregateId, new FakeCommand("My Command"));
                var json        = WriteJson(envelope);

                Validate(json, @"
{
  ""a"": ""a6c45a28-c572-4d5b-ac18-7b0ec2d723fb"",
  ""c"": {
    ""$type"": ""Test.Spark.Serialization.Converters.UsingCommandEnvelopeConverter.FakeCommand, Spark.Serialization.Newtonsoft.Tests"",
    ""Property"": ""My Command""
  }
}");
            }
コード例 #24
0
            public void CanSerializeToJson()
            {
                var aggregateId = Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb");
                var envelope = new CommandEnvelope(aggregateId, new FakeCommand("My Command"));
                var json = WriteJson(envelope);

                Validate(json, @"
                {
                  ""a"": ""a6c45a28-c572-4d5b-ac18-7b0ec2d723fb"",
                  ""c"": {
                ""$type"": ""Test.Spark.Serialization.Converters.UsingCommandEnvelopeConverter.FakeCommand, Spark.Serialization.Newtonsoft.Tests"",
                ""Property"": ""My Command""
                  }
                }");
            }
コード例 #25
0
            public void VerifyInitializedIfExplictCreateRequired()
            {
                var aggregate      = new FakeAggregate(explicitCreateRequired: true, version: 0);
                var envelope       = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    var ex = Assert.Throws <InvalidOperationException>(() => commandHandler.Handle(context));

                    Assert.Equal(Exceptions.AggregateNotInitialized.FormatWith(typeof(FakeAggregate), Guid.Empty), ex.Message);
                }
            }
コード例 #26
0
            public void DoNotVerifyInitializedIfImplicitCreateAllowed()
            {
                var aggregate      = new FakeAggregate(explicitCreateRequired: false, version: 0);
                var envelope       = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    commandHandler.Handle(context);

                    Assert.True(aggregate.Handled);
                }
            }
コード例 #27
0
        public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message,
                                             RequestHandlerDelegate <TResponse> next)
        {
            var context = message.Context;

            if (_skipAuthentication)
            {
                return(await next.Invoke());
            }
            var loginResult = await context.Connection.Authenticate(context.Metadata.AccessToken);

            context.UserId = loginResult.UserId;
            context.User   = loginResult.User;
            return(await next.Invoke());
        }
コード例 #28
0
        public static async Task <long?> Handle <S, C>(CommandEnvelope <C> commandEnvelope, IAggregate <S> aggregate, IEventStore eventStore, CancellationToken cancel = default) where C : class where S : class
        {
            if (commandEnvelope.AggregateId == null || commandEnvelope.Command == null)
            {
                throw new Exception();
            }

            var streamName = aggregate.GetStreamName(commandEnvelope.AggregateId);

            var(version, state) = await Load(streamName, aggregate, eventStore, cancel);

            var events = aggregate.Handle(state, commandEnvelope.Command)
                         .Select((e, i) => e.CreateEventEnvelope(commandEnvelope.AggregateId, version + i + 1))
                         .ToArray();

            return(await eventStore.Save(streamName, cancel, events));
        }
コード例 #29
0
            public void WillTimeoutEventuallyIfCannotSave()
            {
                var command   = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope  = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message   = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);
                var processor = new CommandProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new CommandProcessorSettings {
                    RetryTimeout = TimeSpan.FromMilliseconds(20)
                });

                SystemTime.ClearOverride();

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);
                AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny <CommandContext>())).Callback(() => { throw new ConcurrencyException(); });
                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)));

                Assert.Throws <TimeoutException>(() => processor.Process(message));
            }
コード例 #30
0
        private BasketModel CommitCommand(CommandEnvelope <Command> cmd)
        {
            var list = new List <CommandEnvelope <Command> > {
                cmd
            };
            var res = CommandHandler.handler.Invoke(cmd);

            if (res.IsOk)
            {
                return(GetBasketAggregate(cmd.AggregateId.Item));
            }

            var f = (res as Result <FSharpList <EventEnvelope <Event> >, IError> .Bad).Item;

            var reasons = f.Select(x => x.ToString()).ToArray();
            var reason  = string.Join("; ", reasons);

            throw new Exception(reason);
        }
コード例 #31
0
        private void QueueCommand(CommandEnvelope <Command> cmd)
        {
            var list = new List <Tuple <QueueName, CommandEnvelope <Command> > > {
                Tuple.Create(QueueName.NewQueueName("Order"), cmd)
            };
            var res = PinetreeCQRS.Persistence.SqlServer.Commands.queueCommands(ListModule.OfSeq(list));

            if (res.IsOk)
            {
                return;
            }

            var f = (res as Result <FSharpList <CommandEnvelope <Command> >, IError> .Bad).Item;

            var reasons = f.Select(x => x.ToString()).ToArray();
            var reason  = string.Join("; ", reasons);

            throw new Exception(reason);
        }
コード例 #32
0
        public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message,
                                             RequestHandlerDelegate <TResponse> next)
        {
            var context = message.Context;

            try
            {
                return(await next.Invoke());
            }
            catch (Exception ex)
            {
                _counter.Increment();
                var level = ex is UserException ? LogEventLevel.Warning : LogEventLevel.Error;
                _logger.Write(level, ex, "[{TraceId}-{UserId}] {Message}",
                              context.Metadata.TraceId,
                              context.UserId == null ? "Anonymous" : context.UserId.ToString(),
                              ex.Message);
                throw;
            }
        }
コード例 #33
0
        private async Task TellAndSaveWithoutLoading <TCommand>(
            CommandEnvelope command,
            Func <TCommand, AggregateState <TState> .Transition> update)
        {
            // _log.Debug("Processing command {command}", command);
            var transition = update((TCommand)command.Payload);
            var uow        = UnitOfWork <TState> .For(command.ChainInfo.MessageId
                                                      , command.ChainInfo.CorrelationId
                                                      , command.ChainInfo.CausationId
                                                      , InitializeState(transition.State.Id));

            // var state = uow.State;
            var transaction = uow.Track(transition.Events, transition.State);

            var finalVersion    = transition.State.Version;
            var originlVersion  = finalVersion - transition.Events.Count();
            var expectedVersion = originlVersion;

            await _repository.Save(transaction, expectedVersion);
        }
コード例 #34
0
        public void TypedAsDoesNotThrowIfCommandIsAssignableToType()
        {
            var message = new Message();
            var sut     = new CommandEnvelope()
                          .SetCommand(message)
                          .SetCommandId(CommandId)
                          .SetCorrelationId(CorrelationId)
                          .SetSourceId(SourceId)
                          .SetMetadata(Metadata)
                          .SetPrincipal(Principal);

            var result = sut.TypedAs <object>();

            Assert.IsType <CommandEnvelope <object> >(result);
            Assert.Same(message, result.Command);
            Assert.Equal(CommandId, result.CommandId);
            Assert.Equal(CorrelationId, result.CorrelationId);
            Assert.Equal(SourceId, result.SourceId);
            Assert.Same(Metadata, result.Metadata);
            Assert.Same(Principal, result.Principal);
        }
コード例 #35
0
        public void TypedAsReturnsExpectedInstance()
        {
            var message = new Message();
            var sut     = new CommandEnvelope()
                          .SetCommand(message)
                          .SetCommandId(CommandId)
                          .SetCorrelationId(CorrelationId)
                          .SetSourceId(SourceId)
                          .SetMetadata(Metadata)
                          .SetPrincipal(Principal);

            var result = sut.TypedAs <Message>();

            Assert.IsType <CommandEnvelope <Message> >(result);
            Assert.Same(message, result.Command);
            Assert.Equal(CommandId, result.CommandId);
            Assert.Equal(CorrelationId, result.CorrelationId);
            Assert.Equal(SourceId, result.SourceId);
            Assert.Same(Metadata, result.Metadata);
            Assert.Same(Principal, result.Principal);
        }
コード例 #36
0
            public void ReloadAggregateOnConcurrencyException()
            {
                var save = 0;
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);
                var ex = new ConcurrencyException();

                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)));
                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);
                AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() =>
                {
                    if (++save == 1)
                        throw ex;
                });

                Processor.Process(message);

                AggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId), Times.Exactly(2));
            }
コード例 #37
0
ファイル: AdvancedCommandBus.cs プロジェクト: wortexx/zaz
        public Task PostScheduled(CommandEnvelope envelope)
        {
            var req = CreatePostCommandRequest(envelope);
            return _client.PostScheduled(req)
                .ContinueWith(x =>
                {
                    var resp = x.Result;
                    var id = resp.Id;

                    WriteTrace("Start waiting for execution command " + id);

                    while (true)
                    {
                        Thread.Sleep(300);

                        var resp2 = _client.GetScheduled(id);

                        switch (resp2.Status)
                        {
                            case ScheduledCommandStatus.Pending:
                                WriteTrace("Command(" + id + ") is still pending.");
                                break;

                            case ScheduledCommandStatus.InProgress:
                                WriteTrace("Command(" + id + ") is in progress.");
                                break;

                            case ScheduledCommandStatus.Success:
                                WriteTrace("Command(" + id + ") completed success.");
                                return;

                            case ScheduledCommandStatus.Failure:
                                WriteTrace("Command(" + id + ") failed.");
                                return;
                        }

                    }
                });
        }
コード例 #38
0
            public void DoNotSaveAggregateOnSuccessIfNoEventsRaised()
            {
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => { });

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                    commandHandler.Handle(context);

                AggregateStore.Verify(mock => mock.Save(aggregate, It.IsAny<CommandContext>()), Times.Never);
            }
コード例 #39
0
            public void CanSerializeToBson()
            {
                var aggregateId = Guid.Parse("61296B2F-F040-472D-95DF-B1C3A32A7C7E");
                var envelope = new CommandEnvelope(aggregateId, new FakeCommand("My Command"));
                var bson = WriteBson(envelope);

                Validate(bson, "vQAAAAVhABAAAAAEL2spYUDwLUeV37HDoyp8fgNjAJ0AAAACJHR5cGUAdAAAAFRlc3QuU3BhcmsuU2VyaWFsaXphdGlvbi5Db252ZXJ0ZXJzLlVzaW5nQ29tbWFuZEVudmVsb3BlQ29udmVydGVyLkZha2VDb21tYW5kLCBTcGFyay5TZXJpYWxpemF0aW9uLk5ld3RvbnNvZnQuVGVzdHMAAlByb3BlcnR5AAsAAABNeSBDb21tYW5kAAAA");
            }
コード例 #40
0
 public static TranslationResult Ok(CommandEnvelope command)
 {
     return new TranslationResult(command, TranslationResultType.Ok, null);
 }
コード例 #41
0
            public void WillTimeoutEventuallyIfCannotSave()
            {
                var command = new FakeCommand();
                var aggregate = new FakeAggregate();
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), command);
                var message = Message.Create(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope);
                var processor = new CommandProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new CommandProcessorSettings { RetryTimeout = TimeSpan.FromMilliseconds(20) });

                SystemTime.ClearOverride();

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);
                AggregateStore.Setup(mock => mock.Save(aggregate, It.IsAny<CommandContext>())).Callback(() => { throw new ConcurrencyException(); });
                HandlerRegistry.Setup(mock => mock.GetHandlerFor(command)).Returns(new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c)));

                Assert.Throws<TimeoutException>(() => processor.Process(message));
            }
コード例 #42
0
            public void DoNotVerifyInitializedIfImplicitCreateAllowed()
            {
                var aggregate = new FakeAggregate(explicitCreateRequired: false, version: 0);
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    commandHandler.Handle(context);

                    Assert.True(aggregate.Handled);
                }
            }
コード例 #43
0
 private TranslationResult(CommandEnvelope commandEnvelope, TranslationResultType type, string suggestedVersion)
 {
     Type = type;
     CommandEnvelope = commandEnvelope;
     SuggestedVersion = suggestedVersion;
 }
コード例 #44
0
 private static PostCommandRequest CreatePostCommandRequest(CommandEnvelope envelope)
 {
     return new PostCommandRequest
     {
         Command = envelope.Command,
         Key = envelope.Key,
         Tags = envelope.Tags
     };
 }
コード例 #45
0
 public static TranslationResult NewVersionSuggested(CommandEnvelope command, string suggestedVersion)
 {
     return new TranslationResult(command, TranslationResultType.NewVersionSuggested, suggestedVersion);
 }
コード例 #46
0
            public void VerifyInitializedIfExplictCreateRequired()
            {
                var aggregate = new FakeAggregate(explicitCreateRequired: true, version: 0);
                var envelope = new CommandEnvelope(GuidStrategy.NewGuid(), new FakeCommand());
                var commandHandler = new CommandHandler(typeof(FakeAggregate), typeof(FakeCommand), AggregateStore.Object, (a, c) => ((FakeAggregate)a).Handle((FakeCommand)c));

                AggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), envelope.AggregateId)).Returns(aggregate);

                using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, envelope))
                {
                    var ex = Assert.Throws<InvalidOperationException>(() => commandHandler.Handle(context));

                    Assert.Equal(Exceptions.AggregateNotInitialized.FormatWith(typeof(FakeAggregate), Guid.Empty), ex.Message);
                }
            }