コード例 #1
0
        public override void SetUp()
        {
            base.SetUp();

            DatabaseHelper.CleanEvents();
            DatabaseHelper.CleanEventStreams();

            var eventRepository = new EventRepository(DatabaseHelper.GetConnectionStringBuilder());

            EventSerializer = new Serialization.Newtonsoft.EventSerializer();

            var logger = new SerilogLogger(Log.ForContext<EventStore>());

            var eventStore = new EventStore(
                EventSerializer,
                eventRepository,
                logger,
                Guid.NewGuid);

            AggregateContext = new AggregateContext(
                eventStore,
                null, // TODO: replace with actual SnapshotStore
                new AggregateHydrator(),
                new DummyDispatcher());
        }
コード例 #2
0
        public void Dispatch(EventStore.Commit commit)
        {
            try
            {
                using (var scope = _container.BeginLifetimeScope())
                {
                    var _bus = scope.Resolve<IServiceBus>();

                    if (_logger.IsDebugEnabled)
                    {
                        _logger.Debug("Dispatching commit, number of events: " + commit.Events.Count);
                    }

                    _bus.PublishDomainUpdate(commit.Events.Select(e => e.Body).ToArray(),
                        new DomainUpdateMetadate
                        {
                            AggregateId = Guid.Parse(commit.Headers[AggregateRootMetadata.AggregateIdHeader] as string),
                            AggregateType = commit.Headers[AggregateRootMetadata.AggregateTypeHeader] as string,
                            Tenant = commit.Headers[AggregateRootMetadata.TenantHeader] as string,
                            ApplicationService = _endpoint,
                            LastVersion = commit.StreamRevision
                        });
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Could not dispatch message.", ex);
                throw;
            }
        }
コード例 #3
0
        public void AddingEventsToEmptyDatabaseCreatesProperEventsInDatabase()
        {
            var aggregateId = Guid.NewGuid();
            var expectedVersion = -1;
            IConcurrencyConflictResolver conflictResolver = null;
            var events = new List<Event>
            {
                new Event(),
                new Event()
            };

            var databaseMock = new DatabaseMock<EventDescriptors>();
            var publisherMock = new EventPublisherMock();

            var eventStore = new EventStore(publisherMock, databaseMock);

            eventStore.SaveEvents(
                aggregateId,
                events,
                expectedVersion,
                conflictResolver);

            var actual = databaseMock.Get(aggregateId.ToString());

            Assert.NotNull(actual);
            Assert.Equal(events.Count, actual.Count());
            publisherMock.AssertPublishCount<Event>(events.Count());
        }
コード例 #4
0
ファイル: Global.asax.cs プロジェクト: jeremiahredekop/m-r
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var bus = new FakeBus();

            var storage = new EventStore(bus);
            var rep = new Repository<InventoryItem>(storage);
            var commands = new InventoryCommandHandlers(rep);
            bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
            bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
            bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
            bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
            bus.RegisterHandler<RenameInventoryItem>(commands.Handle);
            var detail = new InvenotryItemDetailView();
            bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
            bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
            bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
            var list = new InventoryListView();
            bus.RegisterHandler<InventoryItemCreated>(list.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
            ServiceLocator.Bus = bus;
        }
コード例 #5
0
        public void ShouldBeVersionAscedingOrder()
        {
            var eventPublisher = MockRepository.GenerateMock<IEventPublisher>();
            var eventPersistence = MockRepository.GenerateMock<IEventPersistence>();
            var id = Guid.NewGuid();
            var events = new List<DomainEvent>
                {
                    new EmptyDomainEvent(id)
                        {
                            Version = 3
                        },
                    new EmptyDomainEvent(id)
                        {
                            Version = 1
                        },
                    new EmptyDomainEvent(id)
                        {
                            Version = 4
                        },
                    new EmptyDomainEvent(id)
                        {
                            Version = 2
                        }
                };
            eventPersistence.Stub(x => x.GetEventsForAggregate<EmptyDomainObject>(id)).Return(events);

            var eventStore = new EventStore(eventPersistence, eventPublisher);
            var retrievedEvents = eventStore.GetEventsForAggregate<EmptyDomainObject>(id);
            Assert.That(retrievedEvents[0].Version, NUnit.Framework.Is.EqualTo(1));
            Assert.That(retrievedEvents[1].Version, NUnit.Framework.Is.EqualTo(2));
            Assert.That(retrievedEvents[2].Version, NUnit.Framework.Is.EqualTo(3));
            Assert.That(retrievedEvents[3].Version, NUnit.Framework.Is.EqualTo(4));
        }
コード例 #6
0
        protected EventStoreBasedRepository(Guid aggregateId, EventStore store)
        {
            if (aggregateId == Guid.Empty)
                throw new InvalidOperationException("Aggregat ohne ID kann nicht erzeugt werden.");

            AggregateId = aggregateId;
            _store = store;
            _pastHistory = _store.Retrieve(aggregateId).ToList();
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: liuxiqin/Sevens
        private static void Main(string[] args)
        {
            ObjectContainer.SetContainer(new AutofacContainerObject());

            var applictionInitializer = new EventHandleProvider();

            applictionInitializer.Initialize(Assembly.GetExecutingAssembly());

            var commandInitializer = new CommandHandleProvider();

            commandInitializer.Initialize(Assembly.GetExecutingAssembly());

            ObjectContainer.RegisterInstance(applictionInitializer);
            ObjectContainer.RegisterInstance(commandInitializer);

            var dbConnection = new MySqlConnection(_mysqlConnection);

            var persistence = new SnapshotPersistence(dbConnection);

            var binarySerializer = new DefaultBinarySerializer();

            var snapshotRepository = new SnapshotRepository(persistence, new SnapshotFactory(binarySerializer));

            var eventPersistence = new EventStorePersistence(dbConnection);

            var eventFactory = new EventStreamFactory(binarySerializer);

            var eventStore = new EventStore(eventPersistence, eventFactory);

            IRepository repository = new EventSouringRepository(eventStore, snapshotRepository);

            var comamndHandler = ObjectContainer.Resolve<CommandHandleProvider>();

            var changePasswordCommand = new ChangePasswordCommand("90ca0d59-65e6-403b-82c5-8df967cc8e22", "2222222", "11111");

            var commandContext = new CommandContext(repository);

            var commandHanldeAction = comamndHandler.GetInternalCommandHandle(typeof(ChangePasswordCommand));
            commandHanldeAction(commandContext, changePasswordCommand);

            var aggregateRoots = commandContext.AggregateRoots;

            IList<IEvent> unCommitEvents = null;

            foreach (var item in aggregateRoots)
            {
                unCommitEvents = item.Value.Commit();
            }

            var aggregateRoot = aggregateRoots.FirstOrDefault().Value;

            eventStore.AppendToStream(aggregateRoot.AggregateRootId, new EventStream(aggregateRoot.Version, unCommitEvents));

            snapshotRepository.Create(aggregateRoot);

            Console.WriteLine("改方法执行完毕...");
        }
 protected IDomainRepository CreateDomainRepository(IBus bus)
 {
     var eventMappings = new NServiceBusDomainEventMappingFactory().CreateMappingCollection();
     var eventPersistence = new InProcEventPersistence();
     var eventPublisher = new NServiceBusEventPublisher(bus, eventMappings);
     var eventStore = new EventStore(eventPersistence, eventPublisher);
     var domainRepository = new DomainRepository(eventStore);
     return domainRepository;
 }
コード例 #9
0
        void SingleStreamPerPartitionUsingIndirectionLayer()
        {
            var store = new EventStore(new Partition(Table, "DIR"));

            store.Provision(VirtualPartition("vs-111"));
            store.Provision(VirtualPartition("vs-222"));

            store.Write(new Stream(new Partition(Partition.Table, "ps-333")), Event());
            store.Write(new Stream(new Partition(Partition.Table, "ps-444")), Event());

            var count = store.Streams().Count();
            Console.WriteLine(count);
        }
コード例 #10
0
ファイル: test_EventStore.cs プロジェクト: ralfw/dnp2013
        public void Play_all_events()
        {
            if (Directory.Exists("teststore")) Directory.Delete("teststore", true);
            var sut = new EventStore("teststore");
            sut.Record("n0", "0", "c");
            sut.Record("n1", "1", "c");
            sut.Record("n2", "2", "c");

            var es = sut.Play().ToArray();

            Assert.AreEqual("0", es[0].Data);
            Assert.AreEqual("1", es[1].Data);
            Assert.AreEqual("2", es[2].Data);
        }
コード例 #11
0
 public void DropSubscription(EventStore.Core.Services.SubscriptionDropReason reason)
 {
     switch (reason)
     {
         case EventStore.Core.Services.SubscriptionDropReason.AccessDenied:
             DropSubscription(SubscriptionDropReason.AccessDenied,
                 new AccessDeniedException(string.Format("Subscription to '{0}' failed due to access denied.",
                     _streamId == string.Empty ? "<all>" : _streamId)));
             break;
         case EventStore.Core.Services.SubscriptionDropReason.Unsubscribed:
             Unsubscribe();
             break;
     }
 }
コード例 #12
0
        public static IEventSourcedRepository<SeatsAvailability> GetSeatsAvailabilityRepository()
        {
            var serializer = new JsonTextSerializer();
#if LOCAL
            Func<EventStoreDbContext> ctxFactory = () => new EventStoreDbContext("EventStore");
            return new SqlEventSourcedRepository<SeatsAvailability>(ConferenceHelper.BuildEventBus(), serializer, ctxFactory);
#else
            var settings = InfrastructureSettings.Read("Settings.xml");
            var eventSourcingAccount = CloudStorageAccount.Parse(settings.EventSourcing.ConnectionString);
            var eventStore = new EventStore(eventSourcingAccount, settings.EventSourcing.SeatsAvailabilityTableName);
            var publisher = new EventStoreBusPublisher(ConferenceHelper.GetTopicSender("eventsAvailability"), eventStore, new EventStoreBusPublisherInstrumentation("worker", false));
            var metadata = new StandardMetadataProvider();
            return new AzureEventSourcedRepository<SeatsAvailability>(eventStore, publisher, serializer, metadata, new MemoryCache("RepositoryCache"));
#endif
        }
コード例 #13
0
ファイル: test_EventStore.cs プロジェクト: ralfw/dnp2013
        public void Read_event()
        {
            if (Directory.Exists("teststore")) Directory.Delete("teststore", true);
            var es = new EventStore("teststore");
            var number = es.Record("n", "d\ne", "c");

            var sut = new EventPersistenceProvider("teststore");
            var e = sut.Read_event(number);

            Assert.AreEqual("n", e.Name);
            Assert.AreEqual("c", e.Context);
            Assert.AreEqual("d\ne", e.Data);
            Assert.AreEqual(number, e.Number);
            Console.WriteLine(e.Timestamp);
        }
コード例 #14
0
ファイル: test_EventStore.cs プロジェクト: ralfw/dnp2013
        public void Play_events_in_range()
        {
            if (Directory.Exists("teststore")) Directory.Delete("teststore", true);
            var sut = new EventStore("teststore");
            sut.Record("n0", "0", "c");
            sut.Record("n1", "1", "c");
            sut.Record("n2", "2", "c");
            sut.Record("n3", "3", "c");

            var es = sut.Play(1,2).ToArray();

            Assert.AreEqual("1", es[0].Data);
            Assert.AreEqual("2", es[1].Data);
            Assert.AreEqual(2, es.Length);
        }
        public void Setup()
        {
            event_store = new EventStore<IEvent>(
                new DocumentDbConfiguration(
                    new Uri(document_db_connection_address),
                    document_db_connection_key,
                    database_id,
                    collection_id));

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Binder = new TypeNameSerialisationBinder("EventStore.DocumentDb.Tests.{0}, EventStore.DocumentDb.Tests"),
                TypeNameHandling = TypeNameHandling.Auto
            };
        }
コード例 #16
0
        public given_empty_store()
        {
            this.tableName = "EventStoreFixture" + new Random((int)DateTime.Now.Ticks).Next();
            var settings = InfrastructureSettings.Read("Settings.xml").EventSourcing;
            this.account = CloudStorageAccount.Parse(settings.ConnectionString);
            this.sut = new EventStore(this.account, this.tableName);

            this.sourceId = Guid.NewGuid().ToString();
            this.partitionKey = Guid.NewGuid().ToString();
            this.events = new[]
                             {
                                 new EventData { Version = 1, SourceId = sourceId, SourceType = "Source", TypeName = "Test1", Payload = "Payload1", CorrelationId = "correlation1" },
                                 new EventData { Version = 2, SourceId = sourceId, SourceType = "Source", TypeName = "Test2", Payload = "Payload2", CorrelationId = "correlation2"  },
                                 new EventData { Version = 3, SourceId = sourceId, SourceType = "Source", TypeName = "Test3", Payload = "Payload3", CorrelationId = "correlation3"  },
                             };
        }
コード例 #17
0
        public void ShouldBeAbleToGetEventsForAnAggregateRootById()
        {
            var eventPublisher = MockRepository.GenerateMock<IEventPublisher>();
            var eventPersistence = MockRepository.GenerateMock<IEventPersistence>();
            var id = Guid.NewGuid();
            var events = new List<DomainEvent>
                {
                    new EmptyDomainEvent(id)
                        {
                            Version = 1
                        }
                };
            eventPersistence.Stub(x => x.GetEventsForAggregate<EmptyDomainObject>(id)).Return(events);

            var eventStore = new EventStore(eventPersistence, eventPublisher);
            var retrievedEvents = eventStore.GetEventsForAggregate<EmptyDomainObject>(id);
            Assert.That(retrievedEvents, NUnit.Framework.Is.EquivalentTo(events));
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: jcwrequests/btw-gtd
        public static ConsoleEnvironment Build()
        {
            var handler = new SynchronousEventHandler();

            var inbox = new InboxProjection();
            handler.RegisterHandler(inbox);

            //var store = new InMemoryStore(handler);

            var store = new FileAppendOnlyStore(new DirectoryInfo(Directory.GetCurrentDirectory()));
            store.Initialize();
            var messageStore = new MessageStore(store);
            messageStore.LoadDataContractsFromAssemblyOf(typeof(ActionDefined));
            var currentVersion = store.GetCurrentVersion();
            var log = LogManager.GetLoggerFor<ConsoleEnvironment>();
            log.Debug("Event Store ver {0}", currentVersion);

            if (currentVersion > 0)
            {
                log.Debug("Running in-memory replay");
                foreach (var record in messageStore.EnumerateAllItems(0, int.MaxValue))
                {
                    foreach (var item in record.Items.OfType<Event>())
                    {
                        handler.Handle(item);
                    }
                }
                log.Debug("Replay complete");
            }

            var events = new EventStore(messageStore,handler);

            var tenant = new TenantAppService(events, new RealTimeProvider());
            var build = new ConsoleEnvironment
                {
                    Store = events,
                    Tenant = tenant,
                    Commands = ConsoleCommands.Actions,
                    Id = new TenantId(1),
                    Inbox = inbox
                };
            return build;
        }
        public void GivenSetOfEvents_WithFetchEventsFromDifferentTimes_ThenProperSetsAreLoaded()
        {
            //Given
            var streamId = Guid.NewGuid();
            var taskId   = Guid.NewGuid();

            //When
            var beforeCreateTimestamp = DateTime.UtcNow;

            EventStore.Append(streamId, new IssueCreated(taskId, "Initial Name"));
            Session.SaveChanges();
            var createTimestamp = DateTime.UtcNow;

            EventStore.Append(streamId, new IssueUpdated(taskId, "Updated name"));
            Session.SaveChanges();
            var firstUpdateTimestamp = DateTime.UtcNow;

            EventStore.Append(streamId, new IssueUpdated(taskId, "Updated again name"),
                              new IssueUpdated(taskId, "Updated again and again name"));
            Session.SaveChanges();
            var secondUpdateTimestamp = DateTime.UtcNow;

            //Then
            var events = EventStore.FetchStream(streamId, timestamp: beforeCreateTimestamp);

            events.Count.Should().Be.EqualTo(0);

            events = EventStore.FetchStream(streamId, timestamp: createTimestamp);
            events.Count.Should().Be.EqualTo(1);

            events = EventStore.FetchStream(streamId, timestamp: firstUpdateTimestamp);
            events.Count.Should().Be.EqualTo(2);

            events = EventStore.FetchStream(streamId, timestamp: secondUpdateTimestamp);
            events.Count.Should().Be.EqualTo(4);
        }
コード例 #20
0
        public void ShouldIncrementVersionCorrectly()
        {
            var rootId       = Guid.NewGuid();
            var queueService = new MemoryQueueService();
            var appendOnly   = new MemoryAppendOnlyStore(queueService);
            var eventStore   = new EventStore(appendOnly);
            var factory      = new AggregateFactory(eventStore);
            var rootToSave   = factory.Create <ProductCatalogAggregate>(rootId);

            eventStore.AppendToStream <ProductCatalogAggregate>(rootToSave.Id, rootToSave.Version, rootToSave.Changes);

            var stream = eventStore.LoadEventStream(rootId);
            var root   = new ProductCatalogAggregate(stream);

            root.CreateProduct(new CreateProductCommand(rootId, Guid.NewGuid(), "Notebook", "Dell Inspiron 15000"));

            eventStore.AppendToStream <ProductCatalogAggregate>(root.Id, root.Version, root.Changes);

            stream = eventStore.LoadEventStream(rootId);
            root   = new ProductCatalogAggregate(stream);

            Assert.Equal(2, stream.Version);
            Assert.Equal(1, root.CountProducts());
        }
コード例 #21
0
        /// <summary>
        /// Limits the calendar list to those specified
        /// </summary>
        /// <returns>The calendars in list.</returns>
        /// <param name="VisibleCalendars">Visible calendars.</param>
        private EKCalendar[] EKCalendarsInList(List <String> VisibleCalendars)
        {
            var visCals = new List <EKCalendar> ();

            EKCalendar[] calendars = null;
            if (new Version(UIDevice.CurrentDevice.SystemVersion) >= new Version(6, 0, 0, 0))
            {
                calendars = EventStore.GetCalendars(EKEntityType.Event);
            }
            else
            {
                calendars = EventStore.Calendars;
            }

            foreach (EKCalendar cal in calendars)
            {
                if (VisibleCalendars.Contains(cal.Title))
                {
                    visCals.Add(cal);
                }
            }

            return(visCals.ToArray());
        }
コード例 #22
0
ファイル: EventStoreTests.cs プロジェクト: yufengfei/Aoite
        public void UnregisterAllTest()
        {
            var container = new IocContainer();
            var store     = new EventStore(container);
            int x         = 1;
            var event1    = new MockEvent <SimpleCommand>((context, command) =>
            {
                x += 1;
                return(true);
            }, (context, command, exception) =>
            {
                x += 2;
            });
            var event2 = new MockEvent <SimpleCommand>((context, command) =>
            {
                x += 3;
                return(true);
            }, (context, command, exception) =>
            {
                x += 4;
            });

            store.Register <SimpleCommand>(event1);
            store.Register <SimpleCommand>(event2);
            Assert.True(store.RaiseExecuting <SimpleCommand>(null, null));
            Assert.Equal(5, x);
            store.RaiseExecuted <SimpleCommand>(null, null, null);
            Assert.Equal(11, x);

            store.UnregisterAll <SimpleCommand>();
            x = 1;
            Assert.True(store.RaiseExecuting <SimpleCommand>(null, null));
            Assert.Equal(1, x);
            store.RaiseExecuted <SimpleCommand>(null, null, null);
            Assert.Equal(1, x);
        }
コード例 #23
0
        public void BuildLMDBEventStoreDoesNotThrow()
        {
            IEventStoreBuilder builder = new EventStoreBuilder();

            EventStore es = null;

            es = builder.UseLMDBRepository()
                 .Configuration(@"c:\lmdb", 2, 10485760, new ProtobufEventsSerializer())
                 .UseCustom(new DummyEventPublisher())
                 .Build();

            Assert.NotNull(es);

            //Clean up database
            es.Dispose();


            //Cleaning up disk

            GC.Collect();
            GC.WaitForPendingFinalizers();

            var datafile = Path.Combine(@"c:\lmdb", "data.mdb");

            if (File.Exists(datafile))
            {
                File.Delete(datafile);
            }

            var lockfile = Path.Combine(@"c:\lmdb", "lock.mdb");

            if (File.Exists(lockfile))
            {
                File.Delete(lockfile);
            }
        }
コード例 #24
0
        public async Task <Guid> Create(ProductTrade newTrade)
        {
            // 1) raise domain events
            AddDomainEvent(new TradeRegisteredEvent(newTrade.Id));

            // store the object
            await _context.ProductTrade.AddAsync(newTrade);

            var command = new TradeRegisteredCommand(Guid.NewGuid(), newTrade.TradeId);

            var domainEvent = new EventStore();

            domainEvent.Id          = command.Id;
            domainEvent.EnqueueDate = DateTime.UtcNow;
            domainEvent.Type        = command.GetType().FullName;
            domainEvent.Data        = JsonConvert.SerializeObject(command);

            await _context.EventStore.AddAsync(domainEvent);

            // save changes
            await _context.SaveChangesAsync();

            return(newTrade.Id);
        }
コード例 #25
0
        private void RegisterRepositories(UnityContainer container)
        {
            // repository
            var eventSourcingAccount = CloudStorageAccount.Parse(this.azureSettings.EventSourcing.ConnectionString);
            var ordersEventStore = new EventStore(eventSourcingAccount, this.azureSettings.EventSourcing.OrdersTableName);
            var seatsAvailabilityEventStore = new EventStore(eventSourcingAccount, this.azureSettings.EventSourcing.SeatsAvailabilityTableName);

            container.RegisterInstance<IEventStore>("orders", ordersEventStore);
            container.RegisterInstance<IPendingEventsQueue>("orders", ordersEventStore);

            container.RegisterInstance<IEventStore>("seatsavailability", seatsAvailabilityEventStore);
            container.RegisterInstance<IPendingEventsQueue>("seatsavailability", seatsAvailabilityEventStore);

            container.RegisterType<IEventStoreBusPublisher, EventStoreBusPublisher>(
                "orders",
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter<IMessageSender>("orders"),
                    new ResolvedParameter<IPendingEventsQueue>("orders"),
                    new EventStoreBusPublisherInstrumentation("worker - orders", this.instrumentationEnabled)));
            container.RegisterType<IEventStoreBusPublisher, EventStoreBusPublisher>(
                "seatsavailability",
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter<IMessageSender>("seatsavailability"),
                    new ResolvedParameter<IPendingEventsQueue>("seatsavailability"),
                    new EventStoreBusPublisherInstrumentation("worker - seatsavailability", this.instrumentationEnabled)));

            var cache = new MemoryCache("RepositoryCache");

            container.RegisterType<IEventSourcedRepository<Order>, AzureEventSourcedRepository<Order>>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter<IEventStore>("orders"),
                    new ResolvedParameter<IEventStoreBusPublisher>("orders"),
                    typeof(ITextSerializer),
                    typeof(IMetadataProvider),
                    cache));

            container.RegisterType<IEventSourcedRepository<SeatAssignments>, AzureEventSourcedRepository<SeatAssignments>>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter<IEventStore>("orders"),
                    new ResolvedParameter<IEventStoreBusPublisher>("orders"),
                    typeof(ITextSerializer),
                    typeof(IMetadataProvider),
                    cache));

            container.RegisterType<IEventSourcedRepository<SeatsAvailability>, AzureEventSourcedRepository<SeatsAvailability>>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter<IEventStore>("seatsavailability"),
                    new ResolvedParameter<IEventStoreBusPublisher>("seatsavailability"),
                    typeof(ITextSerializer),
                    typeof(IMetadataProvider),
                    cache));

            // to satisfy the IProcessor requirements.
            container.RegisterInstance<IProcessor>(
                "OrdersEventStoreBusPublisher",
                new PublisherProcessorAdapter(container.Resolve<IEventStoreBusPublisher>("orders"), this.cancellationTokenSource.Token));
            container.RegisterInstance<IProcessor>(
                "SeatsAvailabilityEventStoreBusPublisher",
                new PublisherProcessorAdapter(container.Resolve<IEventStoreBusPublisher>("seatsavailability"), this.cancellationTokenSource.Token));
        }
