Represent an Event that has not been committed to the Event Store.
Inheritance: Event
Exemplo n.º 1
0
 protected virtual void OnEventApplied(UncommittedEvent evnt)
 {
     if (EventApplied != null)
     {
         EventApplied(this, new EventAppliedEventArgs(evnt));
     }
 }
Exemplo n.º 2
0
        protected CommandTestFixture()
        {
            var commandExecutor = BuildCommandExecutor();

            PublishedEvents = new UncommittedEvent[0];

            SetupDependencies();
            try
            {
                var command = WhenExecutingCommand();

                using (var context = new EventContext())
                {
                    commandExecutor.Execute(command);

                    ExecutedCommand = command;

                    PublishedEvents = context.Events;
                }
            }
            catch (Exception exception)
            {
                CaughtException = exception;
            }
            finally
            {
                Finally();
            }
        }
Exemplo n.º 3
0
    /// <inheritdoc/>
    public async Task <IProjectionResult> Project(ProjectionCurrentState state, UncommittedEvent @event, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        try
        {
            _logger.ProjectEventThroughDispatcher(_embeddingId, state);
            var response = await _dispatcher.Call(
                _requestFactory.Create(state, @event),
                executionContext,
                cancellationToken).ConfigureAwait(false);

            if (IsFailureResponse(response))
            {
                return(new ProjectionFailedResult(GetFailureReason(response)));
            }
            return(response.ResponseCase switch
            {
                EmbeddingResponse.ResponseOneofCase.ProjectionDelete => new ProjectionDeleteResult(),
                EmbeddingResponse.ResponseOneofCase.ProjectionReplace => new ProjectionReplaceResult(response.ProjectionReplace.State),
                EmbeddingResponse.ResponseOneofCase.Compare
                => new ProjectionFailedResult(new UnexpectedEmbeddingResponse(_embeddingId, response.ResponseCase)),
                EmbeddingResponse.ResponseOneofCase.Delete
                => new ProjectionFailedResult(new UnexpectedEmbeddingResponse(_embeddingId, response.ResponseCase)),
                _ => new ProjectionFailedResult(new UnexpectedEmbeddingResponse(_embeddingId, response.ResponseCase))
            });
        }
Exemplo n.º 4
0
 Task InsertEvent(
     IClientSessionHandle transaction,
     EventLogSequenceNumber version,
     DateTimeOffset occurred,
     EventSourceId eventSource,
     UncommittedEvent @event,
     AggregateMetadata aggregate,
     Execution.ExecutionContext executionContext,
     CancellationToken cancellationToken)
 {
     return(_streams.DefaultEventLog.InsertOneAsync(
                transaction,
                new Event(
                    version,
                    executionContext.ToStoreRepresentation(),
                    new EventMetadata(
                        occurred.UtcDateTime,
                        eventSource,
                        @event.Type.Id,
                        @event.Type.Generation,
                        @event.Public),
                    aggregate,
                    new EventHorizonMetadata(),
                    BsonDocument.Parse(@event.Content)),
                cancellationToken: cancellationToken));
 }
Exemplo n.º 5
0
        /// <summary>Saves the event to the data store.</summary>
        /// <param name="uncommittedEvent">The event to save.</param>
        /// <param name="transaction">The transaction.</param>
        private void SaveEvent(UncommittedEvent uncommittedEvent, SqlTransaction transaction)
        {
            Contract.Requires <ArgumentNullException>(uncommittedEvent != null, "The argument uncommittedEvent could not be null.");
            Contract.Requires <ArgumentNullException>(transaction != null, "The argument transaction could not be null.");

            string eventName;
            var    document    = _formatter.Serialize(uncommittedEvent.Payload, out eventName);
            var    storedEvent = new StoredEvent <JObject>(uncommittedEvent.EventIdentifier, uncommittedEvent.EventTimeStamp,
                                                           eventName, uncommittedEvent.EventVersion, uncommittedEvent.EventSourceId,
                                                           uncommittedEvent.EventSequence, document);
            var raw = _translator.TranslateToRaw(storedEvent);

            using (var command = new SqlCommand(Queries.InsertNewEventQuery, transaction.Connection))
            {
                command.Transaction = transaction;
                command.Parameters.AddWithValue("EventId", raw.EventIdentifier);
                command.Parameters.AddWithValue("TimeStamp", raw.EventTimeStamp);
                command.Parameters.AddWithValue("EventSourceId", raw.EventSourceId);
                command.Parameters.AddWithValue("Name", raw.EventName);
                command.Parameters.AddWithValue("Version", raw.EventVersion.ToString());
                command.Parameters.AddWithValue("Sequence", raw.EventSequence);
                command.Parameters.AddWithValue("Data", raw.Data);
                command.ExecuteNonQuery();
            }
        }
Exemplo n.º 6
0
 private static bool AreEqual(UncommittedEvent uncommitted, CommittedEvent committed)
 {
     return(uncommitted.EventIdentifier == committed.EventIdentifier &&
            uncommitted.EventSourceId == committed.EventSourceId &&
            uncommitted.Payload.Equals(committed.Payload) &&
            uncommitted.EventSequence == committed.EventSequence);
 }
Exemplo n.º 7
0
        /// <inheritdoc/>
        public async Task <CommittedEvent> CommitEvent(
            IClientSessionHandle transaction,
            EventLogSequenceNumber sequenceNumber,
            DateTimeOffset occurred,
            Execution.ExecutionContext executionContext,
            UncommittedEvent @event,
            CancellationToken cancellationToken)
        {
            var eventSource = EventSourceId.NotSet;

            await InsertEvent(
                transaction,
                sequenceNumber,
                occurred,
                eventSource,
                @event,
                new AggregateMetadata(),
                executionContext,
                cancellationToken).ConfigureAwait(false);

            return(new CommittedEvent(
                       sequenceNumber,
                       occurred,
                       eventSource,
                       executionContext,
                       @event.Type,
                       @event.Public,
                       @event.Content));
        }
Exemplo n.º 8
0
        protected virtual void Emit <TEvent>(TEvent aggregateEvent, IMetadata metadata = null)
            where TEvent : IAggregateEvent <TAggregate, TIdentity>
        {
            if (aggregateEvent == null)
            {
                throw new ArgumentNullException("aggregateEvent");
            }

            var now           = DateTimeOffset.Now;
            var extraMetadata = new Dictionary <string, string>
            {
                { MetadataKeys.Timestamp, now.ToString("o") },
                { MetadataKeys.TimestampEpoch, now.ToUnixTime().ToString() },
                { MetadataKeys.AggregateSequenceNumber, (Version + 1).ToString() },
                { MetadataKeys.AggregateName, GetType().Name.Replace("Aggregate", string.Empty) },
            };

            metadata = metadata == null
                ? new Metadata(extraMetadata)
                : metadata.CloneWith(extraMetadata);

            var uncommittedEvent = new UncommittedEvent(aggregateEvent, metadata);

            ApplyEvent(aggregateEvent);
            _uncommittedEvents.Add(uncommittedEvent);
        }
        /// <summary>
        /// Emits the specified aggregate event.
        /// </summary>
        /// <typeparam name="TEvent">The type of the event.</typeparam>
        /// <param name="aggregateEvent">The aggregate event.</param>
        /// <param name="metadata">The metadata.</param>
        /// <exception cref="ArgumentNullException">aggregateEvent</exception>
        protected override void Emit <TEvent>(TEvent aggregateEvent, IMetadata metadata = null)
        {
            if (EqualityComparer <TEvent> .Default.Equals(aggregateEvent, default(TEvent)))
            {
                throw new ArgumentNullException(nameof(aggregateEvent));
            }
            //Version = (int)sequenceStore.GetNextSequence(EventSequenceTableName);
            var aggregateSequenceNumber = Version + 1;

            var eventId = EventId.NewDeterministic(
                GuidFactories.Deterministic.Namespaces.Events,
                $"{Id.Value}-v{aggregateSequenceNumber}");
            var now           = DateTimeOffset.Now;
            var eventMetadata = new Metadata
            {
                Timestamp = now,
                AggregateSequenceNumber = (int)aggregateSequenceNumber,
                AggregateName           = Name.Value,
                AggregateId             = Id.Value,
                EventId = eventId
            };

            eventMetadata.Add(MetadataKeys.TimestampEpoch, now.ToUnixTime().ToString());
            if (metadata != null)
            {
                eventMetadata.AddRange(metadata);
            }

            var uncommittedEvent = new UncommittedEvent(aggregateEvent, eventMetadata);

            ApplyEvent(aggregateEvent);
            uncommittedEvents.Add(uncommittedEvent);
        }
Exemplo n.º 10
0
        private void SaveEvent(UncommittedEvent evnt, SQLiteTransaction transaction)
        {
            if (evnt == null || transaction == null)
            {
                throw new ArgumentNullException();
            }
            using (var dataStream = new MemoryStream())
            {
                var bag = _converter.Convert(evnt.Payload);

                var formatter = new BinaryFormatter();
                formatter.Serialize(dataStream, bag);
                var data = dataStream.ToArray();

                using (var cmd = new SQLiteCommand(Query.InsertNewEventQuery, transaction.Connection))
                {
                    cmd.SetTransaction(transaction)
                    .AddParam("SourceId", evnt.EventSourceId)
                    .AddParam("EventId", evnt.EventIdentifier)
                    .AddParam("Name", evnt.Payload.GetType().FullName)
                    .AddParam("Sequence", evnt.EventSequence)
                    .AddParam("Timestamp", evnt.EventTimeStamp.Ticks)
                    .AddParam("Data", data);
                    cmd.ExecuteNonQuery();
                }
            }
        }
Exemplo n.º 11
0
        protected virtual void Emit <TEvent>(TEvent aggregateEvent, IMetadata metadata = null)
            where TEvent : IAggregateEvent <TAggregate, TIdentity>
        {
            if (aggregateEvent == null)
            {
                throw new ArgumentNullException(nameof(aggregateEvent));
            }

            var aggregateSequenceNumber = Version + 1;
            var eventId = EventId.NewDeterministic(
                GuidFactories.Deterministic.Namespaces.Events,
                $"{Id.Value}-v{aggregateSequenceNumber}");
            var now           = DateTimeOffset.Now;
            var eventMetadata = new Metadata
            {
                Timestamp = now,
                AggregateSequenceNumber = aggregateSequenceNumber,
                AggregateName           = Name.Value,
                AggregateId             = Id.Value,
                EventId = eventId
            };

            eventMetadata.Add(MetadataKeys.TimestampEpoch, now.ToUnixTime().ToString());
            if (metadata != null)
            {
                eventMetadata.AddRange(metadata);
            }

            var uncommittedEvent = new UncommittedEvent(aggregateEvent, eventMetadata);

            ApplyEvent(aggregateEvent);
            _uncommittedEvents.Add(uncommittedEvent);
        }
Exemplo n.º 12
0
 protected override void AggregateRootEventAppliedHandler(AggregateRoot aggregateRoot, UncommittedEvent evnt)
 {
     var message = new EventMessage
                       {
                           Body = new StoredEvent
                                      {
                                          Body = evnt.Payload,
                                          CommitId = _commitId,
                                          EventId = evnt.EventIdentifier,
                                          MajorVersion = evnt.EventVersion.Major,
                                          MinorVersion = evnt.EventVersion.Minor,
                                          Sequence = evnt.EventSequence,
                                          TimeStamp = evnt.EventTimeStamp
                                      }
                       };
     IEventStream stream;
     var id = aggregateRoot.EventSourceId;
     if (!_trackedStreams.TryGetValue(id, out stream))
     {
         stream = _eventStore.CreateStream(id);
         _trackedStreams[id] = stream;
     }
     stream.Add(message);
     _eventStream.Append(evnt);
     _dirtyInstances.Add(aggregateRoot);
 }
Exemplo n.º 13
0
 public void Append(UncommittedEvent uncommitted)
 {
     if (uncommitted == null)
     {
         throw new ArgumentNullException(nameof(uncommitted));
     }
     _batch.Add(uncommitted);
 }
Exemplo n.º 14
0
        protected override void OnEventApplied(UncommittedEvent appliedEvent)
        {
            base.OnEventApplied(appliedEvent);
            var callbacks = _eventAppliedCallbacks.Value;

            foreach (var callback in callbacks)
            {
                Log.DebugFormat("Calling event applied callback {0} for event {1} in aggregate root {2}", callback.GetHashCode(), appliedEvent, this);
                callback(this, appliedEvent);
            }
        }
Exemplo n.º 15
0
 public static void WriteTo(this UncommittedEvent e, Stream outputStream)
 {
     outputStream.Write(e.StreamId.ToByteArray(), 0, 16);
     outputStream.WriteVarInt63(e.SequenceNumber);
     outputStream.Write(e.TypeId.ToByteArray(), 0, 16);
     outputStream.WriteVarInt63(e.Created.ToUnixTimeMilliseconds());
     outputStream.WriteVarInt63(e.Payload.Count);
     if (0 < e.Payload.Count)
     {
         outputStream.Write(e.Payload.Array, e.Payload.Offset, e.Payload.Count);
     }
 }
Exemplo n.º 16
0
        public NcqrsEvent(UncommittedEvent @event) :
            base(@event.EventSourceId.ToString(), @event.EventIdentifier.ToString())
        {
            base.Timestamp = @event.EventTimeStamp;
            Name = @event.Payload.GetType().AssemblyQualifiedName;
            Sequence = @event.EventSequence;
            Version = @event.EventVersion.ToString();

            if (@event.Payload != null)
            {
                Data = Utility.Jsonize(@event.Payload, Name);
            }
        }
Exemplo n.º 17
0
        public NcqrsEvent(UncommittedEvent @event) :
            base(@event.EventSourceId.ToString(), @event.EventIdentifier.ToString())
        {
            base.Timestamp = @event.EventTimeStamp;
            Name           = @event.Payload.GetType().AssemblyQualifiedName;
            Sequence       = @event.EventSequence;
            Version        = @event.EventVersion.ToString();

            if (@event.Payload != null)
            {
                Data = Utility.Jsonize(@event.Payload, Name);
            }
        }
Exemplo n.º 18
0
        private UncommittedEvent GenerateMetadata(UncommittedEvent uncommittedEvent)
        {
            uncommittedEvent.Metadata = new MetadataCollection(new[]
            {
                new KeyValuePair <string, object>(MetadataKeys.EventId, Guid.NewGuid()),
                new KeyValuePair <string, object>(MetadataKeys.EventVersion, uncommittedEvent.Version),
                new KeyValuePair <string, object>(MetadataKeys.Timestamp, DateTime.UtcNow),
                new KeyValuePair <string, object>(MetadataKeys.EventClrType, uncommittedEvent.Data.GetType().AssemblyQualifiedName),
                new KeyValuePair <string, object>(MetadataKeys.EventName, uncommittedEvent.Data.GetType().Name)
            });


            return(uncommittedEvent);
        }
Exemplo n.º 19
0
 private static StoredEvent ToStoredEvent(Guid commitId, UncommittedEvent uncommittedEvent)
 {
     return(new StoredEvent
     {
         Id = uncommittedEvent.EventSourceId + "/" + uncommittedEvent.EventSequence,
         EventIdentifier = uncommittedEvent.EventIdentifier,
         EventTimeStamp = uncommittedEvent.EventTimeStamp,
         Version = uncommittedEvent.EventVersion,
         CommitId = commitId,
         Data = uncommittedEvent.Payload,
         EventSequence = uncommittedEvent.EventSequence,
         EventSourceId = uncommittedEvent.EventSourceId,
     });
 }
Exemplo n.º 20
0
 private static StoredEvent ToStoredEvent(Guid commitId, UncommittedEvent uncommittedEvent)
 {
     return new StoredEvent
     {
         Id = uncommittedEvent.EventSourceId + "/" + uncommittedEvent.EventSequence,
         EventIdentifier = uncommittedEvent.EventIdentifier,
         EventTimeStamp = uncommittedEvent.EventTimeStamp,
         Version = uncommittedEvent.EventVersion,
         CommitId = commitId,
         Data = uncommittedEvent.Payload,
         EventSequence = uncommittedEvent.EventSequence,
         EventSourceId = uncommittedEvent.EventSourceId,
     };
 }
Exemplo n.º 21
0
 public IEnumerable <IProcessingElement> Fetch(string pipelineName, int maxCount)
 {
     lock (this)
     {
         int count     = _random.Next(maxCount);
         int available = Count - _fetched;
         count = count > available ? available : count;
         for (int i = 0; i < count; i++)
         {
             _fetched++;
             var evnt = new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), _fetched, _fetched, DateTime.Now, new object(),
                                             new Version(1, 0));
             yield return(new SourcedEventProcessingElement(evnt));
         }
     }
 }
