Esempio n. 1
0
        public async Task CanDepositCashInToValidAccount()
        {
            decimal  depositeAmount = 5000;
            DateTime depositeDate   = System.DateTime.Now;
            var      accountCreated = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId         = _accountId,
                AccountHolderName = "Tushar"
            };
            var cmd = new DepositCash
            {
                AccountId     = _accountId,
                DepositAmount = depositeAmount
            };

            var ev = new CashDeposited(cmd)
            {
                AccountId     = _accountId,
                DepositAmount = depositeAmount
            };

            await _runner.Run(
                def => def.Given(accountCreated).When(cmd).Then(ev)
                );
        }
Esempio n. 2
0
        public when_using_listener_start_with_aggregate_and_guid(StreamStoreConnectionFixture fixture)
        {
            var conn = fixture.Connection;

            conn.Connect();

            // Build an origin stream to which the the events are appended. We are testing this stream directly
            var originalStreamGuid = Guid.NewGuid();
            var originStreamName   = _streamNameBuilder.GenerateForAggregate(typeof(AggregateIdTestAggregate), originalStreamGuid);


            // Drop an event into the stream testAggregate-guid
            var result = conn.AppendToStream(
                originStreamName,
                ExpectedVersion.NoStream,
                null,
                _eventSerializer.Serialize(new TestEvent(CorrelatedMessage.NewRoot())));

            Assert.True(result.NextExpectedVersion == 0);

            // Wait for the stream to be written
            CommonHelpers.WaitForStream(conn, originStreamName);

            StreamListener listener = new SynchronizableStreamListener(
                "guidStream",
                conn,
                _streamNameBuilder,
                _eventSerializer);

            listener.EventStream.Subscribe(new AdHocHandler <Event>(Handle));

            // This will start listening on the TestAggregate-guid stream.
            listener.Start <AggregateIdTestAggregate>(originalStreamGuid);
        }
Esempio n. 3
0
        public void WireTransferCash(Guid id, double amount, IClock clock, CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new InvalidOperationException("Wire transfer Cash's amount must be strictly positive");
            }

            if (_blocked)
            {
                throw new InvalidOperationException("Account is blocked");
            }

            if (_dailyWireTransferAmount + amount > _dailyWireTransferLimit)
            {
                Raise(new AccountBlocked(source)
                {
                    AccountId = Id,
                    Raison    = "_dailyWireTransferLimit attempted"
                });
            }

            var wiretransferTime = clock.GetCurrentInstant();

            Raise(new CashWireTransfered(source)
            {
                AccountId        = Id,
                Amount           = amount,
                WireTransferedAt = wiretransferTime
            });
        }
Esempio n. 4
0
        public void DepositCheque(Guid chequeId, double amount, IClock clock, CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new InvalidOperationException("Cheque's amount must be strictly positive");
            }

            var depositTime = clock.GetCurrentInstant();

            Instant clearanceTime = depositTime;

            switch (clearanceTime.InUtc().DayOfWeek)
            {
            case IsoDayOfWeek.Saturday:
                clearanceTime.Plus(Duration.FromDays(2));
                break;

            case IsoDayOfWeek.Sunday:
                clearanceTime.Plus(Duration.FromDays(1));
                break;
            }

            Raise(new ChequeDeposited(source)
            {
                AccountId     = Id,
                ChequeId      = chequeId,
                Amount        = amount,
                DepositTime   = depositTime,
                ClearanceTime = clearanceTime
            });
        }
 public CorrelatedAggregate(
     Guid id,
     CorrelatedMessage source) : this()
 {
     Source = source; //n.b. source is a transient value used to set the context for the events
     Raise(new Created(id, source.CorrelationId, new SourceId(source)));
 }
Esempio n. 6
0
        public void WithdrawCash(Guid id, double amount, IClock clock, CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new InvalidOperationException("Withdrawn Cash's amount must be strictly positive");
            }

            if (_blocked)
            {
                throw new InvalidOperationException("Account is blocked");
            }

            if (amount > _balance + _overdraftLimit)
            {
                Raise(new AccountBlocked(source)
                {
                    AccountId = Id,
                    Raison    = "amount > _balance + _overdraftLimit"
                });
            }

            var withdrawnTime = clock.GetCurrentInstant();

            Raise(new CashWithdrawn(source)
            {
                AccountId   = Id,
                Amount      = amount,
                WithdrawnAt = withdrawnTime
            });
        }