コード例 #26
0
 public BalanceController(EventStore eventStore, ReadModel readModel)
 {
     _eventStore = eventStore;
     _readModel  = readModel;
 }
コード例 #27
0
        public virtual IAudienceState GetHistoryState(string clientId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IAudienceStateEvent), ToEventStoreAggregateId(clientId), version - 1);

            return(new AudienceState(eventStream.Events));
        }
コード例 #28
0
        public virtual IUserLoginMvoState GetHistoryState(UserLoginId userLoginId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IUserLoginMvoStateEvent), ToEventStoreAggregateId(userLoginId), version - 1);

            return(new UserLoginMvoState(eventStream.Events));
        }
コード例 #29
0
 public void EventAppeared(EventStore.Core.Data.ResolvedEvent resolvedEvent)
 {
     _eventAppeared(_subscription, new ResolvedEvent(resolvedEvent.ConvertToClientResolvedEvent()));
 }
コード例 #30
0
 public EventStoreBuilder()
 {
     _store = WithDefaults();
 }
コード例 #31
0
        public virtual IPartyState GetHistoryState(string partyId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IPartyEvent), ToEventStoreAggregateId(partyId), version - 1);

            return(new PartyState(eventStream.Events));
        }
コード例 #32
0
 /// <summary>
 /// 取消指定事件数据的所有处理器
 /// </summary>
 /// <param name="eventType">事件数据类型</param>
 public virtual void UnsubscribeAll(Type eventType)
 {
     EventStore.RemoveAll(eventType);
 }
