public void CanSendEmail()
        {
            var queueStreamName  = "Test" + EventStoreQueueConstants.QueueStreamName;
            var outboxStreamName = "Test" + EventStoreQueueConstants.OutboxStreamName;

            var mainLog = LogManager.GetLoggerFor("TEST");

            // EventStoreSettings
            var eventStoreIp      = "127.0.0.1";
            var eventStoreTcpPort = 1113;
            var eventStoreUser    = "******";
            var eventStorePass    = "******";

            // Conectando el EventStore
            var eventStoreSettings = ConnectionSettings
                                     .Create()
                                     .KeepReconnecting()
                                     .SetHeartbeatTimeout(TimeSpan.FromSeconds(30))
                                     .SetDefaultUserCredentials(new UserCredentials(eventStoreUser, eventStorePass))
                                     .Build();

            var tcp              = new IPEndPoint(IPAddress.Parse(eventStoreIp), eventStoreTcpPort);
            var connection       = EventStoreConnection.Create(eventStoreSettings, tcp);
            var connectionSource = "local";

            connection.Closed += (s, e) =>
                                 mainLog.Error($"The {connectionSource} ES connection was closed");
            connection.Connected += (s, e) =>
                                    mainLog.Log($"The connection with {connectionSource} ES was establised");
            connection.Disconnected += (s, e) =>
                                       mainLog.Log($"The connection with {connectionSource} ES was lost");
            connection.Reconnecting += (s, e) =>
                                       mainLog.Log($"Reconnecting with {connectionSource} ES");
            connection.ConnectAsync().Wait();

            var serializer = new JsonSerializer();

            var repo = new EventSourcedRepository(connection, serializer, enablePersistentSnapshotting: true, snapshotInterval: 1);

            var client = new SimpleEmailSenderEsClient(connection, serializer, queueStreamName);

            var mail = EmailFactory.NewFrom("Alexis", "*****@*****.**")
                       .To("Alexis", "*****@*****.**")
                       .Subject("Test")
                       .BodyUsingTemplateFromFile(@"~/testmail.html", new { Name = "Chary" })
                       .Build();

            client.Send(mail);

            // Consuming
            //var sender = new FakeEmailSender("mail.fecoprod.com.py", 25);
            var sender = new WaitEmailSender("mail.fecoprod.com.py", 25);

            using (var job = new MailSendingJob(connection, repo, serializer, sender, queueStreamName, outboxStreamName))
            {
                job.Start();

                sender.WaitForSending();
            }
        }