Esempio n. 7
0
        public void can_serialize_json_success_commandresponse()
        {
            var cmd      = new TestCommands.TypedResponse(false, CorrelatedMessage.NewRoot());
            var nearSide = cmd.Succeed(15);

            TestCommands.TestResponse farSide;


            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                var serializer = JsonSerializer.Create(Json.JsonSettings);
                serializer.Serialize(writer, nearSide);
            }

            using (var reader = new JsonTextReader(new StringReader(sb.ToString())))
            {
                var serializer = JsonSerializer.Create(Json.JsonSettings);
                serializer.SerializationBinder = new TestDeserializer();
                serializer.ContractResolver    = new TestContractResolver();
                farSide = serializer.Deserialize <TestCommands.TestResponse>(reader);
            }

            Assert.Equal(nearSide.MsgId, farSide.MsgId);
            Assert.Equal(nearSide.GetType(), farSide.GetType());
            Assert.Equal(nearSide.CorrelationId, farSide.CorrelationId);
            Assert.Equal(nearSide.CommandType, farSide.CommandType);
            Assert.Equal(nearSide.CommandId, farSide.CommandId);
            Assert.Equal(nearSide.SourceId, farSide.SourceId);

            Assert.Equal(nearSide.Data, farSide.Data);
        }
Esempio n. 8
0
 public void can_resubscribe_handler()
 {
     lock (_fixture) {
         AssertEx.IsOrBecomesTrue(() => _fixture.Bus.Idle);
         _fixture.ClearCounters();
         //no subscription
         Assert.False(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
         //Add subscription
         var subscription = _fixture.Bus.Subscribe <TestCommands.Command3>(_fixture);
         Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
         _fixture.Bus.Send(new TestCommands.Command3(CorrelatedMessage.NewRoot()));
         AssertEx.IsOrBecomesTrue(
             () => Interlocked.Read(ref _fixture.GotTestCommand3) == 1,
             msg: "Expected command handled once, got" + Interlocked.Read(ref _fixture.GotTestCommand3));
         //dispose subscription to unsubscribe
         subscription.Dispose();
         Assert.False(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
         Assert.Throws <CommandNotHandledException>(() =>
                                                    _fixture.Bus.Send(new TestCommands.Command3(CorrelatedMessage.NewRoot())));
         //resubscribe
         subscription = _fixture.Bus.Subscribe <TestCommands.Command3>(_fixture);
         Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
         _fixture.Bus.Send(new TestCommands.Command3(CorrelatedMessage.NewRoot()));
         AssertEx.IsOrBecomesTrue(
             () => Interlocked.Read(ref _fixture.GotTestCommand3) == 2,
             msg: "Expected command handled twice, got" + Interlocked.Read(ref _fixture.GotTestCommand3));
         //cleanup
         subscription.Dispose();
     }
 }
Esempio n. 9
0
        public async Task CanWithdrawCash(decimal deposit, decimal withdraw)
        {
            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var depositedEv = new CashDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = deposit
            };

            var cmd = new WithdrawCash()
            {
                AccountId = _accountId,
                Amount    = withdraw
            };

            var withdrawnEv = new CashWithdrawn(cmd)
            {
                AccountId = _accountId,
                Amount    = cmd.Amount
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, depositedEv)
                .When(cmd)
                .Then(withdrawnEv));
        }
        public when_using_listener_start_with_custom_stream_synched(StreamStoreConnectionFixture fixture)
        {
            var conn = fixture.Connection;

            conn.Connect();

            // Build an origin stream from strings to which the the events are appended
            var originStreamName = $"testStream-{Guid.NewGuid():N}";


            var result = fixture.Connection.AppendToStream(
                originStreamName,
                ExpectedVersion.NoStream,
                null,
                _eventSerializer.Serialize(new TestEvent(CorrelatedMessage.NewRoot())));

            Assert.True(result.NextExpectedVersion == 0);

            // Wait for the stream to be written
            CommonHelpers.WaitForStream(conn, originStreamName);

            StreamListener listener = new SynchronizableStreamListener(
                originStreamName,
                fixture.Connection,
                new PrefixedCamelCaseStreamNameBuilder(),
                _eventSerializer,
                true);

            listener.EventStream.Subscribe(new AdHocHandler <Event>(Handle));
            listener.Start(originStreamName);
        }