コード例 #33
0
 public Exchange(EventStore <OrderPlaced> orderStore)
 {
     _orderStore = orderStore;
     _orderBook  = new OrderBook();
 }
コード例 #34
0
        /// <summary>
        /// 取消订阅指定事件数据的事件处理委托
        /// </summary>
        /// <typeparam name="TEventData">事件数据类型</typeparam>
        /// <param name="action">事件处理委托</param>
        public virtual void Unsubscribe <TEventData>(Action <TEventData> action) where TEventData : IEventData
        {
            Check.NotNull(action, nameof(action));

            EventStore.Remove(action);
        }
コード例 #35
0
        static partial void OnCreateContainer(UnityContainer container)
        {
            var serializer = new JsonTextSerializer();
            container.RegisterInstance<ITextSerializer>(serializer);
            var metadata = new StandardMetadataProvider();
            container.RegisterInstance<IMetadataProvider>(metadata);

            var instrumentationEnabled = CloudConfigurationManager.GetSetting("InstrumentationEnabled") == "true";

            // command bus

            var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml"));
            if (!Conference.Common.MaintenanceMode.IsInMaintainanceMode)
            {
                new ServiceBusConfig(settings.ServiceBus).Initialize();
            }
            var commandBus = new CommandBus(new TopicSender(settings.ServiceBus, "conference/commands"), metadata, serializer);

            var synchronousCommandBus = new SynchronousCommandBusDecorator(commandBus);

            container.RegisterInstance<ICommandBus>(synchronousCommandBus);
            container.RegisterInstance<ICommandHandlerRegistry>(synchronousCommandBus);

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(settings.BlobStorage.ConnectionString);
            container.RegisterInstance<IBlobStorage>(new CloudBlobStorage(blobStorageAccount, settings.BlobStorage.RootContainerName));

            // support for inline command processing

            container.RegisterType<ICommandHandler, OrderCommandHandler>("OrderCommandHandler");
            container.RegisterType<ICommandHandler, ThirdPartyProcessorPaymentCommandHandler>("ThirdPartyProcessorPaymentCommandHandler");
            container.RegisterType<ICommandHandler, SeatAssignmentsHandler>("SeatAssignmentsHandler");

            container.RegisterType<DbContext, PaymentsDbContext>("payments", new TransientLifetimeManager(), new InjectionConstructor("Payments"));
            container.RegisterType<IDataContext<ThirdPartyProcessorPayment>, SqlDataContext<ThirdPartyProcessorPayment>>(
                new TransientLifetimeManager(),
                new InjectionConstructor(new ResolvedParameter<Func<DbContext>>("payments"), typeof(IEventBus)));

            container.RegisterType<IPricingService, PricingService>(new ContainerControlledLifetimeManager());

            var topicSender = new TopicSender(settings.ServiceBus, "conference/events");
            container.RegisterInstance<IMessageSender>(topicSender);
            var eventBus = new EventBus(topicSender, metadata, serializer);

            container.RegisterInstance<IEventBus>(eventBus);

            var eventSourcingAccount = CloudStorageAccount.Parse(settings.EventSourcing.ConnectionString);
            var eventStore = new EventStore(eventSourcingAccount, settings.EventSourcing.OrdersTableName);

            container.RegisterInstance<IEventStore>(eventStore);
            container.RegisterInstance<IPendingEventsQueue>(eventStore);
            container.RegisterType<IEventStoreBusPublisher, EventStoreBusPublisher>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new TopicSender(settings.ServiceBus, "conference/eventsOrders"),
                    typeof(IPendingEventsQueue),
                    new EventStoreBusPublisherInstrumentation("web.public - orders", instrumentationEnabled)));
            container.RegisterType(
                typeof(IEventSourcedRepository<>),
                typeof(AzureEventSourcedRepository<>),
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(typeof(IEventStore), typeof(IEventStoreBusPublisher), typeof(ITextSerializer), typeof(IMetadataProvider), new InjectionParameter<ObjectCache>(null)));

            // to satisfy the IProcessor requirements.
            container.RegisterType<IProcessor, PublisherProcessorAdapter>("EventStoreBusPublisher", new ContainerControlledLifetimeManager());
        }
