public void EventStoreTest() { var log = MockRepository.GenerateMock <ILog>(); var eventStoreConnection = EventStoreConnection.Create(ConnectionSettings.Default, new IPEndPoint(IPAddress.Loopback, 1113)); eventStoreConnection.Connect(); using (var engine = new InMemoryCqrsEngine( LocalBoundedContext.Named("local") .PublishingEvents(typeof(int), typeof(TestAggregateRootNameChangedEvent), typeof(TestAggregateRootCreatedEvent)) .To("events") .RoutedTo("events") .ListeningCommands(typeof(string)).On("commands1").RoutedFromSameEndpoint() .WithCommandsHandler <CommandHandler>() .WithProcess <TestProcess>() .WithEventStore(dispatchCommits => Wireup.Init() .LogTo(type => log) .UsingInMemoryPersistence() .InitializeStorageEngine() .UsingJsonSerialization() .UsingSynchronousDispatchScheduler() .DispatchTo(dispatchCommits)) )) { engine.SendCommand("test", "local"); Thread.Sleep(500); Console.WriteLine("Disposing..."); } Console.WriteLine("Dispose completed."); }
public void ReplayEventsTest(Type[] types, int expectedReplayCount) { var log = MockRepository.GenerateMock <ILog>(); var eventsListener = new EventsListener(); var localBoundedContext = LocalBoundedContext.Named("local") .PublishingEvents(typeof(TestAggregateRootNameChangedEvent), typeof(TestAggregateRootCreatedEvent)).To("events").RoutedTo("events") .ListeningCommands(typeof(string)).On("commands").RoutedFromSameEndpoint() .ListeningInfrastructureCommands().On("commands").RoutedFromSameEndpoint() .WithCommandsHandler <EsCommandHandler>() .WithEventStore(dispatchCommits => Wireup.Init() .LogTo(type => log) .UsingInMemoryPersistence() .InitializeStorageEngine() .UsingJsonSerialization() .UsingSynchronousDispatchScheduler() .DispatchTo(dispatchCommits)); using ( var engine = new InMemoryCqrsEngine(localBoundedContext, LocalBoundedContext.Named("projections").WithProjection(eventsListener, "local"))) { var guid = Guid.NewGuid(); engine.SendCommand(guid + ":create", "local"); engine.SendCommand(guid + ":changeName:newName", "local"); Thread.Sleep(2000); //engine.SendCommand(new ReplayEventsCommand { Destination = "events", From = DateTime.MinValue }, "local"); engine.ReplayEvents("local", types); Thread.Sleep(2000); Console.WriteLine("Disposing..."); } Assert.That(eventsListener.Handled.Count, Is.EqualTo(2 + expectedReplayCount), "Wrong number of events was replayed"); }
public RepositoryScenarioBuilder() { _eventStore = Wireup.Init().UsingInMemoryPersistence().Build(); _unitOfWork = new UnitOfWork(); _eventStoreSchedule = new List <Action <IStoreEvents> >(); _unitOfWorkSchedule = new List <Action <UnitOfWork> >(); }
protected override Task Context() { HandleFunction = c => PollingClient2.HandlingResult.MoveToNext; _storeEvents = Wireup.Init().UsingInMemoryPersistence().Build(); sut = new PollingClient2(_storeEvents.Advanced, c => HandleFunction(c), PollingInterval); return(Task.CompletedTask); }
public async Task EnsureSchemaInitialized() { // `receptionDelay` should include transaction timeout + clock drift. Otherwise, it may skip events during reception. var receptionDelay = TimeSpan.FromMilliseconds(3000); var eventStore = Wireup.Init() .UsingSqlPersistence(ConnectionString) .WithDialect(new PostgreSqlDialect()) .InitializeStorageEngine() .UsingJsonSerialization() .Build(); eventStore.Advanced.Purge(); _eventStore = eventStore; Outbox = new NEventStoreOutbox(eventStore, receptionDelay); var db = new TestDbContextWithOutbox(ConnectionString, Outbox); db.Database.CreateIfNotExists(); // Warm-up for (int i = 0; i < 2; i++) { using var warmUpDb = NewDbContext(); warmUpDb.Users.Add(new UserAggregate(Guid.NewGuid(), "")); await warmUpDb.SaveChangesAsync(); } }
public void SimpleAggregateSnapshottingViaSnapshotCreatorAndConcreteAggregateFactory() { IStoreEvents memoryStore = Wireup.Init().UsingInMemoryPersistence().Build(); IConstructAggregates aggregateFactory = new AggregateFactory(); IEventStoreRepository repository = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector()); Guid aggregateID = Guid.NewGuid(); SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now); repository.Save(aggregate, Guid.NewGuid()); aggregate.Version.Should().Be(1); SnapshotCreator <SimpleAggregate> snapshotCreator = new SnapshotCreator <SimpleAggregate>(repository, 1); ISnapshot snapshot = snapshotCreator.SaveSnapShot(aggregate.Id); ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue); retrievedSnapshot.Should().NotBeNull(); retrievedSnapshot.StreamRevision.Should().Be(1); retrievedSnapshot.ShouldBeEquivalentTo(snapshot); SimpleAggregate retrievedAggregate = repository.GetById <SimpleAggregate>(aggregate.Id); retrievedAggregate.Should().NotBeNull(); aggregate.Version.Should().Be(1); retrievedAggregate.ShouldBeEquivalentTo(aggregate); }
public IStoreEvents BuildEventStore( string connectionString, IPipelineHook[] hooks = null, Boolean useSyncDispatcher = false, MongoPersistenceOptions mongoPersistenceOptions = null) { mongoPersistenceOptions = mongoPersistenceOptions ?? new MongoPersistenceOptions() { }; Wireup es = Wireup.Init() .LogTo(t => new NEventStoreLog4NetLogger(_loggerFactory.Create(t))) .UsingMongoPersistence( () => connectionString, new DocumentObjectSerializer(), mongoPersistenceOptions ) .InitializeStorageEngine(); UseSyncDispatcher = useSyncDispatcher; if (hooks != null) { es.HookIntoPipelineUsing(hooks); } return(es.Build()); }
public EventUnwinder( ProjectionEngineConfig config, ILogger logger) { _config = config; _logger = logger; _eventStore = Wireup .Init() .LogTo(t => new NEventStoreLog4NetLogger(_logger)) .UsingMongoPersistence(() => _config.EventStoreConnectionString, new DocumentObjectSerializer()) .InitializeStorageEngine() .Build(); var url = new MongoUrl(_config.EventStoreConnectionString); var client = new MongoClient(url); _mongoDatabase = client.GetDatabase(url.DatabaseName); _persistStream = _eventStore.Advanced; _unwindedEventCollection = _mongoDatabase.GetCollection <UnwindedDomainEvent>("UnwindedEvents"); _unwindedEventCollection.Indexes.CreateOne( Builders <UnwindedDomainEvent> .IndexKeys .Ascending(ude => ude.CheckpointToken) .Ascending(ude => ude.EventSequence) .Ascending(ude => ude.EventType), new CreateIndexOptions() { Name = "ScanPrimary" } ); }
static void Main(string[] args) { ConnectionString = ConfigurationManager.AppSettings["connectionString"]; var config = new ConfigurationConnectionFactory("NEventStoreProc", "system.data.sqlclient", ConnectionString); InvoiceProjectionSetup.CreateSchemaIfNotExists(); StoreEvents = Wireup.Init() .UsingSqlPersistence((config)) .WithDialect(new MsSqlDialect()) .EnlistInAmbientTransaction() .InitializeStorageEngine() .UsingJsonSerialization() .Build(); _invoicesProjection = new InvoicesProjection(); _invoicesProjection.Init(); var baseAddress = "http://localhost:9000/"; // Start OWIN host using (WebApp.Start(baseAddress, Configuration)) { Console.WriteLine("Host started"); Console.ReadLine(); } _invoicesProjection.Dispose(); }
public async Task EnsureSchemaInitialized() { // `receptionDelay` should include transaction timeout + clock drift. Otherwise, it may skip events during reception. var receptionDelay = TimeSpan.FromMilliseconds(3000); var eventStore = Wireup.Init() .UsingSqlPersistence(NpgsqlFactory.Instance, ConnectionString) .WithDialect(new PostgreSqlDialect()) .UsingJsonSerialization() .Build(); _eventStore = eventStore; Outbox = new NEventStoreOutbox(eventStore, receptionDelay); var options = new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options; var db = new TestDbContextWithOutbox(options, Outbox); try { _ = db.Users.FirstOrDefault(); } catch (PostgresException) { await db.Database.EnsureDeletedAsync(); await db.Database.EnsureCreatedAsync(); } eventStore.Advanced.Initialize(); eventStore.Advanced.Purge(); }
static void Main(string[] args) { Console.Title = "Case00022492.Host"; var store = Wireup.Init() .UsingInMemoryPersistence() .EnlistInAmbientTransaction() .NES() .Build(); var busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Case00022492.Host"); busConfiguration.Case00022492CommonConfig(); busConfiguration.RegisterComponents(c => { c.ConfigureComponent <Repository>(DependencyLifecycle.InstancePerUnitOfWork); c.RegisterSingleton(store); }); using (var bus = Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
private App() { var settings = new DefaultHandlerSettings( new HandlerModule(), new DefaultRequestTypeResolver("cedar", Enumerable.Empty <Type>())); var commitDispatcherFailed = new TaskCompletionSource <Exception>(); //MidFunc blah = CommandHandlingMiddleware.HandleCommands(settings); //_middleware = CreateGate(commitDispatcherFailed.Task) _middleware = CommandHandlingMiddleware.HandleCommands(settings); _storeEvents = Wireup.Init().UsingInMemoryPersistence().Build(); var eventStoreClient = new EventStoreClient(_storeEvents.Advanced); _durableCommitDispatcher = new DurableCommitDispatcher( eventStoreClient, new InMemoryCheckpointRepository(), new HandlerModule(), TransientExceptionRetryPolicy.Indefinite(TimeSpan.FromMilliseconds(500))); _durableCommitDispatcher.ProjectedCommits.Subscribe( _ => { }, commitDispatcherFailed.SetResult); _durableCommitDispatcher.Start().Wait(); }
public void SimpleAggregateSnapshottingViaSnapshotCreator() { IStoreEvents memoryStore = Wireup.Init().UsingInMemoryPersistence().Build(); IConstructAggregates aggregateFactory = A.Fake <IConstructAggregates>(); IEventStoreRepository repository = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector()); Guid aggregateID = Guid.NewGuid(); SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now); repository.Save(aggregate, Guid.NewGuid()); A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, null)).ReturnsLazily(() => new SimpleAggregate()); SnapshotCreator <SimpleAggregate> snapshotCreator = new SnapshotCreator <SimpleAggregate>(repository, 1); Snapshot snapshot = snapshotCreator.SaveSnapShot(aggregate.Id); A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once); ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue); A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once); retrievedSnapshot.Should().NotBeNull(); retrievedSnapshot.StreamRevision.Should().Be(1); retrievedSnapshot.ShouldBeEquivalentTo(snapshot); SimpleAggregate retrievedAggregate = repository.GetById <SimpleAggregate>(aggregate.Id); retrievedAggregate.Should().NotBeNull(); aggregate.Version.Should().Be(1); retrievedAggregate.ShouldBeEquivalentTo(aggregate); A.CallTo(aggregateFactory).Where(o => o.Method.Name != "Build").MustNotHaveHappened(); A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.Not.IsNull())).MustHaveHappened(); }
private IStoreEvents WireupEventStore() { //register the class map var type = typeof(IEvent); var types = Assembly.GetAssembly(typeof(IEvent)) .GetTypes() .Where(t => type.IsAssignableFrom(t)) .Where(t => t.IsClass); foreach (var t in types) { BsonClassMap.LookupClassMap(t); } // initialize the eventstore return(Wireup.Init() .LogToOutputWindow() .UsingMongoPersistence("EventStore", new DocumentObjectSerializer()) .InitializeStorageEngine() .UsingJsonSerialization() .Compress() .UsingSynchronousDispatchScheduler() .DispatchTo(new NServiceBusCommitDispatcher <IEvent>()) .Build()); }
protected TestIntegration() { LoggerFactory.Create = type => new Mock <ILogger>().Object; this.Repository = new Repository(); DI.Current.Register(() => this.Repository); var busMock = new Mock <IManageMessageHeaders>().As <IBus>(); busMock.As <IManageMessageHeaders>().SetupGet(b => b.SetHeaderAction).Returns((o, s, arg3) => { }); busMock.Setup(b => b.CurrentMessageContext).Returns(new MessageContext(new TransportMessage())); busMock.Setup(b => b.OutgoingHeaders).Returns(new Dictionary <string, string>()); global::NServiceBus.ExtensionMethods.CurrentMessageBeingHandled = new Mock <ICommand>().Object; DI.Current.Register(() => busMock.Object); var commandContextProvider = new CommandContextProvider(busMock.Object); StoreEvents = Wireup.Init().UsingInMemoryPersistence().InitializeStorageEngine().NES().Build(); DI.Current.Register <ICommandContextProvider>(() => commandContextProvider); DI.Current.Register <IEventPublisher, IBus>(bus => new BusAdapter(bus)); }
public async Task InitializeAndWarmUp() { var eventStore = Wireup.Init() .UsingSqlPersistence(SqlClientFactory.Instance, ConnectionString) .WithDialect(new MsSqlDialect()) .UsingJsonSerialization() .Build(); _outbox = new NEventStoreOutbox(eventStore, TimeSpan.Zero); var options = new DbContextOptionsBuilder().UseSqlServer(ConnectionString).Options; var db = new TestDbContextWithOutbox(options, _outbox); try { _ = db.Users.FirstOrDefault(); } catch (SqlException) { await db.Database.EnsureDeletedAsync(); await db.Database.EnsureCreatedAsync(); } eventStore.Advanced.Initialize(); await WarmUp(); }
protected override void Load(ContainerBuilder builder) { //mongodb read model builder.Register(context => { var mongoServer = MongoServer.Create( ConfigurationManager.ConnectionStrings["mongoReadModelConnectionString"].ConnectionString); return(mongoServer.GetDatabase("wf1_read_model", SafeMode.True)); }) .AsSelf() .SingleInstance(); //eventstore builder.Register(context => Wireup.Init() //.LogTo(type => new EventStoreLog4NetLogger(type)) .LogTo(type => new Log4NetLogger(type)) //- need to get assembly redirection working .UsingMongoPersistence("mongoEventStoreConnectionString", new DocumentObjectSerializer()) .Build()) .As <IStoreEvents>() .SingleInstance(); //do assembly scanning for all event handlers builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ElectionCreatedEventHandler))) .Where(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(Handles <>)))) .AsImplementedInterfaces(); RegisterEventTypesWithMongo(); }
private void Run() { using (var store = Wireup.Init().UsingInMemoryPersistence().Build()) { var eventBus = Substitute.For <IEventBus>(); if (!command.IsFirstCommand) { using (var stream = store.CreateStream(command.CommandId)) { initialEvents.Select(x => new EventMessage { Body = x }).ToList().ForEach(stream.Add); stream.CommitChanges(Guid.NewGuid()); } } var bus = new CommandBus(new EventStoreCommandHandler(store, eventBus)); bus.Subscribe(PriceAggregate.Handle); bus.Publish(command); using (var stream = store.OpenStream(command.CommandId)) { Check.That(stream.CommittedEvents.Select(x => x.Body).Cast <Event>()).Contains(resultingEvents); } } }
internal static IStoreEvents CreateMemoryConnection() { return(Wireup.Init() .UsingInMemoryPersistence() .InitializeStorageEngine() .Build()); }
private IStoreEvents getInitializedEventStore(IDispatchCommits dispatchCommits) { return(Wireup.Init() .UsingRavenPersistence("Raven") .UsingSynchronousDispatchScheduler(dispatchCommits) .Build()); }
public virtual void Init() { ioc = new DictionaryBasedDependencyResolver(); IdGenerator = new IdGeneratorMock(); var wireup = Wireup.Init() .UsingInMemoryPersistence() .UsingJsonSerialization() .UsingEventUpconversion() .WithConvertersFrom(appAssemblies) .UsingSynchronousDispatchScheduler() .UsingCqrs(ioc).WithAggregateFactory(_ => new AggregateFactoryHeaderBased(appAssemblies)); wireup.Hook(innerIoc => { eventBus = new PublishedEventSniffer(innerIoc.Resolve <IEventBus>()); innerIoc.Register <IIdGenerator>(IdGenerator); innerIoc.Register <IEventBus>(eventBus); innerIoc.Register <ICheckpointStore>(new CheckpointStoreMock()); innerIoc.Register <IPersistStreams>(new InMemoryPersistenceEngineWithSerialization(innerIoc.Resolve <ISerialize>())); innerIocLocal = innerIoc; }); OnConfigure(ioc, innerIocLocal); wireup.Build(); }
/// <summary> /// Lazily initialize the event storage engine. depending on the type of persistence engine /// desired, this will create the persistence layer. /// </summary> /// <returns></returns> protected virtual void LazyInit(ref IStoreEvents storeEventsInstance, object lockObject) { if (storeEventsInstance == null) { lock (lockObject) { if (storeEventsInstance == null) { NEventStore.Logging.LogFactory.BuildLogger = (x) => new NLogLogger(x); var wireup = Wireup.Init(); if (_repositoryType == eRepositoryType.AzureBlob) { wireup = WireupAzureBlobRepository(wireup); } else if (_repositoryType == eRepositoryType.Sql) { wireup = WireupSqlServerRepository(wireup); } else { throw new Exception("unknown repository type"); } storeEventsInstance = wireup .UsingSynchronousDispatchScheduler() .DispatchTo(new DelegateMessageDispatcher(DispatchCommit)) .Build(); } } } }
private static IStoreEvents WireupEventStore() { //return Wireup.Init() // .LogToOutputWindow() // .UsingInMemoryPersistence() // .UsingSqlPersistence("EventStore") // Connection string is in app.config // .WithDialect(new MsSqlDialect()) // .EnlistInAmbientTransaction() // two-phase commit // .InitializeStorageEngine() // .TrackPerformanceInstance("example") // .UsingJsonSerialization() // .Compress() // .EncryptWith(EncryptionKey) // .HookIntoPipelineUsing(new[] { new AuthorizationPipelineHook() }) // .UsingSynchronousDispatchScheduler() // .DispatchTo(new DelegateMessageDispatcher(DispatchCommit)) // .Build(); return(Wireup.Init() .LogToOutputWindow() .UsingInMemoryPersistence() .UsingSqlPersistence("EventStoreDB") .WithDialect(new MsSqlDialect()) .EnlistInAmbientTransaction() .InitializeStorageEngine() // .UsingJsonSerialization() .Build()); }
public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component.For <IBus, IDispatchCommits>().ImplementedBy <InMemoryBus>().LifestyleSingleton()); container.Register( Classes .FromAssemblyContaining <ToDoEventsConverters>() .BasedOn(typeof(IUpconvertEvents <,>)) // That implement ICommandHandler Interface .WithService.Base() .LifestyleTransient()); //#region Work-Around for Event-Upconverion with SynchronousDispatchScheduler //IDictionary<Type, Func<object, object>> _registered = new Dictionary<Type, Func<object, object>>(); //var converter = new ToDoEventsConverters(); //_registered[typeof (AddedNewToDoItemEvent_V0)] = @event => converter.Convert(@event as AddedNewToDoItemEvent_V0); //// Workaround for Events Up-conversion. InMemoryBus is injected with EventUpconverterPipelineHook instance. ////container.Register(Component.For<EventUpconverterPipelineHook>().Instance(new EventUpconverterPipelineHook(_registered))); //#endregion _store = Wireup .Init() .LogToOutputWindow() .UsingInMemoryPersistence() .UsingSqlPersistence("EventStore") // Connection string is in web.config .WithDialect(new MsSqlDialect()) //.UsingJsonSerialization() .UsingNewtonsoftJsonSerialization(new VersionedEventSerializationBinder()) // Compress Aggregate serialization. Does NOT allow to do a SQL-uncoding of varbinary Payload // Comment if you need to decode message with CAST([Payload] AS VARCHAR(MAX)) AS [Payload] (on some VIEW) //.Compress() .UsingSynchronousDispatchScheduler() .DispatchTo(container.Resolve <IDispatchCommits>()) .Startup(DispatcherSchedulerStartup.Explicit) //// DOES NOT WORK WITH SynchronousDispatchScheduler .UsingEventUpconversion() .WithConvertersFromAssemblyContaining(new Type[] { typeof(ToDoEventsConverters) }) // .AddConverter<AddedNewToDoItemEvent_V0, AddedNewToDoItemEvent>(new ToDoEventsConverters()) //.HookIntoPipelineUsing(new EventUpconverterPipelineHook(_registered)) //.WithConvertersFromAssemblyContaining(new Type[]{typeof(ToDoEventsConverters)}) .Build(); _store.StartDispatchScheduler(); //wireup.AddConverter(new ToDoEventsConverters()); //_store = wireup.Build(); container.Register( Component.For <IStoreEvents>().Instance(_store), Component.For <IRepository>().ImplementedBy <EventStoreRepository>().LifeStyle.Transient, Component.For <IConstructAggregates>().ImplementedBy <AggregateFactory>().LifeStyle.Transient, Component.For <IDetectConflicts>().ImplementedBy <ConflictDetector>().LifeStyle.Transient); //// Elegant way to write the same Registration as before: //container.Register( // Component.For<IStoreEvents>().Instance(_store), // C<IRepository, EventStoreRepository>(), // C<IConstructAggregates, AggregateFactory>(), // C<IDetectConflicts, ConflictDetector>()); }
public void Start() { Wireup.Init() .UsingInMemoryPersistence() .NES() .Build(); }
private void CreateEventStore() { _eventStore = Wireup.Init() .UsingMongoPersistence(_eventStoreConnectionString, new DocumentObjectSerializer()) .InitializeStorageEngine() .UsingSynchronousDispatchScheduler(new CommitsDispatcher(_simpleMessageQueue)) .Build(); }
private IStoreEvents InitialMongo(string connString) { return(Wireup.Init() .UsingMongoPersistence(connString, new DocumentObjectSerializer()) .InitializeStorageEngine() .UsingJsonSerialization() .Build()); }
public void Start() { Wireup.Init() .UsingInMemoryPersistence() .EnlistInAmbientTransaction() .NES() .Build(); }
public static IStoreEvents Create() { return(Wireup.Init() .UsingInMemoryPersistence() .InitializeStorageEngine() .UsingJsonSerialization() .Build()); }
public void Start() { _store = Wireup.Init() .UsingInMemoryPersistence() .InitializeStorageEngine() .UsingSynchronousDispatchScheduler(_dispatcher) .Build(); }