private Task EventAppeared(EventStoreSubscription eventStorePersistentSubscriptionBase, ResolvedEvent resolvedEvent) { var @event = resolvedEvent.Event; if (@event == null || [email protected]) { return(Task.FromResult(0)); } var eventName = resolvedEvent.Event.EventStreamId; var jsonBytes = resolvedEvent.Event.Data; var eventId = resolvedEvent.Event.EventId; var events = _subscriptionConfiguration.SubscribedEvents; if (events.All(q => q.Key != eventName)) { return(Task.FromResult(0)); } var eventContext = new EventStoreContext(eventId, eventName, resolvedEvent, string.Empty, events, _container); _projectorInvoker.Invoke(eventContext); return(Task.FromResult(0)); }
internal ReadQueryContentCommand(EventStoreContext context, QueryETag etag) { _context = context; _etag = etag; _stream = etag.Key.GetCheckpointStream(); }
public void EventStoreContext_ConnectToSubscription_ConnectException_ErrorThrown() { EventStorePersistentSubscription result = null; EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); connection.Setup(c => c.ConnectToPersistentSubscriptionAsync(It.IsAny <String>(), It.IsAny <String>(), It.IsAny <Func <EventStorePersistentSubscriptionBase, ResolvedEvent, Int32?, Task> >(), It.IsAny <Action <EventStorePersistentSubscriptionBase, SubscriptionDropReason, Exception> >(), It.IsAny <UserCredentials>(), It.IsAny <Int32>(), It.IsAny <Boolean>())) .Throws(new Exception("Error", new Exception("Some nasty error"))); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; PaymentCentric.Logging.Logger.Initialise(NullLogger.Instance); EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); Should.Throw <Exception>(async() => { await context.ConnectToSubscription(EventStoreContextTestData.StreamName, EventStoreContextTestData.GroupName, EventStoreContextTestData.PersistentSubscriptionId, EventStoreContextTestData.BufferSize); }); }
public async Task EventStoreContext_ConnectToSubscription_ExisitngSubscription_ConnectionMade() { EventStorePersistentSubscription result = null; EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); connection.Setup(c => c.ConnectToPersistentSubscriptionAsync(It.IsAny <String>(), It.IsAny <String>(), It.IsAny <Func <EventStorePersistentSubscriptionBase, ResolvedEvent, Int32?, Task> >(), It.IsAny <Action <EventStorePersistentSubscriptionBase, SubscriptionDropReason, Exception> >(), It.IsAny <UserCredentials>(), It.IsAny <Int32>(), It.IsAny <Boolean>())) .ReturnsAsync(result); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; PaymentCentric.Logging.Logger.Initialise(NullLogger.Instance); EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); await context.ConnectToSubscription(EventStoreContextTestData.StreamName, EventStoreContextTestData.GroupName, EventStoreContextTestData.PersistentSubscriptionId, EventStoreContextTestData.BufferSize); connection.Verify(x => x.ConnectToPersistentSubscriptionAsync(It.IsAny <String>(), It.IsAny <String>(), It.IsAny <Func <EventStorePersistentSubscriptionBase, ResolvedEvent, Int32?, Task> >(), It.IsAny <Action <EventStorePersistentSubscriptionBase, SubscriptionDropReason, Exception> >(), It.IsAny <UserCredentials>(), It.IsAny <Int32>(), It.IsAny <Boolean>()), Times.Exactly(1)); }
public IEnumerable <IEventResult> GetAll() { using (var context = new EventStoreContext(ConnectionString.Get())) { return(context.Events.ToList().Select(a => new EventResult(a))); } }
internal ReadFlowToResumeCommand(EventStoreContext context, FlowKey key) { _context = context; _key = key; _routesStream = key.GetRoutesStream(); }
internal ReadFlowWithoutCheckpointCommand(EventStoreContext context, FlowKey key) { _context = context; _key = key; _stream = key.GetRoutesStream(); }
public QueryDb(EventStoreContext context, IQueryNotifier notifier) { _context = context; _notifier = notifier; _changedSubscription = new QueryChangedSubscription(this, context); _changedWindow = new QueryChangedWindow(); }
static async Task Main(string[] args) { await SubscriptionsTest(); EventStoreClientSettings settings = Program.ConfigureEventStoreSettings(); EventStoreClient client = new(settings); EventStoreProjectionManagementClient projectionManagementClient = new EventStoreProjectionManagementClient(settings); //var x = await projectionManagementClient.GetStatusAsync("$by_category", cancellationToken: CancellationToken.None); IEventStoreContext context = new EventStoreContext(client, projectionManagementClient); IAggregateRepository <TestAggregate, DomainEvent> aggregateRepository = new AggregateRepository <TestAggregate, DomainEvent>(context); Guid aggregateId = Guid.Parse("02398284-8284-8284-8284-165402398284"); TestAggregate aggregate = await aggregateRepository.GetLatestVersion(aggregateId, CancellationToken.None); aggregate.SetAggregateName("Test Name"); //aggregate.SetAggregateName("Test Name1"); //aggregate.SetAggregateName("Test Name2"); //aggregate.SetAggregateName("Test Name3"); //aggregate.SetAggregateName("Test Name4"); await aggregateRepository.SaveChanges(aggregate, CancellationToken.None); //TestDockerHelper t = new TestDockerHelper(); //await t.StartContainersForScenarioRun(""); }
public async Task <EventStoreRepository> GetSut() { IEventStoreConnection con = await LocalConfig.GetConnection(); EventStoreContext context = EventStoreContext.CreateDefault("aa", con); return(new EventStoreRepository(context, new EventSourceConfiguration())); }
internal ReadFlowWithCheckpointCommand(EventStoreContext context, FlowKey key, RecordedEvent checkpoint) { _context = context; _key = key; _checkpoint = checkpoint; _stream = key.GetRoutesStream(); }
/// <summary> /// Initializes the repository with a specific context information (default: "Name=EventStoreContext"). /// </summary> public void Initialize(string contextInfo = null) { if (_context != null) { return; } _context = string.IsNullOrWhiteSpace(contextInfo) ? new EventStoreContext() : new EventStoreContext(contextInfo); }
private static async Task ConfigureEventStoreContext(EventStoreContext storeDb) { var storeDbExist = await CheckTableExists <StoredEvent>(storeDb); if (!storeDbExist) { await storeDb.Database.MigrateAsync(); } }
internal SubscribeCommand( EventStoreContext context, CatchUpSubscriptionSettings settings, ITimelineObserver observer) { _context = context; _settings = settings; _observer = observer; }
static async Task Main(string[] args) { var baseTypes = new[] { typeof(BaseEvent) }; var eventTypes = typeof(BaseEvent).Assembly.GetTypes() .Where(t => t.IsSubclassOf(typeof(BaseEvent))); var options = new StreamDbContextOptionsBuilder() .UseEventStore("127.0.0.1:5001") .RegisterTypes(() => baseTypes.Concat(eventTypes)) .Options; var es = new EventStoreContext(options); var orderEvents = es.FromStreams <BaseEvent>("Order-*", "PaymentPlan-*"); var customerEvents = es.FromStreams <BaseEvent>("Customer-*"); var stream = orderEvents .GroupBy(e => (e is OrderCreatedEvent) ? ((OrderCreatedEvent)e).Id : (e is OrderCustomerLinkedV2Event) ? ((OrderCustomerLinkedV2Event)e).OrderId : (e is OrderConfirmedEvent) ? ((OrderConfirmedEvent)e).OrderId : (e is PaymentPlanCreatedEvent) ? ((PaymentPlanCreatedEvent)e).Id : Guid.Empty ) .Where(g => g.Key != Guid.Empty) //.Select(g => g // .Aggregate( // Guid.Empty, // (s, e) => (Guid)(e.GetType().GetProperty("CustomerId") == null ? s : e.GetType().GetProperty("CustomerId").GetValue(e, null)) // ) // .Zip(g, (c, e) => g.Where(x => !x.Bag.ContainsKey("CustomerId")).Do(x => x.Bag.Add("CustomerId", c))) // .SelectMany(x => x) //) .SelectMany(g => g) .Merge(customerEvents) // NB: This doesn't actually work - it's an observable and there's more to joining streams than this... .GroupBy(e => (e is OrderCustomerLinkedV2Event) ? ((OrderCustomerLinkedV2Event)e).CustomerId : (e is OrderConfirmedEvent) ? ((OrderConfirmedEvent)e).CustomerId : //(e is OrderCreatedEvent) ? (Guid)(e.Bag.ContainsKey("CustomerId") ? e.Bag["CustomerId"] : Guid.Empty) : //(e is PaymentPlanCreatedEvent) ? (Guid)(e.Bag.ContainsKey("CustomerId") ? e.Bag["CustomerId"] : Guid.Empty) : (e is CustomerDetailsAddedEvent) ? ((CustomerDetailsAddedEvent)e).CustomerId : Guid.Empty ) //.Where(g => g.Key == new Guid("879c5d39-fd72-4392-bf88-8bba363e590e")) .SelectMany(g => g) .Subscribe( onNext: s => Console.WriteLine(JsonConvert.SerializeObject(s)), onError: e => Console.WriteLine("ERROR: " + e), onCompleted: () => Console.WriteLine("DONE") ); while (!Console.KeyAvailable && Console.ReadKey(true).Key != ConsoleKey.Escape) { await Task.Delay(50); } }
internal WriteNewEventsCommand( EventStoreContext context, TimelinePosition cause, FlowKey topicKey, Many <Event> newEvents) { _context = context; _cause = cause; _topicKey = topicKey; _newEvents = newEvents; _newEventTypes = _newEvents.ToMany(e => _context.GetEventType(e)); }
public void SetUp() { _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); var options = new DbContextOptionsBuilder <EventStoreContext>() .UseSqlite(_connection) .Options; DbContext = new EventStoreContext(options); DbContext.Database.EnsureCreated(); }
public void EventStoreContext_CanBeCreated_IsCreated() { EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); context.ShouldNotBeNull(); }
private static bool IsProcessedBefore(EventStoreContext eventContext) { var IdempotenceReaderService = eventContext.Container.ResolveOptional <IIdempotenceReaderService>(); if (IdempotenceReaderService == null) { return(false); } var isProcessedBefore = IdempotenceReaderService.IsProcessedBefore(eventContext.EventId).GetAwaiter() .GetResult(); return(isProcessedBefore); }
internal ReadResumeScheduleCommand(EventStoreContext context, Many <long> schedule) { _context = context; _schedule = schedule; _scheduleFirst = schedule.First(); _scheduleLast = schedule.Last(); _readCheckpoint = StreamPosition.End; // There is overhead in piping a resume algorithm from configuration. The default should work until // we experience otherwise. _algorithm = new ResumeAlgorithm(); }
public void EventStoreContext_CanBeCreated_NullConnectionSettings_ErrorThrown() { EventStoreConnectionSettings eventStoreConnectionSettings = null; Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; Should.Throw <ArgumentNullException>(() => { EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); }); }
public SqlServerFixture() { var config = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddUserSecrets <SqlServerFixture>() .AddEnvironmentVariables() .Build(); var connectionString = config.GetConnectionString("eventStore"); DbContext = new EventStoreContext( new DbContextOptionsBuilder <EventStoreContext>().UseSqlServer(connectionString).Options); DbContext.Database.EnsureCreated(); }
public async Task EventStoreContext_CreatePersistentSubscriptionFromPosition_InvalidData_ErrorThrown(String streamName, String groupName, Type exceptionType) { EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; PaymentCentric.Logging.Logger.Initialise(NullLogger.Instance); EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); Should.Throw(async() => { await context.CreatePersistentSubscriptionFromPosition(streamName, groupName, EventStoreContextTestData.StartPosition); }, exceptionType); }
public void SetUp() { _connection = new SqliteConnection("DataSource=:memory:"); _aggregateId = new Guid("FC5B2701-E9B4-41E5-BD73-0C37185ADCBB"); _connection.Open(); var options = new DbContextOptionsBuilder <EventStoreContext>() .UseSqlite(_connection) .Options; DbContext = new EventStoreContext(options); var eventsAssembly = Assembly.LoadFile(@"C:\code\CQRSTutorial\CQRSTutorial.Events\bin\Debug\netstandard2.0\CQRSTutorial.Events.dll"); _storeRepository = new EventRepository(DbContext, eventsAssembly); }
public void When_loading_all_events() { CreateAndFillEvents(); var context = new EventStoreContext("ImportStream", new DefaultTypeResolver()); //15 -> 20 seconds Should.CompleteIn(() => { using (var reader = _store.CreateReader<Guid>(context)) { reader .LoadAllEvents() .Count() .ShouldBe(TotalRecords); } }, TimeSpan.FromSeconds(20)); }
private void PerformEventHandlerInvoke(Action <Guid> actionToNotifyEventIsDone, ResolvedEvent[] events) { foreach (var resolvedEvent in events) { var eventName = resolvedEvent.Event.EventStreamId; var jsonBytes = resolvedEvent.Event.Data; var eventId = resolvedEvent.Event.EventId; var eventContext = new EventStoreContext(eventId, eventName, resolvedEvent, string.Empty, _subscriptionConfiguration.SubscribedEvents, _container); _projectorInvoker.Invoke(eventContext); if (actionToNotifyEventIsDone != null) { actionToNotifyEventIsDone(resolvedEvent.Event.EventId); } } }
public async Task EventStoreContext_DeletePersistentSubscription_SubscriptionDeleted() { EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; PaymentCentric.Logging.Logger.Initialise(NullLogger.Instance); EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); await context.DeletePersistentSubscription(EventStoreContextTestData.StreamName, EventStoreContextTestData.GroupName); connection.Verify(x => x.DeletePersistentSubscriptionAsync(EventStoreContextTestData.StreamName, EventStoreContextTestData.GroupName, It.IsAny <UserCredentials>())); }
public async Task EventStoreContext_InsertEvents_EventsInserted() { EventStoreConnectionSettings eventStoreConnectionSettings = EventStoreConnectionSettings.Create(EventStoreContextTestData.ConnectionString); Mock <IEventStoreConnection> connection = new Mock <IEventStoreConnection>(); Mock <ISerialiser> serialiser = new Mock <ISerialiser>(); Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver = settings => { return(connection.Object); }; PaymentCentric.Logging.Logger.Initialise(NullLogger.Instance); EventStoreContext context = new EventStoreContext(eventStoreConnectionSettings, connectionResolver, serialiser.Object); await context.InsertEvents(EventStoreContextTestData.StreamName, EventStoreContextTestData.ExpectedVersion, EventStoreContextTestData.DomainEvents); connection.Verify(x => x.AppendToStreamAsync(EventStoreContextTestData.StreamName, EventStoreContextTestData.ExpectedVersion, It.IsAny <List <EventData> >(), It.IsAny <UserCredentials>())); }
private void InvokeEvent(EventStoreContext eventContext) { var jsonData = Encoding.ASCII.GetString(eventContext.ResolvedEvent.Event.Data); var eventType = eventContext.SubscribedEvents.FirstOrDefault(q => q.Key == eventContext.EventName); if (eventType.Equals(default(KeyValuePair <string, object>))) { return; } Type enumerableType = typeof(IEnumerable <>); Type projectorType = typeof(IProjector <>); Type type = ((Type)eventType.Value); Type genericType = projectorType.MakeGenericType(type); var enumerableGenericType = enumerableType.MakeGenericType(genericType); var resolvedType = eventContext.Container.Resolve(enumerableGenericType); var enumerator = ((IEnumerable)resolvedType).GetEnumerator(); while (enumerator.MoveNext()) { var currentProjectorClass = enumerator.Current; if (currentProjectorClass == null) { continue; } var handlerMethodInfo = currentProjectorClass.GetType().GetMethod("HandleAsync"); if (handlerMethodInfo == null) { throw new Exception("The Projector class doesn't have a HandleAsync method"); } var parameterInfo = handlerMethodInfo.GetParameters().FirstOrDefault(); object deserializedJsonObject = DeserializeObject(jsonData, parameterInfo); handlerMethodInfo.Invoke(currentProjectorClass, new object[] { deserializedJsonObject }); } }
public void Setup() { _connectionHangfire = new SqliteConnection("DataSource=:memory:"); _connectionHangfire.Open(); var options = new DbContextOptionsBuilder <HangfireContext>() .UseSqlite(_connectionHangfire) .Options; _hangfireContext = new HangfireContext(options); _connectionEventStore = new SqliteConnection("DataSource=:memory:"); _connectionEventStore.Open(); var optionsEventStore = new DbContextOptionsBuilder <EventStoreContext>() .UseSqlite(_connectionEventStore) .Options; _eventStoreContext = new EventStoreContext(optionsEventStore); _hangfireContext.Database.EnsureCreated(); _eventStoreContext.Database.EnsureCreated(); }
public bool Invoke(EventStoreContext eventContext) { if (eventContext.SubscribedEvents.All(q => q.Key != eventContext.EventName)) { return(false); } if (IsProcessedBefore(eventContext)) { return(false); } BeforeInvoke(eventContext); InvokeEvent(eventContext); PersistPositionAsync(eventContext).GetAwaiter().GetResult(); PersistIdempotenceAsync(eventContext).GetAwaiter().GetResult(); AfterInvoke(eventContext); return(true); }