Esempio n. 11
0
        public async Task CannotWithdrawCashIfNotEnoughFunds()
        {
            var deposit  = 500m;
            var withdraw = 1000m;

            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var depositSetEv = new CashDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = deposit
            };

            var cmd = new WithdrawCash()
            {
                AccountId = _accountId,
                Amount    = withdraw
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, depositSetEv)
                .When(cmd)
                .Throws(new SystemException("The account does not have enough funds for requested wire transfer.")));
        }
Esempio n. 12
0
        public void DepositCash(
            decimal amount,
            CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new SystemException("The deposited cash amount should be greater than 0.");
            }

            Raise(
                new CashDeposited(source)
            {
                AccountId = Id,
                Amount    = amount
            });

            if (_blocked)
            {
                Raise(
                    new AccountUnblocked(source)
                {
                    AccountId = Id
                });
            }
        }
        public when_using_listener_start_with_category_aggregate(StreamStoreConnectionFixture fixture)
        {
            var streamNameBuilder = new PrefixedCamelCaseStreamNameBuilder();
            var conn = fixture.Connection;

            conn.Connect();

            var aggStream      = streamNameBuilder.GenerateForAggregate(typeof(AggregateCategoryTestAggregate), Guid.NewGuid());
            var categoryStream = streamNameBuilder.GenerateForCategory(typeof(AggregateCategoryTestAggregate));

            // Drop an event into the stream testAggregate-guid
            var result = conn.AppendToStream(
                aggStream,
                ExpectedVersion.NoStream,
                null,
                _eventSerializer.Serialize(new TestEvent(CorrelatedMessage.NewRoot())));

            Assert.True(result.NextExpectedVersion == 0);

            //wait for the projection to be written.
            CommonHelpers.WaitForStream(conn, categoryStream);

            // Now set up the projection listener, and start it.
            var listener = new SynchronizableStreamListener(
                "category listener",
                conn,
                streamNameBuilder,
                new JsonMessageSerializer());

            listener.EventStream.Subscribe <TestEvent>(new AdHocHandler <TestEvent>(Handle));
            listener.Start <AggregateCategoryTestAggregate>();
        }
        public void TestParentTestMessage()
        {
            // When subscribing to ParentTest Event the appropriate handler will be invoked when
            //  child (descendant) message types are published.
            _bus.Subscribe <ParentTestEvent>(this);
            var parentTestEvent = new ParentTestEvent(CorrelatedMessage.NewRoot());

            _bus.Publish(parentTestEvent);
            AssertEx.IsOrBecomesTrue(() => _testEventCount == 0, msg: $"Expected 0 got {_testEventCount}");
            AssertEx.IsOrBecomesTrue(() => _parentTestEventCount == 1, msg: $"Expected 1 got {_parentTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _childTestEventCount == 0, msg: $"Expected 0 got {_childTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _grandChildTestEventCount == 0, msg: $"Expected 0 got {_grandChildTestEventCount}");

            _bus.Subscribe <ChildTestEvent>(this);
            var childTestEvent = new ChildTestEvent(parentTestEvent);

            _bus.Publish(childTestEvent);
            AssertEx.IsOrBecomesTrue(() => _testEventCount == 0, msg: $"Expected 0 got {_testEventCount}");
            AssertEx.IsOrBecomesTrue(() => _parentTestEventCount == 2, msg: $"Expected 2 got {_parentTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _childTestEventCount == 1, msg: $"Expected 1 got {_childTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _grandChildTestEventCount == 0, msg: $"Expected 0 got {_grandChildTestEventCount}");

            _bus.Subscribe <GrandChildTestEvent>(this);
            var grandChildTestEvent = new GrandChildTestEvent(childTestEvent);

            _bus.Publish(grandChildTestEvent);
            AssertEx.IsOrBecomesTrue(() => _testEventCount == 0, msg: $"Expected 0 got {_testEventCount}");
            AssertEx.IsOrBecomesTrue(() => _parentTestEventCount == 3, msg: $"Expected 3 got {_parentTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _childTestEventCount == 2, msg: $"Expected 2 got {_childTestEventCount}");
            AssertEx.IsOrBecomesTrue(() => _grandChildTestEventCount == 1, msg: $"Expected 1 got {_grandChildTestEventCount}");
        }
        public when_logging_disabled_and_commands_are_fired(StreamStoreConnectionFixture fixture) : base(fixture.Connection)
        {
            // command must have a commandHandler
            _cmdHandler = new TestCommandSubscriber(Bus);

            _multiFireCount   = 0;
            _testCommandCount = 0;

            _listener = new SynchronizableStreamListener(
                Logging.FullStreamName,
                Connection,
                StreamNameBuilder,
                EventSerializer);
            _listener.EventStream.Subscribe <Message>(this);

            _listener.Start(Logging.FullStreamName);
            CorrelatedMessage source = CorrelatedMessage.NewRoot();

            // create and fire a set of commands
            for (int i = 0; i < _maxCountedCommands; i++)
            {
                // this is just an example command - choice to fire this one was random
                var cmd = new TestCommands.Command2(source);
                Bus.Send(cmd,
                         $"exception message{i}",
                         TimeSpan.FromSeconds(2));
                source = cmd;
            }
            var tstCmd = new TestCommands.Command3(source);

            Bus.Send(tstCmd,
                     "Test Command exception message",
                     TimeSpan.FromSeconds(1));
        }
Esempio n. 16
0
        public async Task CanUnblockAccountOnNextBusinessDay()
        {
            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var accBlockedEv = new AccountBlocked(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId
            };

            var depositedEv = new ChequeDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = 1000m
            };

            var cmd = new StartNewBusinessDay()
            {
                AccountId = _accountId
            };

            var accUnblockedEv = new AccountUnblocked(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, accBlockedEv, depositedEv)
                .When(cmd)
                .Then(accUnblockedEv));
        }
Esempio n. 17
0
        public void DepositCash(Guid id, double amount, IClock clock, CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new InvalidOperationException("Cash's amount must be strictly positive");
            }

            var depositTime = clock.GetCurrentInstant();

            Raise(new CashDeposited(source)
            {
                AccountId   = Id,
                Amount      = amount,
                DepositedAt = depositTime
            });

            if (_blocked)
            {
                Raise(new AccountUnblocked(source)
                {
                    AccountId = Id,
                    Raison    = "Cash Deposited"
                });
            }
        }