Exemplo n.º 22
0
        private UncommittedEvent GenerateMetadata(UncommittedEvent uncommittedEvent)
        {
            var metadatas = _metadataProviders.SelectMany(md => md.Provide(uncommittedEvent.Aggregate,
                                                                           uncommittedEvent.Data,
                                                                           MetadataCollection.Empty)).Concat(new[]
            {
                new KeyValuePair <string, object>(MetadataKeys.EventId, Guid.NewGuid()),
                new KeyValuePair <string, object>(MetadataKeys.EventVersion, uncommittedEvent.Version),
                new KeyValuePair <string, object>(MetadataKeys.Timestamp, DateTime.UtcNow),
            });

            var metadata = new MetadataCollection(metadatas);

            uncommittedEvent.Metadata = uncommittedEvent.Metadata.Merge(metadata);

            return(uncommittedEvent);
        }
Exemplo n.º 23
0
            public UncommittedEventStream ForSourceUncomitted(Guid id, Guid commitId, int sequenceOffset = 0)
            {
                int sequence       = sequenceOffset + 1;
                int initialVersion = sequenceOffset == 0 ? 1 : sequenceOffset;

                var comittedEvents = new List <CommittedEvent>();
                var result         = new UncommittedEventStream(commitId);

                foreach (var evnt in _events)
                {
                    var uncommittedEvent = new UncommittedEvent(Guid.NewGuid(), id, sequence, initialVersion, DateTime.UtcNow,
                                                                evnt, new Version(1, 0));
                    result.Append(uncommittedEvent);
                    sequence++;
                }
                return(result);
            }