コード例 #36
0
        public virtual IOrderState GetHistoryState(string orderId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IOrderEvent), ToEventStoreAggregateId(orderId), version - 1);

            return(new OrderState(eventStream.Events));
        }
コード例 #37
0
        public virtual IPicklistItemMvoState GetHistoryState(PicklistBinPicklistItemId picklistBinPicklistItemId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IPicklistItemMvoEvent), ToEventStoreAggregateId(picklistBinPicklistItemId), version - 1);

            return(new PicklistItemMvoState(eventStream.Events));
        }
コード例 #38
0
 protected void SendPrerecordedEvent(
     EventStore.Core.Data.ResolvedEvent pair, CheckpointTag positionTag,
     long prerecordedEventMessageSequenceNumber)
 {
     var position = pair.OriginalEvent;
     var committedEvent = new ReaderSubscriptionMessage.CommittedEventDistributed(
         Guid.Empty,
         new ResolvedEvent(
             position.EventStreamId, position.EventNumber, pair.Event.EventStreamId, pair.Event.EventNumber,
             pair.Link != null, new TFPos(-1, position.LogPosition), new TFPos(-1, pair.Event.LogPosition),
             pair.Event.EventId, pair.Event.EventType, (pair.Event.Flags & PrepareFlags.IsJson) != 0,
             pair.Event.Data, pair.Event.Metadata, pair.Link == null ? null : pair.Link.Metadata, null,
             pair.Event.TimeStamp), null, -1, source: this.GetType());
     _publisher.Publish(
         EventReaderSubscriptionMessage.CommittedEventReceived.FromCommittedEventDistributed(
             committedEvent, positionTag, null, _projectionCorrelationId, 
             prerecordedEventMessageSequenceNumber));
 }