Exemple #2
0
        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 async Task Should_dispatch_events()
        {
            //Arrange
            var eventStoreMock = new Mock <IEventStore>();
            //var wasCalled = false;
            //var mediatorMock = new Mock<IMediator>();
            //mediatorMock
            //    .Setup(m => m.Publish(It.IsAny<TestDomainEvent>(), It.IsAny<CancellationToken>()))
            //    .Callback(() =>
            //    {
            //        wasCalled = true;
            //    });
            //    .Returns(Task.CompletedTask);

            //.ReturnsAsync(Task.CompletedTask); //<-- return Task to allow await to continue
            //mediatorMock.Setup(x=> x.Publish())
            var mediatorMock = new TestMediator();

            var sut           = new EventSourcedRepository <TestEventSourcedAggregateRoot>(eventStoreMock.Object, Mock.Of <ISnapshotStore>(), mediatorMock, new EventSourcingOptions(), Mock.Of <ILogger <EventSourcedRepository <TestEventSourcedAggregateRoot> > >());
            var testAggregate = new Mock <TestEventSourcedAggregateRoot>();
            var domainEvent   = new TestDomainEvent();
            var domainEvents  = new List <IDomainEvent> {
                domainEvent
            };

            testAggregate.Setup(a => a.GetUncommittedChanges()).Returns(domainEvents);
            //Act
            await sut.SaveAsync(testAggregate.Object, CancellationToken.None);

            //Assert
            //mediatorMock.Verify(m => m.Publish(domainEvent, It.IsAny<CancellationToken>()), Times.Once());

            mediatorMock.PublishCallsCount.Should().Be(1);
        }
        public void Find_should_return_hydrated_entity_when_it_has_snapsot_and_no_later_events()
        {
            var entityId = Guid.NewGuid();

            var snapshot = new MementoOriginator.Memento
            {
                SourceId = entityId,
                Version  = 3,
                Value    = 30
            };

            var eventStoreMock = new Mock <IEventStore>();

            eventStoreMock.Setup(eventStore => eventStore.Load(entityId, snapshot.Version + 1)).Returns(Enumerable.Empty <Commit>);

            var snapshotStoreMock = new Mock <ISnapshotStore>();

            snapshotStoreMock.Setup(snapshotStore => snapshotStore.Get(entityId, int.MaxValue)).Returns(() => snapshot);

            var repository = new EventSourcedRepository <MementoOriginator>(eventStoreMock.Object, snapshotStoreMock.Object);

            var entity = repository.Find(entityId);

            entity.Id.Should().Be(entityId);
            entity.Version.Should().Be(snapshot.Version);
            entity.Value.Should().Be(snapshot.Value);
        }
        internal static async Task <PaymentCQRS> Build(BankPaymentStatus paymentStatus,
                                                       IGenerateBankPaymentId bankPaymentIdGenerator,
                                                       IConnectToAcquiringBanks bankConnectionBehavior,
                                                       IProvideBankResponseTime delayProvider,
                                                       IProvideTimeout providerForBankResponseWaiting,
                                                       IKnowBufferAndReprocessPaymentRequest knowBufferAndReprocessPaymentRequest,
                                                       IAmCircuitBreakers circuitBreakers,
                                                       IThrowsException gatewayExceptionSimulator = null,
                                                       IPublishEvents eventsPublisher             = null)
        {
            var bus = eventsPublisher ?? new InMemoryBus();
            var eventSourcedRepository = new EventSourcedRepository <Payment>(new InMemoryEventStore(bus));

            var appSettingsAccessor = Substitute.For <IOptionsMonitor <AppSettings> >();

            appSettingsAccessor.CurrentValue.Returns(new AppSettings {
                Executor = ExecutorType.Tests
            });

            var random = Substitute.For <IGenerateAcquiringBankPaymentStatus>();

            random.GeneratePaymentStatus().Returns(paymentStatus);

            var paymentsIdsMemory           = new PaymentIdsMemory();
            var bankAdapterSelector         = new BankAdapterSelector(random, bankPaymentIdGenerator, delayProvider, bankConnectionBehavior, paymentsIdsMemory, NullLogger <BankAdapterSelector> .Instance);
            var merchantToBankAdapterMapper = new MerchantToBankAdapterMapper(bankAdapterSelector);
            var paymentRequestsMemory       = new PaymentRequestsMemory();

            var paymentProcessor = new PaymentProcessor(eventSourcedRepository,
                                                        NullLogger <PaymentProcessor> .Instance,
                                                        providerForBankResponseWaiting,
                                                        knowBufferAndReprocessPaymentRequest,
                                                        circuitBreakers,

                                                        gatewayExceptionSimulator);

            var optionMonitor = Substitute.For <IOptionsMonitor <AppSettings> >();

            optionMonitor.CurrentValue.Returns(new AppSettings
            {
                Executor = ExecutorType.Tests
            });

            var paymentRequestCommandHandler = new PaymentRequestCommandHandler(eventSourcedRepository, paymentRequestsMemory, paymentProcessor, merchantToBankAdapterMapper, new RequestBankSynchronyMaster(optionMonitor), NullLogger <PaymentRequestCommandHandler> .Instance);
            var requestController            = new PaymentRequestsController(paymentRequestCommandHandler, NullLogger <PaymentRequestsController> .Instance);

            var readController = new PaymentReadController(eventSourcedRepository);

            var paymentDetailsRepository     = new PaymentDetailsRepository(NullLogger <PaymentDetailsRepository> .Instance);
            var paymentDetailsReadController = new PaymentsDetailsController(paymentsIdsMemory, paymentDetailsRepository);

            var readProjections = new ReadProjections(bus, paymentDetailsRepository);
            await readProjections.StartAsync(new CancellationToken(false));

            var gatewayPaymentsIdsController       = new GatewayPaymentsIdsController(paymentsIdsMemory);
            var acquiringBankPaymentsIdsController = new AcquiringBankPaymentsIdsController(paymentsIdsMemory);

            return(new PaymentCQRS(requestController, readController, paymentDetailsReadController, paymentRequestsMemory, paymentProcessor, gatewayPaymentsIdsController, acquiringBankPaymentsIdsController, readProjections));
        }
        public void Find_should_return_null_when_there_are_no_evetns_with_specified_source_id()
        {
            var eventStoreMock = new Mock <IEventStore>();

            eventStoreMock.Setup(eventStore => eventStore.Load(It.IsAny <Guid>(), 0)).Returns(Enumerable.Empty <Commit>);

            var repository = new EventSourcedRepository <CorrectEventSourced>(eventStoreMock.Object);

            repository.Find(Guid.NewGuid()).Should().BeNull();
        }