Esempio n. 18
0
        public void unsubscribe_should_not_remove_other_handlers()
        {
            lock (_fixture) {
                AssertEx.IsOrBecomesTrue(() => _fixture.Bus.Idle);
                _fixture.ClearCounters();

                Interlocked.Exchange(ref _fixture.GotTestCommand3, 0);
                //no subscription
                Assert.False(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
                //Add subscription
                var subscription = _fixture.Bus.Subscribe <TestCommands.Command3>(_fixture);
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
                _fixture.Bus.Send(new TestCommands.Command3(CorrelatedMessage.NewRoot()));
                AssertEx.IsOrBecomesTrue(
                    () => Interlocked.Read(ref _fixture.GotTestCommand3) == 1,
                    msg: "Expected command handled once, got" + Interlocked.Read(ref _fixture.GotTestCommand3));
                //dispose subscription to unsubscribe
                subscription.Dispose();
                Assert.False(_fixture.Bus.HasSubscriberFor <TestCommands.Command3>());
                Assert.Throws <CommandNotHandledException>(() =>
                                                           _fixture.Bus.Send(new TestCommands.Command3(CorrelatedMessage.NewRoot())));

                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Command1>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Command2>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Fail>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.Throw>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.WrapException>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.TypedResponse>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.ChainedCaller>());
                Assert.True(_fixture.Bus.HasSubscriberFor <TestCommands.LongRunning>());
            }
        }