コード例 #39
0
        public virtual IGoodIdentificationTypeState GetHistoryState(string goodIdentificationTypeId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IGoodIdentificationTypeEvent), ToEventStoreAggregateId(goodIdentificationTypeId), version - 1);

            return(new GoodIdentificationTypeState(eventStream.Events));
        }
コード例 #40
0
        private void RegisterRepository(UnityContainer container)
        {
            // repository
            var eventSourcingAccount = CloudStorageAccount.Parse(this.azureSettings.EventSourcing.ConnectionString);
            var eventStore = new EventStore(eventSourcingAccount, this.azureSettings.EventSourcing.TableName);

            container.RegisterInstance<IEventStore>(eventStore);
            container.RegisterInstance<IPendingEventsQueue>(eventStore);
            container.RegisterInstance<IEventStoreBusPublisherInstrumentation>(new EventStoreBusPublisherInstrumentation("v3migration", this.instrumentationEnabled));
            container.RegisterType<IEventStoreBusPublisher, EventStoreBusPublisher>(new ContainerControlledLifetimeManager());
            var cache = new MemoryCache("RepositoryCache");
            container.RegisterType(
                typeof(IEventSourcedRepository<>),
                typeof(AzureEventSourcedRepository<>),
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(typeof(IEventStore), typeof(IEventStoreBusPublisher), typeof(ITextSerializer), typeof(IMetadataProvider), cache));

            // to satisfy the IProcessor requirements.
            container.RegisterInstance<IProcessor>("EventStoreBusPublisher", new PublisherProcessorAdapter(
                container.Resolve<IEventStoreBusPublisher>(), this.cancellationTokenSource.Token));
        }