Exemplo n.º 24
0
 public byte[] GetBytes(UncommittedEvent evnt)
 {
     string eventName;
     JObject serializedPayload = _formatter.Serialize(evnt.Payload, out eventName);
     var output = new MemoryStream();
     var writer = new BinaryWriter(output);
     writer.Write(evnt.CommitId.ToByteArray());
     writer.Write(evnt.EventIdentifier.ToByteArray());
     writer.Write(evnt.EventSequence);
     writer.Write(evnt.EventTimeStamp.Ticks);
     writer.Write(eventName);
     writer.Write(evnt.EventVersion.ToString());
     var bsonWriter = new BsonWriter(output);
     serializedPayload.WriteTo(bsonWriter);
     bsonWriter.Flush();
     output.Flush();
     return output.ToArray();
 }
Exemplo n.º 25
0
        public void SetUp()
        {
            _testEvent = new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), 1, 1, DateTime.UtcNow, new FakeEvent(),
                                              new Version(1, 0));
            _handler1  = MockRepository.GenerateMock <IEventHandler <FakeEvent> >();
            _handler2  = MockRepository.GenerateMock <IEventHandler <FakeEventBase> >();
            _handler3  = MockRepository.GenerateMock <IEventHandler <IFakeEventInterface> >();
            _container = new WindsorContainer();
            _container.Register(
                Component.For <IWindsorContainer>().Instance(_container),
                Component.For <IEventHandler <FakeEvent> >().Instance(_handler1),
                Component.For <IEventHandler <FakeEventBase> >().Instance(_handler2),
                Component.For <IEventHandler <IFakeEventInterface> >().Instance(_handler3),
                Component.For <IEventBus>().ImplementedBy <WindsorInProcessEventBus>());
            var svc = _container.Resolve <IEventBus>();

            svc.Publish(_testEvent);
        }