Exemple #7
0
        public CalendarSystem()
        {
            _publisher = new EventPublisher();
            var eventStore = new EventStore(_publisher);

            _sender = new CommandSender();

            var calendarDayRepo = new EventSourcedRepository <CalendarDayAggregate>(eventStore);

            _sender.RegisterHandler(new CreateCalendarDayHandler(calendarDayRepo));
            _sender.RegisterHandler(new RequestAppointmentCommandHandler(calendarDayRepo));
        }
        public void Should_save_events_in_event_store()
        {
            var entity = new CorrectEventSourced(42);

            entity.Update(43);
            entity.Update(44);

            var correlationId = Guid.NewGuid().ToString();

            var expectedEvents = new IEvent[]
            {
                new CorrectEventSourced.Created
                {
                    SourceId      = entity.Id,
                    SourceVersion = 1,
                    Value         = 42
                },
                new CorrectEventSourced.Updated
                {
                    SourceId      = entity.Id,
                    SourceVersion = 2,
                    Value         = 43
                },
                new CorrectEventSourced.Updated
                {
                    SourceId      = entity.Id,
                    SourceVersion = 3,
                    Value         = 44
                }
            };

            var expectedMetadata = new Dictionary <string, string>
            {
                { "CorrelationId", correlationId }
            };

            var eventStoreMock = new Mock <IEventStore>();

            Commit storedCommit = null;

            eventStoreMock.Setup(eventStore => eventStore.Save(It.IsAny <Commit>()))
            .Callback <Commit>(commit => storedCommit = commit);

            var repository = new EventSourcedRepository <CorrectEventSourced>(eventStoreMock.Object);

            repository.Save(entity, correlationId);

            storedCommit.Changes.ShouldBeEquivalentTo(expectedEvents);
            storedCommit.Metadata.ShouldAllBeEquivalentTo(expectedMetadata);
            storedCommit.Id.Should().NotBeEmpty();
            storedCommit.SourceId.Should().Be(entity.Id);
            storedCommit.SourceType.Should().Be(typeof(CorrectEventSourced).Name);
        }
