Пример #1
0
            public async Task <SerializedEvent> Next()
            {
                if (_slice != null && _currentPostion >= _slice.Events.Length && _slice.NextEventNumber < 0)
                {
                    return(SerializedEvent.None);
                }

                if (_slice == null || _currentPostion >= _slice.Events.Length)
                {
                    _currentPostion = 0;
                    if (_slice != null)
                    {
                        _start = _slice.NextEventNumber;
                    }
                    _slice = await _readSlice(_start);

                    if (_slice.Status != SliceReadStatus.Success)
                    {
                        _onNotFound();
                    }
                }
                if (_slice.Events.Length == 0 && _slice.IsEndOfStream)
                {
                    return(SerializedEvent.None);
                }
                var resolvedEvent = _slice.Events[_currentPostion];
                var e             = resolvedEvent.Event;
                var result        = new SerializedEvent(e.EventId, e.EventType, e.Data, e.Metadata, e.EventStreamId, resolvedEvent.OriginalEventNumber);

                _currentPostion++;
                return(result);
            }
Пример #2
0
        public async Task <TAggregateRoot> FindAsync(params object[] keyValues)
        {
            string            streamName = StreamExtensions.GetStreamName(typeof(TAggregateRoot), keyValues[0].ToString());
            StreamEventsSlice slice      =
                await
                _connection.ReadStreamEventsForwardAsync(streamName, StreamPosition.Start, 20,
                                                         false);

            if (slice.Status == SliceReadStatus.StreamDeleted || slice.Status == SliceReadStatus.StreamNotFound)
            {
                return(null);
            }

            var aggregateRoot = (TAggregateRoot)Activator.CreateInstance(typeof(TAggregateRoot), true);
            var events        = await GetEvents(streamName);

            events.ForEach(e =>
            {
                (aggregateRoot as IEntity).ApplyEvent(e);
            });

            (aggregateRoot as IEntity).ClearEvents();

            var aggregate = new Aggregate(keyValues[0].ToString(), (int)slice.LastEventNumber, aggregateRoot);

            this._unitOfworkAsync.Attach(aggregate);

            return(aggregateRoot);
        }
        //Read Backwards 1 event to get last event
        private void ReverseLastTransaction()
        {
            StreamEventsSlice slice = EventStoreLoader.Connection.ReadStreamEventsBackwardAsync(
                _streamName,
                StreamPosition.End,
                1,
                false).Result;

            if (!slice.Events.Any() || !_rm.Checkpoint.HasValue)
            {
                _view.ErrorMsg = "Event not found to undo";
                return;
            }
            var evt            = slice.Events[0].Event;
            var amount         = int.Parse((string)JObject.Parse(Encoding.UTF8.GetString(evt.Data))["amount"]);
            var reversedAmount = amount * -1;

            EventStoreLoader.Connection.AppendToStreamAsync(
                evt.EventStreamId,
                _rm.Checkpoint.Value,
                new EventData(
                    Guid.NewGuid(),
                    evt.EventType,
                    evt.IsJson,
                    Encoding.UTF8.GetBytes("{amount:" + reversedAmount + "}"),
                    evt.Metadata));
        }
Пример #4
0
            public IObservable <ICommit> ReadStream(string stream, int minRevision, int maxRevision)
            {
                Guard.AgainstNull(stream, "stream");
                minRevision = Math.Max(minRevision, 0);
                Guard.Against <ArgumentOutOfRangeException>(maxRevision < minRevision, "maxRevision");

                const int batchSize = 512;

                int start = 0;

                return(Observable.Create <ICommit>(async observer =>
                {
                    bool isEndOfStream;
                    do
                    {
                        StreamEventsSlice slice =
                            await _connection.ReadStreamEventsForwardAsync(stream, start, batchSize, true);

                        var commits = (from resolved in slice.Events
                                       where false == IsSystemEvent(resolved)
                                       let dto = DeserializeEvent(resolved)
                                                 where SingleStreamIsInRange(dto, minRevision, maxRevision)
                                                 let commit = BuildCommit(dto, resolved)
                                                              select commit).ToList();

                        commits.ForEach(observer.OnNext);

                        start += batchSize;
                        isEndOfStream = slice.IsEndOfStream ||
                                        commits.Any(commit => commit.StreamRevision > maxRevision);
                    } while (false == isEndOfStream);

                    observer.OnCompleted();
                }));
            }