コード例 #41
0
 /// <summary>
 /// Store a game that has been entered.
 /// Also updates the stats when done.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ButtonStore_Click(object sender, EventArgs e)
 {
     EventStore?.Invoke();
 }
コード例 #42
0
        public virtual IRejectionReasonState GetHistoryState(string rejectionReasonId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IRejectionReasonEvent), ToEventStoreAggregateId(rejectionReasonId), version - 1);

            return(new RejectionReasonState(eventStream.Events));
        }
コード例 #43
0
 /// <summary>
 /// 将命令事件持久化
 /// </summary>
 /// <param name="theEvent"></param>
 public void Store(EventStore theEvent)
 {
     _context.EventStore.Add(theEvent);
     _context.SaveChanges();
 }
コード例 #44
0
 private void EnqueueStreamForProcessing(EventStore.Core.Data.ResolvedEvent resolvedEvent)
 {
     //TODO: consider catalog referring to earlier written events (should we check here?)
     if (resolvedEvent.OriginalEvent.LogPosition > _limitingCommitPosition)
         return;
     var streamId = SystemEventTypes.StreamReferenceEventToStreamId(resolvedEvent.Event.EventType, resolvedEvent.Event.Data);
     _pendingStreams.Enqueue(streamId);
     _catalogNextSequenceNumber = resolvedEvent.OriginalEventNumber;
 }
 public async Task AppendAsync(EventStore @event)
 {
     await _dbSet.AddAsync(@event);
 }
