Example #1
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)
        {
            Aggregate aggregate;

            if (_unitOfWork.TryGet(identifier, out aggregate))
            {
                return(new Optional <TAggregateRoot>((TAggregateRoot)aggregate.Root));
            }
            var streamUserCredentials = _configuration.StreamUserCredentialsResolver.Resolve(identifier);
            var streamName            = _configuration.StreamNameResolver.Resolve(identifier);
            var slice = _connection.ReadStreamEventsForward(streamName, StreamPosition.Start, _configuration.SliceSize,
                                                            false, streamUserCredentials);

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

            root.Initialize(slice.Events.SelectMany(resolved => _configuration.Deserializer.Deserialize(resolved)));
            while (!slice.IsEndOfStream)
            {
                slice = _connection.ReadStreamEventsForward(streamName, slice.NextEventNumber, _configuration.SliceSize,
                                                            false, streamUserCredentials);
                root.Initialize(slice.Events.SelectMany(resolved => _configuration.Deserializer.Deserialize(resolved)));
            }
            aggregate = new Aggregate(identifier, slice.LastEventNumber, root);
            _unitOfWork.Attach(aggregate);
            return(new Optional <TAggregateRoot>(root));
        }
Example #2
0
        public void read_stream_forward_respects_max_count()
        {
            var res = _connection.ReadStreamEventsForward(Stream, 0, 100, false);

            Assert.AreEqual(SliceReadStatus.Success, res.Status);
            Assert.AreEqual(3, res.Events.Length);
            Assert.AreEqual(_testEvents.Skip(2).Select(x => x.EventId).ToArray(),
                            res.Events.Select(x => x.Event.EventId).ToArray());
        }
        public void following_append_with_correct_expected_version_are_commited_correctly()
        {
            Assert.AreEqual(4, _connection.AppendToStream("test-stream", 2, TestEvent.NewTestEvent(), TestEvent.NewTestEvent()).NextExpectedVersion);

            var res = _connection.ReadStreamEventsForward("test-stream", 0, 100, false);

            Assert.AreEqual(SliceReadStatus.Success, res.Status);
            Assert.AreEqual(5, res.Events.Length);
            for (int i = 0; i < 5; ++i)
            {
                Assert.AreEqual(i, res.Events[i].OriginalEventNumber);
            }
        }
        public override TResult GetById <TResult>(Guid id)
        {
            var streamName = AggregateToStreamName(typeof(TResult), id);

            try
            {
                var eventsSlice = _connection.ReadStreamEventsForward(streamName, 0, int.MaxValue, false);
                if (eventsSlice.Status == SliceReadStatus.StreamNotFound)
                {
                    throw new AggregateNotFoundException("Could not found aggregate of type " + typeof(TResult) +
                                                         " and id " + id);
                }
                var deserializedEvents = eventsSlice.Events.Select(e =>
                {
                    var metadata  = DeserializeObject <Dictionary <string, string> >(e.OriginalEvent.Metadata);
                    var eventData = DeserializeObject(e.OriginalEvent.Data, metadata[EventClrTypeHeader]);
                    return(eventData as IEvent);
                });
                return(BuildAggregate <TResult>(deserializedEvents));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void read_stream_forward_respects_truncatebefore()
        {
            const string stream = "read_stream_forward_respects_truncatebefore";

            _connection.AppendToStream(stream, ExpectedVersion.EmptyStream, _testEvents);

            _connection.SetStreamMetadata(stream, ExpectedVersion.EmptyStream, StreamMetadata.Build().SetTruncateBefore(2));

            var res = _connection.ReadStreamEventsForward(stream, 0, 100, false);

            Assert.AreEqual(SliceReadStatus.Success, res.Status);
            Assert.AreEqual(3, res.Events.Length);
            Assert.AreEqual(_testEvents.Skip(2).Select(x => x.EventId).ToArray(),
                            res.Events.Select(x => x.Event.EventId).ToArray());
        }
        public IEnumerable <DomainEvent> GetStream(string streamName, int fromVersion, int toVersion)
        {
            // ES wants the number of events to retrieve not highest version
            var amount = (toVersion - fromVersion) + 1;

            Console.WriteLine("Amount: " + amount);
            var events = esConn.ReadStreamEventsForward(StreamName(streamName), fromVersion, amount, false); // last param not important here

            // map events back from JSON string to DomainEvent. Header indicates the type
            return(events.Events.Select(e => (DomainEvent)RebuildEvent(e)));
        }
 public static int Count(IEventStoreConnection store, string stream)
 {
     var result = 0;
     while (true)
     {
         var slice = store.ReadStreamEventsForward(stream, result, SliceSize, false);
         result += slice.Events.Length;
         if (slice.IsEndOfStream)
             break;
     }
     return result;
 }
Example #8
0
        public TAggregate GetById <TAggregate>(string streamName) where TAggregate : class, IAggregate
        {
            EnsureConnected();

            var aggregate = ConstructAggregate <TAggregate>();

            StreamEventsSlice currentSlice;
            var nextSliceStart = 0;

            do
            {
                currentSlice   = _eventStoreConnection.ReadStreamEventsForward(streamName, nextSliceStart, ReadPageSize, true);
                nextSliceStart = currentSlice.NextEventNumber;

                foreach (var evnt in currentSlice.Events)
                {
                    aggregate.ApplyEvent(_adapter.DeserializeEvent(evnt.Event));
                }
            } while (!currentSlice.IsEndOfStream);

            return(aggregate);
        }
Example #9
0
        public IList <Event> GetEventsForAggregate(Guid aggregate_id,
                                                   IEventSerializer serializer, int version)
        {
            var events      = new List <Event>();
            var stream_name = StreamNameForID(aggregate_id);
            int position    = 0;
            StreamEventsSlice slice;

            do
            {
                var count = position + kReadPageSize <= version
          ? kReadPageSize
          : version - position + 1;
                slice = connection_.ReadStreamEventsForward(stream_name, position,
                                                            count, false);
                position = slice.NextEventNumber;
                var serialized_events =
                    slice.Events.Select(@event => Deserialize(@event, serializer));
                events.AddRange(serialized_events);
            } while (version > slice.NextEventNumber && !slice.IsEndOfStream);
            return(events);
        }
        protected override void ReadEventsTill(IEventStoreConnection connection, bool resolveLinkTos,
                                               UserCredentials userCredentials, long?lastCommitPosition, int?lastEventNumber)
        {
            bool done;

            do
            {
                var slice = connection.ReadStreamEventsForward(StreamId, _nextReadEventNumber, ReadBatchSize, resolveLinkTos, userCredentials);
                switch (slice.Status)
                {
                case SliceReadStatus.Success:
                {
                    foreach (var e in slice.Events)
                    {
                        TryProcess(e);
                    }
                    _nextReadEventNumber = slice.NextEventNumber;
                    done = lastEventNumber == null ? slice.IsEndOfStream : slice.NextEventNumber > lastEventNumber;
                    break;
                }

                case SliceReadStatus.StreamNotFound:
                {
                    if (lastEventNumber.HasValue && lastEventNumber != -1)
                    {
                        throw new Exception(string.Format("Impossible: stream {0} disappeared in the middle of catching up subscription.", StreamId));
                    }
                    done = true;
                    break;
                }

                case SliceReadStatus.StreamDeleted:
                    throw new StreamDeletedException(StreamId);

                default:
                    throw new ArgumentOutOfRangeException(string.Format("Unexpected StreamEventsSlice.Status: {0}.", slice.Status));
                }

                if (!done && slice.IsEndOfStream)
                {
                    Thread.Sleep(1); // we are waiting for server to flush its data
                }
            } while (!done);

            if (Verbose)
            {
                Log.Debug("Catch-up Subscription to {0}: finished reading events, nextReadEventNumber = {1}.",
                          IsSubscribedToAll ? "<all>" : StreamId, _nextReadEventNumber);
            }
        }
        /// <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);
        }
Example #12
0
        public static int Count(IEventStoreConnection store, string stream)
        {
            var result = 0;

            while (true)
            {
                var slice = store.ReadStreamEventsForward(stream, result, SliceSize, false);
                result += slice.Events.Length;
                if (slice.IsEndOfStream)
                {
                    break;
                }
            }
            return(result);
        }
Example #13
0
        public IEnumerable LoadEventsFor <TAggregate>(Guid id)
        {
            StreamEventsSlice currentSlice;
            var nextSliceStart = StreamPosition.Start;

            do
            {
                currentSlice = conn.ReadStreamEventsForward(id.ToString(), nextSliceStart, 200, false);
                foreach (var e in currentSlice.Events)
                {
                    yield return(Deserialize(e.Event.EventType, e.Event.Data));
                }
                nextSliceStart = currentSlice.NextEventNumber;
            } while (!currentSlice.IsEndOfStream);
        }
        public TAggregate GetById(Guid id, int version)
        {
            if (version < 0)
            {
                throw new InvalidOperationException("Cannot get version < 0");
            }

            var streamName = _aggregateIdToStreamName(typeof(TAggregate), id);
            var aggregate  = LoadFromSnapshot(id, version) ?? ConstructAggregate();

            var sliceStart = aggregate.Version + 1;
            StreamEventsSlice currentSlice;

            do
            {
                var sliceCount = sliceStart + ReadPageSize <= version
                                    ? ReadPageSize
                                    : version - sliceStart + 1;

                if (sliceCount <= 0)
                {
                    break;
                }

                currentSlice = _eventStoreConnection.ReadStreamEventsForward(streamName, sliceStart, sliceCount, false);

                if (currentSlice.Status == SliceReadStatus.StreamNotFound)
                {
                    throw new AggregateNotFoundException(id, typeof(TAggregate));
                }

                if (currentSlice.Status == SliceReadStatus.StreamDeleted)
                {
                    throw new AggregateDeletedException(id, typeof(TAggregate));
                }

                sliceStart = currentSlice.NextEventNumber;

                aggregate.LoadsFromHistory(currentSlice.Events.Select(evnt => DeserializeObject <EventBase>(evnt.OriginalEvent.Metadata, evnt.OriginalEvent.Data)));
            } while (version >= currentSlice.NextEventNumber && !currentSlice.IsEndOfStream);

            if (aggregate.Version != version && version < Int32.MaxValue)
            {
                throw new AggregateVersionException(id, typeof(TAggregate), aggregate.Version, version);
            }

            return(aggregate);
        }
Example #15
0
        public TAggregate GetById <TAggregate>(Guid id, int version) where TAggregate : class, IAggregate
        {
            if (version <= 0)
            {
                throw new InvalidOperationException("Cannot get version <= 0");
            }

            var streamName = _aggregateIdToStreamName(typeof(TAggregate), id);
            var aggregate  = ConstructAggregate <TAggregate>(id);
            //aggregate.Id = id;

            var sliceStart = 0;
            StreamEventsSlice currentSlice;

            do
            {
                var sliceCount = sliceStart + ReadPageSize <= version
                                    ? ReadPageSize
                                    : version - sliceStart + 1;

                currentSlice = _eventStoreConnection.ReadStreamEventsForward(streamName, sliceStart, sliceCount, false);

                if (currentSlice.Status == SliceReadStatus.StreamNotFound)
                {
                    throw new AggregateNotFoundException(id, typeof(TAggregate));
                }

                if (currentSlice.Status == SliceReadStatus.StreamDeleted)
                {
                    throw new AggregateDeletedException(id, typeof(TAggregate));
                }

                sliceStart = currentSlice.NextEventNumber;

                foreach (var evnt in currentSlice.Events)
                {
                    var realEvent = DeserializeEvent(evnt.OriginalEvent.Metadata, evnt.OriginalEvent.Data);
                    aggregate.ApplyEvent(realEvent);
                }
            } while (version >= currentSlice.NextEventNumber && !currentSlice.IsEndOfStream);

            if (aggregate.Version != version && version < Int32.MaxValue)
            {
                throw new AggregateVersionException(id, typeof(TAggregate), aggregate.Version, version);
            }

            return(aggregate);
        }
Example #16
0
        private void LoadProjectionCatalog()
        {
            Log("Loading projection catalog...");
            StreamEventsSlice projections;

            _lastCatalogEventNumber = 0;
            do
            {
                Log("Reading catalog chunk...");
                projections = _connection.ReadStreamEventsForward("$projections-$all", _lastCatalogEventNumber, 100, false, _credentials);
                Log("{0} events loaded", projections.Events.Length);
                foreach (var e in projections.Events)
                {
                    if (e.Event.EventType == "$stream-created-implicit")
                    {
                        continue;
                    }
                    var projectionName = Encoding.UTF8.GetString(e.Event.Data);
                    if (e.Event.EventType == ProjectionCreatedOld)
                    {
                        Log("Old style projection registration found for: {0}", projectionName);
                        _oldStyleProjections.Add(projectionName);
                    }
                    else if (e.Event.EventType == ProjectionCreatedNew)
                    {
                        Log("New style projection registration found for: {0}", projectionName);
                        if (_oldStyleProjections.Contains(projectionName))
                        {
                            Log("Old style registration for the {0} is already upgraded", projectionName);
                            _oldStyleProjections.Remove(projectionName);
                        }
                    }
                    else
                    {
                        Log("Skipping event: {0}", e.Event.EventType);
                    }
                    _existingProjections.Add(projectionName);
                    _lastCatalogEventNumber = e.Event.EventNumber;
                }
            } while (!projections.IsEndOfStream);
            Log("Projection catalog loaded.");
        }
        public static void DeleteAllStreams(this IEventStoreConnection connection)
        {
            var slice = connection.ReadAllEventsForward(Position.Start, Int32.MaxValue, false,
                                                        EmbeddedEventStore.Instance.DefaultCredentials);
            var streams = slice.
                          Events.
                          Select(_ => _.OriginalStreamId).
                          Where(StreamNameIsNotReserved).
                          Distinct();

            foreach (var stream in
                     from _ in streams
                     let streamStatusSlice = connection.ReadStreamEventsForward(_, 0, 1, false)
                                             where streamStatusSlice.Status != SliceReadStatus.StreamDeleted &&
                                             streamStatusSlice.Status != SliceReadStatus.StreamNotFound
                                             select _)
            {
                connection.DeleteStream(stream, ExpectedVersion.Any, EmbeddedEventStore.Instance.DefaultCredentials);
            }
        }
        public void SavesCommitHeadersOnEachEvent()
        {
            var commitId = Guid.NewGuid();
            var aggregateToSave = new TestAggregate(Guid.NewGuid());
            aggregateToSave.ProduceEvents(20);
            _repo.Save(aggregateToSave, commitId, d => {
                d.Add("CustomHeader1", "CustomValue1");
                d.Add("CustomHeader2", "CustomValue2");
            });

            var read = _connection.ReadStreamEventsForward(string.Format("aggregate-{0}", aggregateToSave.Id), 1, 20, false);
            foreach (var serializedEvent in read.Events)
            {
                var parsedMetadata = JObject.Parse(Encoding.UTF8.GetString(serializedEvent.OriginalEvent.Metadata));
                var deserializedCommitId = parsedMetadata.Property("CommitId").Value.ToObject<Guid>();
                Assert.AreEqual(commitId, deserializedCommitId);

                var deserializedCustomHeader1 = parsedMetadata.Property("CustomHeader1").Value.ToObject<string>();
                Assert.AreEqual("CustomValue1", deserializedCustomHeader1);

                var deserializedCustomHeader2 = parsedMetadata.Property("CustomHeader2").Value.ToObject<string>();
                Assert.AreEqual("CustomValue2", deserializedCustomHeader2);
            }
        }
Example #19
0
        static void FromStream(IEventStoreConnection con, UserCredentials userCredentials)
        {
            var ad = new MyBudget.Infrastructure.EventStoreAdapter(address, userCredentials);

            // var sub = con.SubscribeToStreamFrom("$category-Users", null, true, Appeared, Live, Dropped, userCredentials);
            //   sub.Start();

            var read = con.ReadStreamEventsForward("lines_of_", 0, 1000, true, userCredentials);

            foreach (var e in read.Events)
            {
                var t = ad.TryGetDomainEvent(e);
            }
            var mre = new ManualResetEvent(false);

            mre.WaitOne(3000);

            var rgpsa = events.GroupBy(g => g.Event.EventId).ToList();
            int i     = 0;
            var rgps  = events.Select(s => new { s, position = i++ }).GroupBy(g => g.s.Event.EventId).ToList();

            //var rgps2 = read.Events.Select(s => new { s, position = i++ }).GroupBy(g => g.s.Event.EventId).ToList();

            foreach (var r in rgps)
            {
                var values = r.ToArray();

                foreach (var v in values)
                {
                    var t = ad.TryGetDomainEvent(v.s);
                }
            }


            Console.ReadLine();
        }
Example #20
0
        static void FromStream(IEventStoreConnection con, UserCredentials userCredentials)
        {
            var ad = new MyBudget.Infrastructure.EventStoreAdapter(address, userCredentials);

            // var sub = con.SubscribeToStreamFrom("$category-Users", null, true, Appeared, Live, Dropped, userCredentials);
            //   sub.Start();

            var read = con.ReadStreamEventsForward("lines_of_", 0, 1000, true, userCredentials);

            foreach (var e in read.Events)
            {
                var t = ad.TryGetDomainEvent(e);

            }
            var mre = new ManualResetEvent(false);
            mre.WaitOne(3000);

            var rgpsa = events.GroupBy(g => g.Event.EventId).ToList();
            int i = 0;
            var rgps = events.Select(s => new { s, position = i++ }).GroupBy(g => g.s.Event.EventId).ToList();
            //var rgps2 = read.Events.Select(s => new { s, position = i++ }).GroupBy(g => g.s.Event.EventId).ToList();

            foreach (var r in rgps)
            {
                var values = r.ToArray();

                foreach (var v in values)
                {

                    var t = ad.TryGetDomainEvent(v.s);
                }
            }


            Console.ReadLine();
        }
        protected override void ReadEventsTill(IEventStoreConnection connection, bool resolveLinkTos, 
                                               UserCredentials userCredentials, long? lastCommitPosition, int? lastEventNumber)
        {
            bool done;
            do
            {
                var slice = connection.ReadStreamEventsForward(StreamId, _nextReadEventNumber, ReadBatchSize, resolveLinkTos, userCredentials);
                switch (slice.Status)
                {
                    case SliceReadStatus.Success:
                    {
                        foreach (var e in slice.Events)
                        {
                            TryProcess(e);
                        }
                        _nextReadEventNumber = slice.NextEventNumber;
                        done = lastEventNumber == null ? slice.IsEndOfStream : slice.NextEventNumber > lastEventNumber;
                        break;
                    }
                    case SliceReadStatus.StreamNotFound:
                    {
                        if (lastEventNumber.HasValue && lastEventNumber != -1)
                            throw new Exception(string.Format("Impossible: stream {0} disappeared in the middle of catching up subscription.", StreamId));
                        done = true;
                        break;
                    }
                    case SliceReadStatus.StreamDeleted:
                        throw new StreamDeletedException(StreamId);
                    default:
                        throw new ArgumentOutOfRangeException(string.Format("Unexpected StreamEventsSlice.Status: {0}.", slice.Status));
                }

                if (!done && slice.IsEndOfStream)
                    Thread.Sleep(1); // we are waiting for server to flush its data
            } while (!done);

            if (Verbose)
                Log.Debug("Catch-up Subscription to {0}: finished reading events, nextReadEventNumber = {1}.",
                          IsSubscribedToAll ? "<all>" : StreamId, _nextReadEventNumber);
        }
 protected void ReadStreamForward(string streamId, string login, string password)
 {
     Connection.ReadStreamEventsForward(streamId, 0, 1, false,
                                        login == null && password == null ? null : new UserCredentials(login, password));
 }
Example #23
0
        ResolvedEvent GetInputMessage(string actorId, int minVersion)
        {
            var slice = _connection.ReadStreamEventsForward(actorId + "-input", minVersion, 1, true);

            return(slice.Events.Single());
        }
        public static IEnumerable <ResolvedEvent> RecentEvents(string stream)
        {
            var results = esConn.ReadStreamEventsForward(stream, 0, 20, false);

            return(results.Events);
        }
Example #25
0
        public void soft_deleted_stream_returns_no_stream_and_no_events_on_read()
        {
            const string stream = "soft_deleted_stream_returns_no_stream_and_no_events_on_read";

            Assert.AreEqual(1, _conn.AppendToStream(stream, ExpectedVersion.NoStream, TestEvent.NewTestEvent(), TestEvent.NewTestEvent()).NextExpectedVersion);
            _conn.DeleteStream(stream, 1);

            var res = _conn.ReadStreamEventsForward(stream, 0, 100, false);

            Assert.AreEqual(SliceReadStatus.StreamNotFound, res.Status);
            Assert.AreEqual(0, res.Events.Length);
            Assert.AreEqual(1, res.LastEventNumber);
        }