Exemple #9
0
        private static ContractCommandHandlers GetCommandHandler()
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                       .AddEnvironmentVariables();

            var environment   = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT");
            var isDevelopment = string.Equals(environment, "development", StringComparison.OrdinalIgnoreCase);

            if (isDevelopment)
            {
                configurationBuilder.AddUserSecrets(Assembly.GetCallingAssembly());
            }

            var configuration = configurationBuilder.Build();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .Enrich.With <CorrelationLogEventEnricher>()
                         .WriteTo.MSSqlServer(configuration.GetConnectionString("Logs"), "Logs", autoCreateSqlTable: true)
                         .CreateLogger();

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddSerilog();

            var stanConnectionProvider  = new StanConnectionProvider(configuration, new Logger <StanConnectionProvider>(loggerFactory), null);
            var topicRegistry           = new DefaultTopicRegistry(configuration);
            var messageTypeRegistry     = new DefaultMessageTypeRegistry();
            var messageSerdes           = new NewtonsoftJsonMessageSerDes(messageTypeRegistry);
            var messagingTopicPublisher = new NatsMessagingTopicPublisher(stanConnectionProvider, new Logger <NatsMessagingTopicPublisher>(loggerFactory));
            var messageBusPublisher     = new MessageBusPublisher(messagingTopicPublisher, topicRegistry, messageSerdes, configuration);

            var scripts         = new Scripts();
            var eventRepository = new AdoNetEventRepository(scripts, new Logger <AdoNetEventRepository>(loggerFactory), new Options());

            var eventStoreSerDes    = new NewtonsoftJsonEventStoreSerDes();
            var eventStore          = new EventStore.EventStore(eventRepository, eventStoreSerDes, new Logger <EventStore.EventStore>(loggerFactory));
            var eventStoreDecorator = new MessagingEventStoreDecorator(eventStore, messageBusPublisher, new MessagingTopicResolver(new Options()));
            var mediator            = new OpenFaaSMediator(configuration, new Logger <OpenFaaSMediator>(loggerFactory));
            var repository          = new EventSourcedRepository <Contract>(eventStoreDecorator, null, mediator, new EventSourcingOptions(), new Logger <EventSourcedRepository <Contract> >(loggerFactory));
            var result = new ContractCommandHandlers(repository);

            //disposables = new List<IDisposable>{stanConnectionProvider};

            return(result);
        }
        public void Get_should_throw_an_exception_when_there_are_no_evetns_with_specified_source_id()
        {
            var eventStoreMock = new Mock <IEventStore>();

            eventStoreMock.Setup(eventStore => eventStore.Load(It.IsAny <Guid>(), 0)).Returns(Enumerable.Empty <Commit>);

            var repository = new EventSourcedRepository <CorrectEventSourced>(eventStoreMock.Object);

            var    id     = Guid.NewGuid();
            Action action = () => repository.Get(id);

            action.ShouldThrow <EntityNotFoundException>()
            .Where(ex => ex.EntityId == id.ToString() && ex.EntityType == typeof(CorrectEventSourced).Name);
        }