コード例 #46
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterRoutes(RouteTable.Routes);

            var builder = new ContainerBuilder();

            builder.RegisterModule(new NHibernateSessionModule());

            //builder.RegisterModule(new ReportingSessionModule());

            builder.RegisterModule(new QueryModule());

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            var container = builder.Build();

            _container = container;

            QueryModule._container = _container;

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var rabbitMQPublisher = new RabbitMQPublisher(System.Configuration.ConfigurationManager.AppSettings["CLOUDAMQP_URL"]);

            //Use RabbitMQ
            //var commandBus = new CommandBus(rabbitMQPublisher);

            var commandBus = new CommandBus();

            var eventStore = new EventStore(commandBus, container.Resolve<ISessionFactory>());

            //Context
            var transferMoneyContext = new TransferMoneyContext(eventStore);
            var createBankAccountContext = new CreateBankAccountContext(eventStore);
            var changeAccountAndBalanceContext = new ChangeAccountNameAndBalanceContext(eventStore);
            var createCustomerContext = new CreateCustomerContext(eventStore);
            var addCustomerAddressContext = new AddCustomerAddressContext(eventStore);
            var stockNewProductContext = new StockNewProductContext(eventStore);
            var placeOrderContext = new PlaceOrderContext(eventStore);

            //Register Command
            commandBus.RegisterHandlerCommand<OpenAccountCommand>(createBankAccountContext.Handle);
            commandBus.RegisterHandlerCommand<TransferMoneyCommand>(transferMoneyContext.Handle);
            commandBus.RegisterHandlerCommand<ChangeAccountNameAndBalanceCommand>(changeAccountAndBalanceContext.Handle);
            commandBus.RegisterHandlerCommand<CreateCustomerCommand>(createCustomerContext.Handle);
            commandBus.RegisterHandlerCommand<AddCustomerAddressCommand>(addCustomerAddressContext.Handle);
            commandBus.RegisterHandlerCommand<CreateProductCommand>(stockNewProductContext.Handle);
            commandBus.RegisterHandlerCommand<PlaceOrderCommand>(placeOrderContext.Handle);

            //Report View
            var accountReportView = new AccountReportView(container.Resolve<ISessionFactory>());

            //Register Event
            commandBus.RegisterHandlerEvent<AccountCreatedEvent>(accountReportView.Handle);
            commandBus.RegisterHandlerEvent<AccountNameAndBalanceChangedEvent>(accountReportView.Handle);
            commandBus.RegisterHandlerEvent<BalanceDecreasedEvent>(accountReportView.Handle);
            commandBus.RegisterHandlerEvent<BalanceIncreasedEvent>(accountReportView.Handle);

            //Report View
            var customerReportView = new CustomerReportView(container.Resolve<ISessionFactory>());

            //Register Event
            commandBus.RegisterHandlerEvent<CustomerCreatedEvent>(customerReportView.Handle);
            commandBus.RegisterHandlerEvent<CustomerAddressAddedEvent>(customerReportView.Handle);

            var placeOrderView = new PlaceOrderView(container.Resolve<ISessionFactory>());

            commandBus.RegisterHandlerEvent<OrderPlacedEvent>(placeOrderView.Handle);

            var productStockReportView = new ProductStockReportView(container.Resolve<ISessionFactory>());

            commandBus.RegisterHandlerEvent<ProductCreatedEvent>(productStockReportView.Handle);

            //ServiceLocator.Pub = rabbitMQPublisher;
            ServiceLocator.Bus = commandBus;
            //ServiceLocator.Sub = rabbitMQSubsriber;
        }
コード例 #47
0
 protected void SendPrerecordedEvent(
     EventStore.Core.Data.ResolvedEvent pair, CheckpointTag positionTag,
     long prerecordedEventMessageSequenceNumber)
 {
     var committedEvent = new ReaderSubscriptionMessage.CommittedEventDistributed(
         Guid.Empty, new ResolvedEvent(pair, null), null, -1, source: this.GetType());
     _publisher.Publish(
         EventReaderSubscriptionMessage.CommittedEventReceived.FromCommittedEventDistributed(
             committedEvent, positionTag, null, _projectionCorrelationId, 
             prerecordedEventMessageSequenceNumber));
 }
コード例 #48
0
        private void RegisterRepository(UnityContainer container)
        {
            // repository
            var eventSourcingAccount = CloudStorageAccount.Parse(this.azureSettings.EventSourcing.ConnectionString);
            var eventStore = new EventStore(eventSourcingAccount, this.azureSettings.EventSourcing.TableName);

            container.RegisterInstance<IEventStore>(eventStore);
            container.RegisterInstance<IPendingEventsQueue>(eventStore);
            container.RegisterType<IEventStoreBusPublisher, EventStoreBusPublisher>(new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(IEventSourcedRepository<>), typeof(AzureEventSourcedRepository<>), new ContainerControlledLifetimeManager());

            // to satisfy the IProcessor requirements.
            container.RegisterInstance<IProcessor>("EventStoreBusPublisher", new PublisherProcessorAdapter(
                container.Resolve<IEventStoreBusPublisher>(), this.cancellationTokenSource.Token));
        }
コード例 #49
0
 public BuyOrderCreatedHandler(EventStore eventStore) =>
 protected void SendPrerecordedEvent(
     EventStore.Core.Data.ResolvedEvent pair, CheckpointTag positionTag, long prerecordedEventMessageSequenceNumber)
 {
     var position = pair.OriginalEvent;
     var committedEvent = new ProjectionCoreServiceMessage.CommittedEventDistributed(
         Guid.Empty, default(EventPosition), position.EventStreamId, position.EventNumber,
         pair.Event.EventStreamId, pair.Event.EventNumber, pair.Link != null,
         ResolvedEvent.Create(
             pair.Event.EventId, pair.Event.EventType, (pair.Event.Flags & PrepareFlags.IsJson) != 0,
             pair.Event.Data, pair.Event.Metadata, pair.Event.TimeStamp), null, -1);
     _coreProjection.Handle(
         ProjectionSubscriptionMessage.CommittedEventReceived.FromCommittedEventDistributed(
             committedEvent, positionTag, null, Guid.Empty, prerecordedEventMessageSequenceNumber));
 }