Exemplo n.º 26
0
        internal protected void ApplyEvent(object evnt)
        {
            Log.DebugFormat("Applying an event to event source {0}", evnt);
            var eventVersion  = evnt.GetType().Assembly.GetName().Version;
            var eventSequence = GetNextSequence();
            var wrappedEvent  = new UncommittedEvent(_idGenerator.GenerateNewId(), EventSourceId, eventSequence, _initialVersion, DateTime.UtcNow, evnt, eventVersion);

            //Legacy stuff...
            var sourcedEvent = evnt as ISourcedEvent;

            if (sourcedEvent != null)
            {
                sourcedEvent.ClaimEvent(EventSourceId, eventSequence);
            }
            Log.DebugFormat("Handling event {0} in event source {1}", wrappedEvent, this);
            HandleEvent(wrappedEvent.Payload);
            Log.DebugFormat("Notifying about application of an event {0} to event source {1}", wrappedEvent, this);
            OnEventApplied(wrappedEvent);
        }
Exemplo n.º 27
0
        public byte[] GetBytes(UncommittedEvent evnt)
        {
            string  eventName;
            JObject serializedPayload = _formatter.Serialize(evnt.Payload, out eventName);
            var     output            = new MemoryStream();
            var     writer            = new BinaryWriter(output);

            writer.Write(evnt.CommitId.ToByteArray());
            writer.Write(evnt.EventIdentifier.ToByteArray());
            writer.Write(evnt.EventSequence);
            writer.Write(evnt.EventTimeStamp.Ticks);
            writer.Write(eventName);
            writer.Write(evnt.EventVersion.ToString());
            var bsonWriter = new BsonWriter(output);

            serializedPayload.WriteTo(bsonWriter);
            bsonWriter.Flush();
            output.Flush();
            return(output.ToArray());
        }