Exemple #11
0
        public void SetUp()
        {
            serializer = new JsonSerializer();

            var cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;

            var eventStore = new EventStore(Tenant, cloudStorageAccount, serializer, new Mock <IEventBus>().Object);

            repository = new EventSourcedRepository <TestEventSourced>(eventStore);

            var blobClient = cloudStorageAccount.CreateCloudBlobClient();

            this.headsContainer   = blobClient.GetContainerReference(Tenant.ToLower() + "-heads");
            this.commitsContainer = blobClient.GetContainerReference(Tenant.ToLower() + "-commits");
        }
        public void Find_should_return_hydrated_entity_when_it_has_snapsot_and_events()
        {
            var entityId = Guid.NewGuid();

            var snapshot = new MementoOriginator.Memento
            {
                SourceId = entityId,
                Version  = 3,
                Value    = 30
            };

            var events = new IEvent[]
            {
                new CorrectEventSourced.Updated {
                    SourceId = entityId, SourceVersion = snapshot.Version + 1, Value = 40
                },
                new CorrectEventSourced.Updated {
                    SourceId = entityId, SourceVersion = snapshot.Version + 2, Value = 50
                }
            };

            var commit = new Commit
            {
                Id       = Guid.NewGuid(),
                SourceId = entityId,
                Changes  = events
            };

            var snapshotStoreMock = new Mock <ISnapshotStore>();

            snapshotStoreMock.Setup(snapshotStore => snapshotStore.Get(entityId, int.MaxValue)).Returns(() => snapshot);

            var eventStoreMock = new Mock <IEventStore>();

            eventStoreMock.Setup(eventStore => eventStore.Load(entityId, snapshot.Version + 1)).Returns(new[] { commit });

            var repository = new EventSourcedRepository <MementoOriginator>(eventStoreMock.Object, snapshotStoreMock.Object);

            var entity = repository.Find(entityId);

            entity.Id.Should().Be(entityId);
            entity.Version.Should().Be(events.Last().SourceVersion);
            entity.Value.Should().Be(events.OfType <CorrectEventSourced.Updated>().Last().Value);
        }
        public async Task Should_mark_changes_as_committed_for_aggregate_when_aggregate_is_saved()
        {
            //Arrange
            var eventStoreMock = new Mock <IEventStore>();
            var sut            = new EventSourcedRepository <TestEventSourcedAggregateRoot>(eventStoreMock.Object, Mock.Of <ISnapshotStore>(), Mock.Of <IMediator>(), new EventSourcingOptions(), Mock.Of <ILogger <EventSourcedRepository <TestEventSourcedAggregateRoot> > >());
            var domainEvent    = Mock.Of <IDomainEvent>();
            var domainEvents   = new List <IDomainEvent> {
                domainEvent
            };
            var testAggregate = new Mock <TestEventSourcedAggregateRoot>();

            testAggregate.Setup(a => a.GetUncommittedChanges()).Returns(domainEvents);

            //Act
            await sut.SaveAsync(testAggregate.Object, CancellationToken.None);

            //Assert
            testAggregate.Verify(a => a.MarkChangesAsCommitted(), Times.Once);
        }
        public async Task Should_save_events_in_event_store_when_aggregate_is_saved()
        {
            //Arrange
            //var eventStoreMock = new Mock<IEventStore>();
            var eventStoreMock = new TestEventStore();
            var sut            = new EventSourcedRepository <TestEventSourcedAggregateRoot>(eventStoreMock, Mock.Of <ISnapshotStore>(), Mock.Of <IMediator>(), new EventSourcingOptions(), Mock.Of <ILogger <EventSourcedRepository <TestEventSourcedAggregateRoot> > >());
            var domainEvent    = Mock.Of <IDomainEvent>();
            var domainEvents   = new List <IDomainEvent> {
                domainEvent
            };
            var testAggregate = new TestEventSourcedAggregateRoot(Guid.NewGuid(), 5, domainEvents);

            //Act
            await sut.SaveAsync(testAggregate, CancellationToken.None);

            //Assert
            //eventStoreMock.Verify(es => es.AppendEventsToStreamAsync(It.IsAny<string>(), It.Is<IEnumerable<IDomainEvent>>(de=> de.Single() == domainEvent), null, It.IsAny<CancellationToken>()));
            eventStoreMock.AppendEventsToStreamAsyncCallsCount.Should().Be(1);
        }