Пример #5
0
            public IObservable <ICommit> ReadAllFromCheckpoint(GetEventStoreCheckpoint checkpoint)
            {
                const int batchSize = 512;

                var start = ((int?)checkpoint ?? 0);

                const string stream = "$et-" + GetEventStoreCommitAttempt.EventType;

                return(Observable.Create <ICommit>(async observer =>
                {
                    bool isEndOfStream;
                    do
                    {
                        StreamEventsSlice slice =
                            await _connection.ReadStreamEventsForwardAsync(stream, start, batchSize, true);

                        var commits = (from resolved in slice.Events
                                       where false == IsSystemEvent(resolved)
                                       let dto = DeserializeEvent(resolved)
                                                 let commit = BuildCommit(dto, resolved)
                                                              select commit).ToList();

                        commits.ForEach(observer.OnNext);

                        start += batchSize;
                        isEndOfStream = slice.IsEndOfStream;
                    } while (false == isEndOfStream);

                    observer.OnCompleted();
                }));
            }
Пример #6
0
        /// <summary>
        /// Gets a collection of <see cref="IEvent{TAuthenticationToken}"/> for the <see cref="IAggregateRoot{TAuthenticationToken}"/> of type <paramref name="aggregateRootType"/> with the ID matching the provided <paramref name="aggregateId"/> from and including the provided <paramref name="fromVersionedDate"/> up to and including the provided <paramref name="toVersionedDate"/>.
        /// </summary>
        /// <param name="aggregateRootType"> <see cref="Type"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/> the <see cref="IEvent{TAuthenticationToken}"/> was raised in.</param>
        /// <param name="aggregateId">The <see cref="IAggregateRoot{TAuthenticationToken}.Id"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/>.</param>
        /// <param name="fromVersionedDate">Load events from and including from this <see cref="DateTime"/></param>
        /// <param name="toVersionedDate">Load events up-to and including from this <see cref="DateTime"/></param>
        public IEnumerable <IEvent <TAuthenticationToken> > GetBetweenDates(Type aggregateRootType, Guid aggregateId, DateTime fromVersionedDate, DateTime toVersionedDate)
        {
            string            streamName      = string.Format(CqrsEventStoreStreamNamePattern, aggregateRootType.FullName, aggregateId);
            StreamEventsSlice eventCollection = EventStoreConnection.ReadStreamEventsForwardAsync(streamName, StreamPosition.Start, 200, false).Result;

            return(eventCollection.Events.Select(EventDeserialiser.Deserialise).Where(eventData => eventData.TimeStamp >= fromVersionedDate && eventData.TimeStamp <= toVersionedDate));
        }
Пример #7
0
        /// <summary>
        /// Gets a collection of <see cref="IEvent{TAuthenticationToken}"/> for the <see cref="IAggregateRoot{TAuthenticationToken}"/> of type <paramref name="aggregateRootType"/> with the ID matching the provided <paramref name="aggregateId"/> up to and including the provided <paramref name="version"/>.
        /// </summary>
        /// <param name="aggregateRootType"> <see cref="Type"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/> the <see cref="IEvent{TAuthenticationToken}"/> was raised in.</param>
        /// <param name="aggregateId">The <see cref="IAggregateRoot{TAuthenticationToken}.Id"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/>.</param>
        /// <param name="version">Load events up-to and including from this version</param>
        public IEnumerable <IEvent <TAuthenticationToken> > GetToVersion(Type aggregateRootType, Guid aggregateId, int version)
        {
            string            streamName      = string.Format(CqrsEventStoreStreamNamePattern, aggregateRootType.FullName, aggregateId);
            StreamEventsSlice eventCollection = EventStoreConnection.ReadStreamEventsForwardAsync(streamName, StreamPosition.Start, version, false).Result;

            return(eventCollection.Events.Select(EventDeserialiser.Deserialise));
        }