Exemplo n.º 28
0
        /// <summary>Saves the event to the data store.</summary>
        /// <param name="evnt">The event to save.</param>
        /// <param name="transaction">The transaction.</param>
        private void SaveEvent(UncommittedEvent evnt, NpgsqlTransaction transaction)
        {
            string eventName;
            var    document    = _formatter.Serialize(evnt.Payload, out eventName);
            var    storedEvent = new StoredEvent <JObject>(evnt.EventIdentifier, evnt.EventTimeStamp, eventName, evnt.EventVersion, evnt.EventSourceId, evnt.EventSequence, document);
            var    raw         = _translator.TranslateToRaw(storedEvent);

            using (var command = new NpgsqlCommand(Queries.InsertNewEventQuery, transaction.Connection))
            {
                command.Transaction = transaction;
                command.Parameters.AddWithValue("EventId", raw.EventIdentifier);
                command.Parameters.AddWithValue("TimeStamp", raw.EventTimeStamp);
                command.Parameters.AddWithValue("EventSourceId", raw.EventSourceId);
                command.Parameters.AddWithValue("Name", raw.EventName);
                command.Parameters.AddWithValue("Version", raw.EventVersion.ToString());
                command.Parameters.AddWithValue("Sequence", raw.EventSequence);
                command.Parameters.AddWithValue("Data", raw.Data);
                command.ExecuteNonQuery();
            }
        }