Exemple #15
0
        public void Start()
        {
            connection = new ConnectionFactory {
                HostName = QueueHost, RequestedHeartbeat = 30
            }.CreateConnection();

            channel = connection.CreateModel();
            channel.ExchangeDeclare(EventsExchange, "fanout", true);
            channel.QueueDeclare(queue: CommandsQueue, durable: false, exclusive: false, autoDelete: false, arguments: null);
            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
            consumer = new QueueingBasicConsumer(channel);
            channel.BasicConsume(queue: CommandsQueue, noAck: false, consumer: consumer);

            var repository     = new EventSourcedRepository <Customer>(new InMemoryEventStore(Publish));
            var commandHandler = new CommandHandler(repository);

            running = true;
            worker  = Task.Factory.StartNew(() => CommandHandlingTask(commandHandler));
        }
        public static void Run(string connStr)
        {
            IMessageSender  sender     = new SqlMessageSender(connStr, "dbo.messages");
            ITextSerializer serializer = new JsonTextSerializer();
            IEventStore     eventStore = new SqlEventStore(connStr, "dbo.events");

            IEventBus         eventBus     = new EventBus(sender, serializer);
            IMetadataProvider metaProvider = new StandardMetadataProvider();

            IEventSourcedRepository <AppointmentAggregate> repo = new
                                                                  EventSourcedRepository <AppointmentAggregate>(eventStore, eventBus, serializer, metaProvider);
            ICommandDispatcher cmdDispatcher = new CommandDispatcher();

            cmdDispatcher.Register(new AppointmentCommandHandler(repo));

            IMessageReceiver cmdReceiver = new SqlMessageReceiver(connStr, "dbo.messages");

            CommandProcessor commandProcessor = new CommandProcessor(cmdReceiver, serializer, cmdDispatcher);

            commandProcessor.Start();
        }
        public async Task Should_save_snapshot_in_snapshot_store_when_aggregate_is_saved()
        {
            //Arrange
            var snapshotStore = Mock.Of <ISnapshotStore>();
            var sut           = new EventSourcedRepository <TestSnapshotAggregateRoot>(Mock.Of <IEventStore>(), snapshotStore, Mock.Of <IMediator>(), new EventSourcingOptions {
                DefaultSnapshotVersionFrequency = 1
            }, Mock.Of <ILogger <EventSourcedRepository <TestSnapshotAggregateRoot> > >());

            var domainEvent  = Mock.Of <IDomainEvent>();
            var domainEvents = new List <IDomainEvent> {
                domainEvent
            };
            var testAggregate = new TestSnapshotAggregateRoot(Guid.NewGuid(), 1000, 1, 10, domainEvents);

            //Act
            await sut.SaveAsync(testAggregate, CancellationToken.None);

            //Assert
            Mock.Get(snapshotStore)
            .Verify(
                x => x.StoreSnapshotAsync(It.IsAny <SnapshotEnvelope>(), It.IsAny <CancellationToken>()),
                Times.Once);
        }
        public static void Run(string connStr)
        {
            IMessageSender  sender     = new SqlMessageSender(connStr, "dbo.messages");
            ITextSerializer serializer = new JsonTextSerializer();

            IEventStore       eventStore   = new SqlEventStore(connStr, "dbo.events");
            IEventBus         eventBus     = new EventBus(sender, serializer);
            IMetadataProvider metaProvider = new StandardMetadataProvider();
            IReadModelStorage <AppointmentReadModel> readModelStorage = new InMemeoryStorage <AppointmentReadModel>();

            IEventSourcedRepository <AppointmentAggregate> repo = new
                                                                  EventSourcedRepository <AppointmentAggregate>(eventStore, eventBus, serializer, metaProvider);

            IEventDispatcher evtDispatcher = new EventDispatcher();

            evtDispatcher.Register(new AppointmentEventHandler(readModelStorage));

            var evtReceiver = new SqlEventReceiver(new SqlEventStore(connStr, "dbo.events"));

            var eventProcessor = new EventProcessor(evtReceiver, serializer, evtDispatcher);

            eventProcessor.Start();
        }
        public void Find_should_return_hydrated_entity_when_it_has_events()
        {
            var entityId = Guid.NewGuid();

            var events = new IEvent[]
            {
                new CorrectEventSourced.Created {
                    SourceId = entityId, SourceVersion = 1, Value = 1
                },
                new CorrectEventSourced.Updated {
                    SourceId = entityId, SourceVersion = 2, Value = 20
                },
                new CorrectEventSourced.Updated {
                    SourceId = entityId, SourceVersion = 3, Value = 30
                }
            };

            var commit = new Commit
            {
                Id       = Guid.NewGuid(),
                SourceId = entityId,
                Changes  = events
            };

            var eventStoreMock = new Mock <IEventStore>();

            eventStoreMock.Setup(eventStore => eventStore.Load(entityId, 0)).Returns(new [] { commit });

            var repository = new EventSourcedRepository <CorrectEventSourced>(eventStoreMock.Object);

            var entity = repository.Find(entityId);

            entity.Id.Should().Be(entityId);
            entity.Version.Should().Be(events.Last().SourceVersion);
            entity.Value.Should().Be(events.Cast <dynamic>().Last().Value);
        }
        public async Task Should_not_take_snapshot_below_custom_frequency()
        {
            //Arrange
            var snapshotStore = Mock.Of <ISnapshotStore>();
            var options       = new EventSourcingOptions {
                DefaultSnapshotVersionFrequency = 10
            };
            var sut = new EventSourcedRepository <TestSnapshotAggregateRoot>(Mock.Of <IEventStore>(), snapshotStore, Mock.Of <IMediator>(), options, Mock.Of <ILogger <EventSourcedRepository <TestSnapshotAggregateRoot> > >());

            var domainEvent  = Mock.Of <IDomainEvent>();
            var domainEvents = new List <IDomainEvent> {
                domainEvent
            };
            var testAggregate = new TestSnapshotAggregateRoot(Guid.NewGuid(), 2, 1, 2, domainEvents);

            //Act
            await sut.SaveAsync(testAggregate, CancellationToken.None);

            //Assert
            Mock.Get(snapshotStore)
            .Verify(
                x => x.StoreSnapshotAsync(It.IsAny <SnapshotEnvelope>(), It.IsAny <CancellationToken>()),
                Times.Never);
        }