Пример #8
0
        /// <summary>
        ///     Attempts to get the aggregate root entity associated with the aggregate identifier.
        /// </summary>
        /// <param name="identifier">The aggregate identifier.</param>
        /// <returns>The found <typeparamref name="TAggregateRoot" />, or empty if not found.</returns>
        public Optional <TAggregateRoot> GetOptional(string identifier)
        {
            if (UnitOfWork.TryGet(identifier, out Aggregate aggregate))
            {
                return(new Optional <TAggregateRoot>((TAggregateRoot)aggregate.Root));
            }
            UserCredentials   streamUserCredentials = Configuration.StreamUserCredentialsResolver.Resolve(identifier);
            string            streamName            = Configuration.StreamNameResolver.Resolve(identifier);
            StreamEventsSlice slice = Connection.
                                      ReadStreamEventsForwardAsync(
                streamName, StreamPosition.Start, Configuration.SliceSize, false, streamUserCredentials).
                                      Result;

            if (slice.Status == SliceReadStatus.StreamDeleted || slice.Status == SliceReadStatus.StreamNotFound)
            {
                return(Optional <TAggregateRoot> .Empty);
            }
            TAggregateRoot root = RootFactory();

            root.Initialize(slice.Events.Select(resolved => Configuration.Deserializer.Deserialize(resolved)));
            while (!slice.IsEndOfStream)
            {
                slice = Connection.
                        ReadStreamEventsForwardAsync(
                    streamName, slice.NextEventNumber, Configuration.SliceSize, false, streamUserCredentials).
                        Result;
                root.Initialize(slice.Events.Select(resolved => Configuration.Deserializer.Deserialize(resolved)));
            }
            aggregate = new Aggregate(identifier, (int)slice.LastEventNumber, root);
            UnitOfWork.Attach(aggregate);
            return(new Optional <TAggregateRoot>(root));
        }
Пример #9
0
        private async Task AppendToStream()
        {
            foreach (Aggregate aggregate in _repository.UnitOfWork.GetChanges())
            {
                EventData[] changes = aggregate.Root.GetChanges()
                                      .Select(@event => new EventData(
                                                  Guid.NewGuid(),
                                                  @event.GetType().TypeQualifiedName(),
                                                  true,
                                                  Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@event)),
                                                  Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new EventMetadata
                {
                    TimeStamp     = _now(),
                    AggregateType = typeof(T).Name,
                    AggregateAssemblyQualifiedName = typeof(T).AssemblyQualifiedName,
                    IsSnapshot = false
                }))
                                                  )).ToArray();
                try
                {
                    await _repository.Connection.AppendToStreamAsync(_getStreamName(typeof(T), aggregate.Identifier), aggregate.ExpectedVersion, changes);
                }
                catch (WrongExpectedVersionException)
                {
                    StreamEventsSlice page = await _repository.Connection.ReadStreamEventsBackwardAsync(aggregate.Identifier, -1, 1, false);

                    throw new WrongExpectedStreamVersionException(
                              $"Failed to append stream {aggregate.Identifier} with expected version {aggregate.ExpectedVersion}. " +
                              $"{(page.Status == SliceReadStatus.StreamNotFound ? "Stream not found!" : $"Current Version: {page.LastEventNumber}")}");
                }
            }
        }
Пример #10
0
        public Mutation Read()
        {
            StreamEventsSlice streamEvents =
                connection.ReadStreamEventsForwardAsync("test-stream", 0, 1, false).Result;

            RecordedEvent returnedEvent = streamEvents.Events[0].Event;

            return(JsonConvert.DeserializeObject <Mutation>(Encoding.UTF8.GetString(returnedEvent.Data)));
        }
Пример #11
0
        private StreamEventsSlice ReadFromStream(
            string streamName,
            long start,
            long count,
            List <RecordedEvent> stream,
            ReadDirection direction)
        {
            var result = new List <RecordedEvent>();
            var next   = start == -1 ? stream.Count - 1 : (int)start;

            for (int i = 0; i < count; i++)
            {
                if (next < stream.Count && next >= 0)
                {
                    long current = next;
                    result.Add(stream[(int)current]);
                }
                next += (int)direction;
            }

            bool isEnd;

            if (direction == ReadDirection.Forward)
            {
                isEnd = next >= stream.Count;
                if (next > stream.Count)
                {
                    next = stream.Count;
                }
            }
            else  //Direction.Backward
            {
                isEnd = next < 0;
                if (next < 0)
                {
                    next = StreamPosition.End;
                }
                if (next > stream.Count + 1)
                {
                    next = stream.Count - 1;
                }
                else if (next > stream.Count)
                {
                    next = stream.Count;
                }
            }
            var slice = new StreamEventsSlice(
                streamName,
                start,
                direction,
                result.ToArray(),
                next,
                stream.Count - 1,
                isEnd);

            return(slice);
        }
        public async Task PollAsync_IfUnsuccessful_ShouldNotTryToProcessResults()
        {
            var result = new StreamEventsSlice
            {
                Status  = StreamReadStatus.StreamNotFound,
                Entries = null
            };

            _eventStoreHttpConnectionMock.Setup(x => x.ReadStreamEventsForwardAsync(StreamName, It.IsAny <int>(), It.IsAny <int>(), It.IsAny <TimeSpan?>())).Returns(async() => result);
            await _subscriber.PollAsync(StreamName, SubscriberId);
        }