Exemplo n.º 29
0
        public void SetUp()
        {
            _testEvent = new UncommittedEvent(Guid.NewGuid(), Guid.NewGuid(), 1, 1, DateTime.UtcNow, new FakeEvent(),
                                              new Version(1, 0));
            _handler1 = new Mock <IEventHandler <FakeEvent> >(MockBehavior.Strict);
            _handler1.Setup(x => x.Handle(It.IsAny <IPublishedEvent <FakeEvent> >())).Verifiable();
            _handler2 = new Mock <IEventHandler <FakeEventBase> >(MockBehavior.Strict);
            _handler2.Setup(x => x.Handle(It.IsAny <IPublishedEvent <FakeEventBase> >())).Verifiable();
            _handler3 = new Mock <IEventHandler <IFakeEventInterface> >(MockBehavior.Strict);
            _handler3.Setup(x => x.Handle(It.IsAny <IPublishedEvent <IFakeEventInterface> >())).Verifiable();
            _container = new WindsorContainer();
            _container.Register(
                Component.For <IWindsorContainer>().Instance(_container),
                Component.For <IEventHandler <FakeEvent> >().Instance(_handler1.Object),
                Component.For <IEventHandler <FakeEvent> >().Instance(_handler2.Object),
                Component.For <IEventHandler <FakeEvent> >().Instance(_handler3.Object),
                Component.For <IEventBus>().ImplementedBy <WindsorInProcessEventBus>());
            var svc = _container.Resolve <IEventBus>();

            svc.Publish(_testEvent);
        }
Exemplo n.º 30
0
        /// <inheritdoc/>
        public async Task <CommittedAggregateEvent> CommitAggregateEvent(
            IClientSessionHandle transaction,
            Artifact aggregateRoot,
            AggregateRootVersion aggregateRootVersion,
            EventLogSequenceNumber version,
            DateTimeOffset occurred,
            EventSourceId eventSource,
            Execution.ExecutionContext executionContext,
            UncommittedEvent @event,
            CancellationToken cancellationToken)
        {
            await InsertEvent(
                transaction,
                version,
                occurred,
                eventSource,
                @event,
                new AggregateMetadata
            {
                WasAppliedByAggregate = true,
                TypeId         = aggregateRoot.Id,
                TypeGeneration = aggregateRoot.Generation,
                Version        = aggregateRootVersion
            },
                executionContext,
                cancellationToken).ConfigureAwait(false);

            return(new CommittedAggregateEvent(
                       aggregateRoot,
                       aggregateRootVersion,
                       version,
                       occurred,
                       eventSource,
                       executionContext,
                       @event.Type,
                       @event.Public,
                       @event.Content));
        }