Esempio n. 19
0
        public async Task CannotUnblockAccountAfterDepositCheque()
        {
            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var accBlockedEv = new AccountBlocked(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId
            };

            var cmd = new DepositCheque()
            {
                AccountId = _accountId,
                Amount    = 1000
            };

            var amountSetEv = new ChequeDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = cmd.AccountId,
                Amount    = cmd.Amount
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, accBlockedEv)
                .When(cmd)
                .Then(amountSetEv));
        }
        public async Task CanDepositCash()
        {
            Clock.SetCurrent(new LocalDateTime(2018, 1, 1, 9, 0));

            var created = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId         = AccountId,
                AccountHolderName = "NNN"
            };

            var cmd = new DepositCash
            {
                AccountId = AccountId,
                Amount    = 350
            };

            var ev = new CashDeposited(cmd)
            {
                AccountId   = AccountId,
                Amount      = cmd.Amount,
                DepositedAt = Clock.Current
            };

            await Runner.Run(
                def => def.Given(created).When(cmd).Then(ev)
                );
        }
Esempio n. 21
0
        public async Task CashWithdrawalGreaterThanAllowedLimit()
        {
            decimal withdrawAmount = 10000;
            decimal depositeAmount = 5000;

            var accountCreated = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId         = _accountId,
                AccountHolderName = "Tushar"
            };

            var evtCashDeposited = new CashDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId     = _accountId,
                DepositAmount = depositeAmount
            };

            var cmdWithdrawCash = new WithdrawCash()
            {
                AccountId      = _accountId,
                WithdrawAmount = withdrawAmount
            };

            var evAccountBlocked = new AccountBlocked(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = withdrawAmount
            };

            await _runner.Run(
                def => def.Given(accountCreated, evtCashDeposited).When(cmdWithdrawCash).Then(evAccountBlocked)
                );
        }
        public void TestNoSubscriber()
        {
            var testEvent = new TestEvent(CorrelatedMessage.NewRoot());

            _bus.Publish(testEvent);
            AssertEx.IsOrBecomesTrue(() => _testEventCount == 0, msg: $"Expected 0 got {_testEventCount}");
        }
Esempio n. 23
0
        public when_events_are_published(StreamStoreConnectionFixture fixture) : base(fixture.Connection)
        {
            _listener = new SynchronizableStreamListener(
                Logging.FullStreamName,
                Connection,
                StreamNameBuilder,
                EventSerializer);
            _listener.EventStream.Subscribe <Event>(this);

            _listener.Start(Logging.FullStreamName);

            _countedEventCount    = 0;
            _testDomainEventCount = 0;
            CorrelatedMessage source = CorrelatedMessage.NewRoot();

            // create and publish a set of events
            for (int i = 0; i < _maxCountedEvents; i++)
            {
                var evt = new CountedEvent(i, source);
                Bus.Publish(evt);
                source = evt;
            }

            Bus.Subscribe(new AdHocHandler <TestEvent>(_ => Interlocked.Increment(ref _gotEvt)));
            Bus.Publish(new TestEvent(source));
        }
Esempio n. 24
0
        public void can_retrieve_correlated_aggregate()
        {
            var command1 = CorrelatedMessage.NewRoot();
            var id       = Guid.NewGuid();
            var agg      = new CorrelatedAggregate(id, command1);

            agg.RaiseCorrelatedEvent();
            agg.RaiseCorrelatedEvent();
            _repo.Save(agg);

            var command2  = CorrelatedMessage.NewRoot();
            var recovered = _repo.GetById <CorrelatedAggregate>(id, command2);

            Assert.NotNull(recovered);
            Assert.Equal(2, recovered.Version);//zero based, includes created

            recovered.RaiseCorrelatedEvent();
            recovered.RaiseCorrelatedEvent();

            _repo.Save(recovered);
            var command3   = CorrelatedMessage.NewRoot();
            var recovered2 = _repo.GetById <CorrelatedAggregate>(id, command3);

            Assert.NotNull(recovered2);
            Assert.Equal(4, recovered2.Version);
        }