Пример #13
0
 IEnumerable <dynamic> GetEventsFrom(StreamEventsSlice slice)
 {
     foreach (var evnt in slice.Events)
     {
         var r = TryGetDomainEvent(evnt);
         if (r != null)
         {
             yield return(r);
         }
     }
 }
        public async Task PollAsync_IfNoEvents_ShouldImmediatelyResumeTheEventTimerDuringPolling()//to keep the polling going at the preferred rate
        {
            var result = new StreamEventsSlice
            {
                Entries = new List <BasicEventInfo>()
            };

            _eventStoreHttpConnectionMock.Setup(x => x.ReadStreamEventsForwardAsync(StreamName, It.IsAny <int>(), It.IsAny <int>(), It.IsAny <TimeSpan?>())).Returns(async() => result);
            await _subscriber.PollAsync(StreamName, SubscriberId);

            _subscriptionTimerManagerMock.Verify(x => x.Pause(StreamName, SubscriberId));
        }
        private void ApplySlice(int maxVersion, StreamEventsSlice slice, IAggregate aggregate)
        {
            int version       = aggregate.Version;
            var eventsToApply = from @event in slice.Events
                                where++ version <= maxVersion
                                select _serializer.DeserializeEventData(@event);

            using (var rehydrateAggregate = aggregate.BeginRehydrate())
            {
                eventsToApply.ForEach(rehydrateAggregate.ApplyEvent);
            }
        }
Пример #16
0
        public async Task <List <Event <T> > > GetEventsAsync <T>(string streamName, Guid streamId)
        {
            string stream = $"{streamName}-{streamId}";

            StreamEventsSlice result = await Connection.ReadStreamEventsBackwardAsync(stream, StreamPosition.End, 10, true);

            IEnumerable <Event <T> > events = result.Events.Select(x => new Event <T>
            {
                Data = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(x.Event.Data))
            });

            return(events.ToList());
        }
Пример #17
0
        public bool FindEventType(StreamEventsSlice streamEvents, string desiredEvent)
        {
            bool eventFound = false;

            foreach (var eventEmitted in streamEvents.Events)
            {
                if (eventEmitted.Event.EventType == desiredEvent)
                {
                    eventFound = true;
                }
            }
            return(eventFound);
        }