コード例 #51
0
        static void Main(string[] args)
        {
            var ex = new StockExchangeProvider();

            using (var es = new EventStore("eventstream.db"))
                using (var msgpump = new MessagePump(es)) {
                    IMessageContextManager mcm;
                    IMessageProcessor      mp;

                    mcm = new BuyStockCommandContextManager();
                    mp  = new BuyStockCommandProcessor();
                    msgpump.Register <BuyStockCommand>(mcm, mp);

                    mcm = new SellStockCommandManager(es);
                    mp  = new SellStockCommandProcessor();
                    msgpump.Register <SellStockCommand>(mcm, mp);

                    mcm = new UpdatePortfolioCommandContextManager(es);
                    mp  = new UpdatePortfolioCommandProcessor(ex);
                    msgpump.Register <UpdatePortfolioCommand>(mcm, mp);

                    mcm = new CandidateStocksQueryContextManager();
                    mp  = new CandidateStocksQueryProcessor(ex);
                    msgpump.Register <CandidateStocksQuery>(mcm, mp);

                    mcm = new PortfolioQueryContextManager(es);
                    mp  = new PortfolioQueryProcessor();
                    msgpump.Register <PortfolioQuery>(mcm, mp);

                    mcm = new PortfolioStockQueryContextManager(es);
                    mp  = new PortfolioStockQueryProcessor();
                    msgpump.Register <PortfolioStockQuery>(mcm, mp);

                    var frontend = new UserInterface();


                    frontend.OnPortfolioQuery += q => {
                        var result = msgpump.Handle(q) as PortfolioQueryResult;
                        frontend.Display(result);
                    };

                    frontend.OnUpdatePortfolioCommand += c => {
                        msgpump.Handle(c);
                        var result = msgpump.Handle(new PortfolioQuery()) as PortfolioQueryResult;
                        frontend.Display(result);
                    };

                    frontend.OnCandidateStocksQuery += q => {
                        var result = msgpump.Handle(q) as CandidateStocksQueryResult;
                        if (frontend.SelectStockToBuy(result, out var cmd))
                        {
                            msgpump.Handle(cmd);
                            frontend.DisplayBuyConfirmation(cmd.StockSymbol, cmd.Qty, cmd.StockPrice);
                        }
                    };

                    frontend.OnPortfolioStockQuery += q => {
                        var result = msgpump.Handle(q) as PortfolioStockQueryResult;
                        if (frontend.SelectStockToSell(result, out var cmd))
                        {
                            msgpump.Handle(cmd);
                            frontend.DisplaySellConfirmation(cmd.StockSymbol);
                        }
                    };


                    frontend.Run();
                }
        }
コード例 #52
0
 public AuftragRepository(Guid aggregateId, EventStore store)
     : base(aggregateId, store)
 {
 }
コード例 #53
0
ファイル: EventManager.cs プロジェクト: st9007a/little-rpg
 void Awake()
 {
     store          = EventStore.getDefault();
     currentEventId = 0;
 }
コード例 #54
0
        public virtual IWarehouseState GetHistoryState(string warehouseId, long version)
        {
            var eventStream = EventStore.LoadEventStream(typeof(IWarehouseEvent), ToEventStoreAggregateId(warehouseId), version - 1);

            return(new WarehouseState(eventStream.Events));
        }
コード例 #55
0
 /// <summary>
 /// 取消订阅指定事件数据的事件处理对象
 /// </summary>
 /// <param name="eventType">事件数据类型</param>
 /// <param name="eventHandler">事件处理对象</param>
 public virtual void Unsubscribe(Type eventType, IEventHandler eventHandler)
 {
     EventStore.Remove(eventType, eventHandler);
     Logger.LogDebug($"移除事件“{eventType}”到处理器“{eventHandler.GetType()}”的订阅配对");
 }
 public void SetLoadedEvent(EventStore.Core.Data.ResolvedEvent eventLinkPair)
 {
     _result = eventLinkPair;
 }
コード例 #57
0
 /// <summary>
 /// 订阅指定事件数据的事件处理类型
 /// </summary>
 /// <typeparam name="TEventData">事件数据类型</typeparam>
 /// <typeparam name="TEventHandler">事件处理器类型</typeparam>
 public virtual void Subscribe <TEventData, TEventHandler>() where TEventData : IEventData where TEventHandler : IEventHandler, new()
 {
     EventStore.Add <TEventData, TEventHandler>();
 }
コード例 #58
0
ファイル: Program.cs プロジェクト: MoimHossain/event-sourcing
        private static async Task UseStreamApi(Tenant tenant, Guid aggregateID, string streamName, EventStore eventStore)
        {
            var stream = await eventStore.GetStreamAsync(tenant, streamName);

            var version = await stream.GetCurrentVersionAsync(aggregateID);

            await stream.EmitEventsAsync(aggregateID, version, new List <EventBase>
            {
                new SampleEvent {
                    Desc = "Event 1"
                },
                new SampleEvent {
                    Desc = "Event 2"
                }
            }, CancellationToken.None);
        }
コード例 #59
0
 public void SetUp()
 {
     Target = new EventStore(DbContext);
 }
コード例 #60
0
ファイル: Program.cs プロジェクト: MoimHossain/event-sourcing
        private static async Task UseTxApi(Tenant tenant, Guid aggregateID, string streamName, EventStore eventStore)
        {
            await eventStore.ExecuteInTransactionAsync(tenant, streamName, aggregateID, async (tx) =>
            {
                tx.AddEvent(new SampleEvent {
                    Desc = "Event 3"
                });
                // Do somthing else
                tx.AddEvent(new SampleEvent {
                    Desc = "Event 4"
                });

                tx.AddEvents(new List <EventBase>            {
                    new SampleEvent {
                        Desc = "Event 5"
                    },
                    new SampleEvent {
                        Desc = "Event 6"
                    }
                });

                await Task.CompletedTask;
            });
        }