Esempio n. 25
0
        public async Task CanSetDailyTransfertLimit()
        {
            var created = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId         = AccountId,
                AccountHolderName = "Miled",
                OverdraftLimit    = 0
            };

            var cmd = new SetDailyWireTransfertLimit
            {
                AccountId = AccountId,
                Limit     = 350
            };

            var ev = new DailyWireTransfertLimitSet(cmd)
            {
                AccountId = AccountId,
                Limit     = 350
            };

            await Runner.Run(
                def => def.Given(created).When(cmd).Then(ev)
                );
        }
Esempio n. 26
0
        public TAggregate GetById <TAggregate>(Guid id, int version, CorrelatedMessage source) where TAggregate : CorrelatedEDSM, IEventSource
        {
            var agg = _repository.GetById <TAggregate>(id, version);

            agg.ApplyNewSource(source);
            return(agg);
        }
Esempio n. 27
0
        public async Task CannotWireTransferIfNotEnoughFunds(
            decimal deposit, decimal transfer)
        {
            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var cashDepositedEv = new CashDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = deposit
            };

            var cmd = new TryWireTransfer()
            {
                AccountId = _accountId,
                Amount    = transfer
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, cashDepositedEv)
                .When(cmd)
                .Throws(new SystemException("The account does not have enough funds for requested wire transfer.")));
        }
Esempio n. 28
0
        public async Task CannotWithdrawFundsIfTransferIsNotPositive(decimal transfer)
        {
            var deposit = 5000m;
            var limit   = 5000m;

            var accCreatedEv = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Name      = "Jake Sanders"
            };

            var cashDepositedEv = new CashDeposited(CorrelatedMessage.NewRoot())
            {
                AccountId = _accountId,
                Amount    = deposit
            };

            var limitSetEv = new DailyWireTransferLimitSet(CorrelatedMessage.NewRoot())
            {
                AccountId  = _accountId,
                DailyLimit = limit
            };

            var cmd = new TryWireTransfer()
            {
                AccountId = _accountId,
                Amount    = transfer
            };

            await _runner.Run(
                def => def
                .Given(accCreatedEv, cashDepositedEv, limitSetEv)
                .When(cmd)
                .Throws(new SystemException("Wire Transfer amount should be greater than 0.")));
        }
        public async Task CanLimitOverdraft()
        {
            var created = new AccountCreated(CorrelatedMessage.NewRoot())
            {
                AccountId         = AccountId,
                AccountHolderName = "Miled",
                OverdraftLimit    = 0
            };

            var cmd = new LimitOverdraft
            {
                AccountId = AccountId,
                Limit     = 350
            };

            var ev = new OverdraftLimited(cmd)
            {
                AccountId = AccountId,
                Limit     = 350
            };

            await Runner.Run(
                def => def.Given(created).When(cmd).Then(ev)
                );
        }
Esempio n. 30
0
        public void WithdrawCashFromAccount(decimal withdrawAmount, CorrelatedMessage source)
        {
            if (withdrawAmount < 0)
            {
                throw new ValidationException("Cash withdrawal amount cannot be negative");
            }

            if (_isBlocked)
            {
                Raise(new AccountBlocked(source)
                {
                    AccountId = Id,
                    Amount    = withdrawAmount
                });
                return;
            }

            if (withdrawAmount > (_accountBalance + _accountOverdraftLimit))
            {
                Raise(new AccountBlocked(source)
                {
                    AccountId = Id,
                    Amount    = withdrawAmount
                });
                return;
            }

            Raise(new CashWithdrawn(source)
            {
                AccountId      = Id,
                WithdrawAmount = withdrawAmount
            });
        }
        public void Should_convert_a_simple_correlation_expression()
        {
            var message = new CorrelatedMessage
            {
                CorrelationId = NewId.NextGuid()
            };
            ConsumeContext<CorrelatedMessage> consumeContext = new TestConsumeContext<CorrelatedMessage>(message);
            var converter = new EventCorrelationExpressionConverter<TestState, CorrelatedMessage>(consumeContext);

            Expression<Func<TestState, bool>> result = converter
                .Convert((state, context) => state.CorrelationId == context.Message.CorrelationId);

            Console.WriteLine(result);
        }