Пример #18
0
        public async Task <TAggregateRoot> FindAsync(params object[] keyValues)
        {
            var existingAggregate = _unitOfworkAsync.AttachedObject(keyValues[0].ToString());

            if (existingAggregate != null)
            {
                return((TAggregateRoot)(((Aggregate)existingAggregate).Root));
            }
            var streamName = StreamExtensions.GetStreamName(typeof(TAggregateRoot), keyValues[0].ToString());

            var version = StreamPosition.Start;

            StreamEventsSlice slice =
                await
                _connection.ReadStreamEventsForwardAsync(streamName, version, 100, false);

            if (slice.Status == SliceReadStatus.StreamDeleted || slice.Status == SliceReadStatus.StreamNotFound)
            {
                throw new AggregateNotFoundException($"Aggregate not found by {streamName}");
            }

            TAggregateRoot root = (TAggregateRoot)Activator.CreateInstance(typeof(TAggregateRoot), true);

            slice.Events.ToList().ForEach(e =>
            {
                var resolvedEvent = this._serializer.Deserialize(Type.GetType(e.Event.EventType, true), Encoding.UTF8.GetString(e.Event.Data));
                (root as IEntity).ApplyEvent(resolvedEvent);
            });

            while (!slice.IsEndOfStream)
            {
                slice =
                    await
                    _connection.ReadStreamEventsForwardAsync(streamName, slice.NextEventNumber, 100,
                                                             false);

                slice.Events.ToList().ForEach(e =>
                {
                    var resolvedEvent = this._serializer.Deserialize(Type.GetType(e.Event.EventType, true), Encoding.UTF8.GetString(e.Event.Data));
                    (root as IEntity).ApplyEvent(resolvedEvent);
                });
            }

            (root as IEntity).ClearEvents();

            var aggregate = new Aggregate(keyValues[0].ToString(), (int)slice.LastEventNumber, root);

            this._unitOfworkAsync.Attach(aggregate);

            return(root);
        }
        /// <summary>
        ///     Attempts to get the aggregate root entity associated with the aggregate identifier.
        /// </summary>
        /// <param name="identifier">The aggregate identifier.</param>
        /// <returns>The found <typeparamref name="TAggregateRoot" />, or empty if not found.</returns>
        public async Task <Optional <TAggregateRoot> > GetOptionalAsync(string identifier)
        {
            if (_unitOfWork.TryGet(identifier, out Aggregate aggregate))
            {
                return(new Optional <TAggregateRoot>((TAggregateRoot)aggregate.Root));
            }

            Optional <Snapshot> snapshot = await _reader.ReadOptionalAsync(identifier);

            var version = StreamPosition.Start;

            if (snapshot.HasValue)
            {
                version = snapshot.Value.Version + 1;
            }

            UserCredentials   streamUserCredentials = _configuration.StreamUserCredentialsResolver.Resolve(identifier);
            string            streamName            = _configuration.StreamNameResolver.Resolve(identifier);
            StreamEventsSlice slice =
                await
                _connection.ReadStreamEventsForwardAsync(streamName, version, _configuration.SliceSize, false,
                                                         streamUserCredentials);

            if (slice.Status == SliceReadStatus.StreamDeleted || slice.Status == SliceReadStatus.StreamNotFound)
            {
                return(Optional <TAggregateRoot> .Empty);
            }

            TAggregateRoot root = _rootFactory();

            if (snapshot.HasValue)
            {
                root.RestoreSnapshot(snapshot.Value.State);
            }

            root.Initialize(slice.Events.Select(resolved => _configuration.Deserializer.Deserialize(resolved)));
            while (!slice.IsEndOfStream)
            {
                slice =
                    await
                    _connection.ReadStreamEventsForwardAsync(streamName, slice.NextEventNumber, _configuration.SliceSize,
                                                             false, streamUserCredentials);

                root.Initialize(slice.Events.Select(resolved => _configuration.Deserializer.Deserialize(resolved)));
            }

            aggregate = new Aggregate(identifier, (int)slice.LastEventNumber, root);
            _unitOfWork.Attach(aggregate);
            return(new Optional <TAggregateRoot>(root));
        }
Пример #20
0
        public async IAsyncEnumerable <object> GetEvents(string id)
        {
            StreamEventsSlice slice = null;

            do
            {
                slice = await _connection.ReadStreamEventsForwardAsync(id, slice?.LastEventNumber + 1 ?? StreamPosition.Start, 200, false);

                foreach (var @event in slice.Events)
                {
                    yield return(@event.ToDomainEvent());
                }
            } while (!slice.IsEndOfStream);
        }
Пример #21
0
        private static List <IEvent> GetEvents(StreamEventsSlice events)
        {
            var Result = new List <IEvent>();

            foreach (var x in events.Events)
            {
                var data = Helper.Parse(x.Event);
                if (data != null)
                {
                    Result.AddRange(data);
                }
            }
            return(Result);
        }
        /// <summary>
        /// Reads all events in stream
        /// </summary>
        protected IEnumerable <ResolvedEvent> ReadAllEventsInStream(string streamName, IEventStoreConnection connection, int pageSize = 500)
        {
            var result  = new List <ResolvedEvent>();
            var coursor = StreamPosition.Start;
            StreamEventsSlice events = null;

            do
            {
                events = connection.ReadStreamEventsForward(streamName, coursor, pageSize, false);
                result.AddRange(events.Events);
                coursor = events.NextEventNumber;
            } while (events != null && !events.IsEndOfStream);

            return(result);
        }