Exemplo n.º 31
0
        protected void Emit <TEvent>(TEvent aggregateEvent, IMetadata metadata = null)
            where TEvent : AggregateEvent <TAggregate>
        {
            if (aggregateEvent == null)
            {
                throw new ArgumentNullException("aggregateEvent");
            }

            var extraMetadata = new Dictionary <string, string>
            {
                { MetadataKeys.Timestamp, DateTimeOffset.Now.ToString("o") },
                { MetadataKeys.AggregateSequenceNumber, (Version + 1).ToString() }
            };

            metadata = metadata == null
                ? new Metadata(extraMetadata)
                : metadata.CloneWith(extraMetadata);

            var uncommittedEvent = new UncommittedEvent(aggregateEvent, metadata);

            ApplyEvent(aggregateEvent);
            _uncommittedEvents.Add(uncommittedEvent);
        }
Exemplo n.º 32
0
 protected override void AggregateRootEventAppliedHandler(AggregateRoot aggregateRoot, UncommittedEvent evnt)
 {
     RegisterDirtyInstance(aggregateRoot);
     _eventStream.Append(evnt);
 }
Exemplo n.º 33
0
        protected override void AggregateRootEventAppliedHandler(AggregateRoot aggregateRoot, UncommittedEvent evnt)
        {
            var message = new EventMessage
            {
                Body = new StoredEvent
                {
                    Body         = evnt.Payload,
                    CommitId     = _commitId,
                    EventId      = evnt.EventIdentifier,
                    MajorVersion = evnt.EventVersion.Major,
                    MinorVersion = evnt.EventVersion.Minor,
                    Sequence     = evnt.EventSequence,
                    TimeStamp    = evnt.EventTimeStamp
                }
            };
            IEventStream stream;
            var          id = aggregateRoot.EventSourceId;

            if (!_trackedStreams.TryGetValue(id, out stream))
            {
                stream = _eventStore.CreateStream(id);
                _trackedStreams[id] = stream;
            }
            stream.Add(message);
            _eventStream.Append(evnt);
            _dirtyInstances.Add(aggregateRoot);
        }
        /// <summary>
        /// Saves the event to the data store.
        /// </summary>
        /// <param name="evnt">The event to save.</param>
        /// <param name="transaction">The transaction.</param>
        private void SaveEvent(UncommittedEvent evnt, NpgsqlTransaction transaction)
        {
            string eventName;
            var document = _formatter.Serialize(evnt.Payload, out eventName);
            var storedEvent = new StoredEvent<JObject>(evnt.EventIdentifier, evnt.EventTimeStamp,
                                                      eventName, evnt.EventVersion, evnt.EventSourceId,
                                                      evnt.EventSequence, document);
            var raw = _translator.TranslateToRaw(storedEvent);

            using (var command = new NpgsqlCommand(Queries.InsertNewEventQuery, transaction.Connection))
            {
                command.Transaction = transaction;
                command.Parameters.AddWithValue("EventId", raw.EventIdentifier);
                command.Parameters.AddWithValue("TimeStamp", raw.EventTimeStamp);
                command.Parameters.AddWithValue("EventSourceId", raw.EventSourceId);
                command.Parameters.AddWithValue("Name", raw.EventName);
                command.Parameters.AddWithValue("Version", raw.EventVersion.ToString());
                command.Parameters.AddWithValue("Sequence", raw.EventSequence);
                command.Parameters.AddWithValue("Data", raw.Data);
                command.ExecuteNonQuery();
            }
        }