Exemple #21
0
        static void Main(string[] args)
        {
            Console.Title = "Simple Email Sender";

            _log = LogManager.GetLoggerFor("MAIN");

            // EventStoreSettings
            var eventStoreIp      = ConfigurationManager.AppSettings["EventStoreIp"];
            var eventStoreTcpPort = int.Parse(ConfigurationManager.AppSettings["EventStoreTcpPort"]);
            var eventStoreUser    = ConfigurationManager.AppSettings["EventStoreUser"];
            var eventStorePass    = ConfigurationManager.AppSettings["EventStorePass"];

            // Conectando el EventStore
            var eventStoreSettings = ConnectionSettings
                                     .Create()
                                     .KeepReconnecting()
                                     .SetDefaultUserCredentials(new UserCredentials(eventStoreUser, eventStorePass))
                                     .Build();

            var ip = new IPEndPoint(IPAddress.Parse(eventStoreIp), eventStoreTcpPort);

            _connection         = EventStoreConnection.Create(eventStoreSettings, ip);
            _connection.Closed += (s, e) =>
            {
                var ex = new InvalidOperationException($"The connection was {_connection.ConnectionName} closed. Reason: {e.Reason}");
                _log.Error(ex, "The connection was closed");
                throw ex;
            };
            _connection.Disconnected  += (s, e) => _log.Log($"The connection {_connection.ConnectionName} was disconnected. Reconnecting....");
            _connection.Reconnecting  += (s, e) => _log.Log($"The connection {_connection.ConnectionName} is now reconnecting");
            _connection.ErrorOccurred += (s, e) =>
            {
                _log.Error(e.Exception, "An error ocurred in connection " + _connection.ConnectionName);
                throw e.Exception;
            };
            _connection.Connected += (s, e) => _log.Log($"The connection {_connection.ConnectionName} is now connected");
            _connection.ConnectAsync();

            var serializer = new JsonSerializer();

            // Main sender settings
            var snapshotInterval             = int.Parse(ConfigurationManager.AppSettings["snapshotInterval"]);
            var enablePersistentSnapshotting = snapshotInterval > 0;
            var host = ConfigurationManager.AppSettings["host"];
            var port = int.Parse(ConfigurationManager.AppSettings["port"]);


            var repo        = new EventSourcedRepository(() => _connection, serializer, "MailQueueRepo", enablePersistentSnapshotting, snapshotInterval);
            var emailSender = new EmailSender(host, port);

            using (var job = new MailSendingJob(_connection, repo, serializer, emailSender, EventStoreQueueConstants.QueueStreamName, EventStoreQueueConstants.OutboxStreamName))
            {
                job.Start();

                string exitCode;
                do
                {
                    Console.WriteLine("Type [exit] to shut down...");
                    exitCode = Console.ReadLine();
                } while (exitCode.ToUpper().Trim() != "EXIT");
            }
        }
Exemple #22
0
        public CommandHandler(EventSourcedRepository <Customer> repository)
        {
            this.repository = repository;

            FillUpFakeData();
        }