Пример #23
0
        static void Main(string[] args)
        {
            //describe connection
            //bizim portumuz 2113 gösteriyor niye burada 1113 ve çalışıyor?
            var connection = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"));

            //open connection. senkron olması için wait komutunu veriyoruz.
            connection.ConnectAsync().Wait();

            User u = new User();

            u.Name     = "Özgün";
            u.Surname  = "Türkmen";
            u.UserName = "******";

            byte[] bytearrayData = Serialize.ObjectToByteArray(u);

            //göndereceğimiz event yani yazılacak olan event
            EventData myEvent = new EventData(Guid.NewGuid(), "myUserEvent", false,
                                              bytearrayData,
                                              bytearrayData);

            //asenkron olarak stream ekleme
            connection.AppendToStreamAsync("myUserstream", ExpectedVersion.Any, myEvent).Wait();

            //bu da streami okuyor herhalde. resulttan senkron olduğu sonucuna vardım.
            //streameventslice => event'in tek okuma operasyonu olarak geçiyor
            StreamEventsSlice streamEvents = connection.ReadStreamEventsForwardAsync("myUserstream", 0, 1, false).Result;

            //recorded event => yazılan eventleri gösteriyor.
            RecordedEvent returnedEvent = streamEvents.Events[0].Event;

            foreach (var item in myEvent.Data)
            {
                //wtf? neyi yazdırdı bu ? neyi datası bu? mantık tam olarak ne? nereye gidiyoruz?
                Console.WriteLine(item.ToString());
            }

            Console.WriteLine("-------------------------------------------");


            Console.WriteLine(returnedEvent.EventNumber);
            Console.WriteLine(returnedEvent.EventStreamId);
            Console.WriteLine(returnedEvent.IsJson);


            Console.ReadLine();
        }
Пример #24
0
        public async Task <TProjection> Hydrate <TProjection>(StreamEventsSlice events)
            where TProjection : Projection, new()
        {
            return(await Task.Run(() =>
            {
                var projetion = new TProjection();

                foreach (var @event in events.Events)
                {
                    var e = @event.Deserialize();
                    projetion.ApplayEvent(e);
                }

                return projetion;
            }));
        }
        protected override async Task <SelectedSnapshot> LoadAsync(string persistenceId, SnapshotSelectionCriteria criteria)
        {
            var streamName           = GetStreamName(persistenceId);
            var requestedSnapVersion = (int)criteria.MaxSequenceNr;
            StreamEventsSlice slice  = null;

            if (criteria.MaxSequenceNr == long.MaxValue)
            {
                requestedSnapVersion = StreamPosition.End;
                slice = await connection.ReadStreamEventsBackwardAsync(streamName, requestedSnapVersion, 1, false);
            }
            else
            {
                slice = await connection.ReadStreamEventsBackwardAsync(streamName, StreamPosition.End, requestedSnapVersion, false);
            }

            if (slice.Status == SliceReadStatus.StreamNotFound)
            {
                await connection.SetStreamMetadataAsync(streamName, ExpectedVersion.Any, StreamMetadata.Data);

                return(null);
            }

            if (slice.Events.Any())
            {
                log.Debug("Found snapshot of {0}", persistenceId);

                ResolvedEvent?resolvedEvent = null;
                foreach (var @event in slice.Events)
                {
                    if (requestedSnapVersion == @event.OriginalEvent.EventNumber ||
                        requestedSnapVersion == StreamPosition.End)
                    {
                        resolvedEvent = @event;
                    }
                }

                resolvedEvent = resolvedEvent ?? new ResolvedEvent?(slice.Events.First());

                var originalEvent = resolvedEvent.Value.OriginalEvent;

                return((SelectedSnapshot)serializer.FromBinary(originalEvent.Data, typeof(SelectedSnapshot)));
            }

            return(null);
        }
        public async Task PollAsync_IfEventBodyNotFound_ShouldKeepRetryingUntilItsFound()
        {
            var count             = 0;
            var streamSliceResult = new StreamEventsSlice
            {
                Entries = new List <BasicEventInfo> {
                    new BasicEventInfo {
                        Title = "1@Stream", Links = new List <Link> {
                            new Link {
                                Relation = "edit"
                            }
                        }
                    }
                }
            };


            _eventTypeResolverMock.Setup(x => x.Resolve(It.IsAny <string>())).Returns(typeof(string));
            _eventStoreHttpConnectionMock.Setup(x => x.ReadStreamEventsForwardAsync(StreamName, It.IsAny <int>(), It.IsAny <int>(), It.IsAny <TimeSpan?>())).Returns(async() => streamSliceResult).Callback(
                () =>
            {
                if (count++ == 3000)
                {
                    streamSliceResult.Entries.Clear();
                }
            });

            _eventStoreHttpConnectionMock.Setup(x => x.ReadEventAsync(StreamName, It.IsAny <int>())).Returns(async() => new EventReadResult(EventReadStatus.Success, new EventInfo {
                EventType = typeof(EventANoBaseOrInterface).FullName
            }));

            _eventHandlerResolverMock.Setup(x => x.GetHandlersOf(It.IsAny <Type>())).Returns(new List <object> {
                new SomeImplicitHandler()
            });
            _eventTypeResolverMock.Setup(x => x.Resolve(It.IsAny <string>())).Returns(typeof(EventANoBaseOrInterface));

            _eventStoreHttpConnectionMock.SetupSequence(x => x.ReadEventBodyAsync(It.IsAny <Type>(), It.IsAny <string>()))
            .Throws(new EventNotFoundException(""))
            .Throws(new EventNotFoundException(""))
            .Throws(new EventNotFoundException(""))
            .Returns(Task.FromResult((object)new EventANoBaseOrInterface()));

            await _subscriber.PollAsync(StreamName, null);

            _eventStoreHttpConnectionMock.Verify(x => x.ReadEventBodyAsync(It.IsAny <Type>(), It.IsAny <string>()), Times.Exactly(4));
        }
        public IEnumerable <object> Translate(StreamEventsSlice slice)
        {
            if (slice == null)
            {
                throw new ArgumentNullException(nameof(slice));
            }

            foreach (var @event in slice.Events)
            {
                var originalEvent = @event.OriginalEvent;
                var typeOfEvent   = Resolver(originalEvent.EventType);
                var translated    = JsonConvert.DeserializeObject(
                    Encoding.UTF8.GetString(originalEvent.Data),
                    typeOfEvent,
                    Settings);
                yield return(translated);
            }
        }