Exemplo n.º 35
0
        protected internal void ApplyEvent(object evnt)
        {
            Log.DebugFormat("Applying an event to event source {0}", evnt);
            var eventVersion = evnt.GetType().Assembly.GetName().Version;
            var eventSequence = GetNextSequence();
            //Legacy stuff...
            var sourcedEvent = evnt as ISourcedEvent;
            if (sourcedEvent != null)
            {
                sourcedEvent.ClaimEvent(EventSourceId, eventSequence);
            }
            var wrappedEvent = new UncommittedEvent(_idGenerator.GenerateNewId(), EventSourceId, eventSequence, _initialVersion, DateTime.UtcNow, evnt, eventVersion);

            Log.DebugFormat("Handling event {0} in event source {1}", wrappedEvent, this);
            HandleEvent(wrappedEvent.Payload);
            Log.DebugFormat("Notifying about application of an event {0} to event source {1}", wrappedEvent, this);
            OnEventApplied(wrappedEvent);
        }
Exemplo n.º 36
0
 protected virtual void OnEventApplied(UncommittedEvent evnt)
 {
     if (EventApplied != null)
     {
         EventApplied(this, new EventAppliedEventArgs(evnt));
     }
 }
 public EventAppliedEventArgs(UncommittedEvent evnt)
 {
     _event = evnt;
 }
Exemplo n.º 38
0
 protected override void Given()
 {
     SetupDependencies();
     PublishedEvents = new UncommittedEvent[0];
     ExecutedCommand = WhenExecuting();
 }
        /// <summary>Saves the event to the data store.</summary>
        /// <param name="uncommittedEvent">The event to save.</param>
        /// <param name="transaction">The transaction.</param>
        private void SaveEvent(UncommittedEvent uncommittedEvent, SqlTransaction transaction)
        {
            Contract.Requires<ArgumentNullException>(uncommittedEvent != null, "The argument uncommittedEvent could not be null.");
            Contract.Requires<ArgumentNullException>(transaction != null, "The argument transaction could not be null.");

            string eventName;
            var document = _formatter.Serialize(uncommittedEvent.Payload, out eventName);
            var storedEvent = new StoredEvent<JObject>(uncommittedEvent.EventIdentifier, uncommittedEvent.EventTimeStamp,
                                                      eventName, uncommittedEvent.EventVersion, uncommittedEvent.EventSourceId,
                                                      uncommittedEvent.EventSequence, document);
            var raw = _translator.TranslateToRaw(storedEvent);

            using (var command = new SqlCommand(Queries.InsertNewEventQuery, transaction.Connection))
            {
                command.Transaction = transaction;
                command.Parameters.AddWithValue("EventId", raw.EventIdentifier);
                command.Parameters.AddWithValue("TimeStamp", raw.EventTimeStamp);
                command.Parameters.AddWithValue("EventSourceId", raw.EventSourceId);
                command.Parameters.AddWithValue("Name", raw.EventName);
                command.Parameters.AddWithValue("Version", raw.EventVersion.ToString());
                command.Parameters.AddWithValue("Sequence", raw.EventSequence);
                command.Parameters.AddWithValue("Data", raw.Data);
                command.ExecuteNonQuery();
            }
        }
Exemplo n.º 40
0
        private void SaveEvent(UncommittedEvent evnt, SQLiteTransaction transaction)
        {
            if (evnt == null || transaction == null) throw new ArgumentNullException();
            using (var dataStream = new MemoryStream())
            {
                var bag = _converter.Convert(evnt.Payload);

                var formatter = new BinaryFormatter();
                formatter.Serialize(dataStream, bag);
                var data = dataStream.ToArray();

                using (var cmd = new SQLiteCommand(Query.InsertNewEventQuery, transaction.Connection))
                {
                    cmd.SetTransaction(transaction)
                        .AddParam("SourceId", evnt.EventSourceId)
                        .AddParam("EventId", evnt.EventIdentifier)
                        .AddParam("Name", evnt.Payload.GetType().FullName)
                        .AddParam("Sequence", evnt.EventSequence)                        
                        .AddParam("Timestamp", evnt.EventTimeStamp.Ticks)
                        .AddParam("Data", data);
                    cmd.ExecuteNonQuery();
                }
            }
        }
 private static bool AreEqual(UncommittedEvent uncommitted, CommittedEvent committed)
 {
     return uncommitted.EventIdentifier == committed.EventIdentifier
            && uncommitted.EventSourceId == committed.EventSourceId
            && uncommitted.Payload.Equals(committed.Payload)
            && uncommitted.EventTimeStamp == committed.EventTimeStamp
            && uncommitted.EventSequence == committed.EventSequence;
 }