Пример #28
0
        /// <summary>
        ///     Reads a snapshot from the underlying storage if one is present.
        /// </summary>
        /// <param name="identifier">The aggregate identifier.</param>
        /// <returns>
        ///     A <see cref="Snapshot" /> if found, otherwise <c>empty</c>.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">identifier</exception>
        public async Task <Optional <Snapshot> > ReadOptionalAsync(string identifier)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException(nameof(identifier));
            }
            UserCredentials   streamUserCredentials = Configuration.StreamUserCredentialsResolver.Resolve(identifier);
            string            streamName            = Configuration.StreamNameResolver.Resolve(identifier);
            StreamEventsSlice slice =
                await
                Connection.ReadStreamEventsBackwardAsync(streamName, StreamPosition.End, 1, false, streamUserCredentials);

            if (slice.Status == SliceReadStatus.StreamDeleted || slice.Status == SliceReadStatus.StreamNotFound ||
                slice.Events.Length == 0 && slice.NextEventNumber == -1)
            {
                return(Optional <Snapshot> .Empty);
            }
            return(new Optional <Snapshot>(Configuration.Deserializer.Deserialize(slice.Events[0])));
        }
        private static void GetEventStoreData(IEventStoreConnection connection, string aggregateId)
        {
            Task <StreamEventsSlice> results = Task.Run(() =>
                                                        connection.ReadStreamEventsForwardAsync(GetStreamName(aggregateId), StreamPosition.Start, 999,
                                                                                                false));

            Task.WaitAll();

            StreamEventsSlice resultsData = results.Result;
            var bankState = new BankAccount();

            foreach (ResolvedEvent evnt in resultsData.Events)
            {
                string esJsonData = Encoding.UTF8.GetString(evnt.Event.Data);
                Console.WriteLine("\n" + esJsonData);

                switch (evnt.Event.EventType)
                {
                case "AccountCreated":
                {
                    var objState = JsonConvert.DeserializeObject <AccountCreated>(esJsonData);
                    bankState.Apply(objState);
                    break;
                }

                case "FundsDeposited":
                {
                    var objState = JsonConvert.DeserializeObject <FundsDeposited>(esJsonData);
                    bankState.Apply(objState);
                    break;
                }

                default:
                {
                    var objState = JsonConvert.DeserializeObject <FundsWithdrawn>(esJsonData);
                    bankState.Apply(objState);
                    break;
                }
                }

                Console.WriteLine("Current Balance: " + bankState.CurrentBalance);
            }
        }
        private static bool StreamExists(StreamEventsSlice readResult)
        {
            bool streamExists = false;

            try
            {
                var readState = readResult.Status;
                streamExists = readState == SliceReadStatus.Success;
            }
#pragma warning disable 168
            catch (StreamDeletedException ex)
            // This happens when the stream is hard-deleted. We don't want to throw in that case
#pragma warning restore 168
            {
                streamExists = false;
            }

            return(streamExists);
        }