Пример #1
0
        protected Event Serialize(IVersionedEvent e)
        {
            Event serialized;

            using (var writer = new StringWriter())
            {
                this.serializer.Serialize(writer, e);
                serialized = new Event
                {
                    SourceId       = e.SourceId,
                    SourceType     = _sourceType,
                    Version        = e.Version,
                    Payload        = writer.ToString(),
                    CorrelationId  = e.CorrelationId,
                    EventType      = e.GetType().Name,
                    CreationDate   = e.CreationDate,
                    LastUpdateTime = dateTime.Now
                };
            }

            var projectable = e as IProjectableEvent;

            if (projectable != null)
            {
                serialized.IsProjectable = true;
            }
            else
            {
                serialized.IsProjectable = false;
            }

            return(serialized);
        }
Пример #2
0
        public virtual void ApplyUpdate(IVersionedEvent versionedEvent)
        {
            if (!_isUpdateHandlersRegistered)
            {
                RegisterUpdateHandlers();
                _isUpdateHandlersRegistered = true;
            }

            if (_handlers.TryGetValue(versionedEvent.GetType(), out var eventHandler))
            {
                eventHandler(versionedEvent);
            }

            var eventSourcedEntities = GetChildEntities();

            if (!eventSourcedEntities.Any())
            {
                return;
            }

            eventSourcedEntities.ToList().ForEach(eventSourcedEntity =>
            {
                eventSourcedEntity.ApplyUpdate(versionedEvent);
            });
        }
Пример #3
0
        private EventData ToEventData(IVersionedEvent versionedEvent)
        {
            var eventType = versionedEvent.GetType().Name;

            var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(versionedEvent, _serializerSettings));

            return(new EventData(versionedEvent.EventId, eventType, true, body, new byte[0]));
        }
Пример #4
0
 public void Update(IVersionedEvent versionedEvent)
 {
     versionedEvent.SourceId = entity.Id;
     versionedEvent.Version  = Version + 1;
     this.handlers[versionedEvent.GetType()].Invoke(versionedEvent);
     Version = versionedEvent.Version;
     this.events.Enqueue(versionedEvent);
 }
Пример #5
0
 private StoredEvent ToStoredEvent(IVersionedEvent versionedEvent)
 {
     return(new StoredEvent(
                versionedEvent.SourceId,
                _aggregateType,
                JsonConvert.SerializeObject(versionedEvent, _serializerSettings),
                versionedEvent.Version,
                versionedEvent.GetType().Name,
                null));
 }
Пример #6
0
        private void WriteEvent(IVersionedEvent e)
        {
            var command = _sqlConnection.CreateCommand();

            command.CommandText = @"INSERT INTO [TodoItem] ([Id], [Version], [EventName], [EventData]) VALUES (@id, @version, @eventName, @eventData)";
            command.Parameters.AddWithValue("@id", e.SourceId);
            command.Parameters.AddWithValue("@version", e.Version);
            command.Parameters.AddWithValue("@eventName", e.GetType().Name);
            command.Parameters.AddWithValue("@eventData", JsonConvert.SerializeObject(e));
            command.ExecuteNonQuery();
        }
 private Log BuildConsumedEventEntity <Log>(IVersionedEvent e)
     where Log : class, IProcessedEvent, new()
 {
     return(new Log
     {
         SourceId = e.SourceId,
         SourceType = e.SourceType,
         Version = e.Version,
         EventType = e.GetType().Name,
         CorrelationId = e.CorrelationId
     });
 }
        public EventData Serialize(IVersionedEvent e, Type sourceType, string correlationId)
        {
            using (var writer = new StringWriter())
            {
                _serializer.Serialize(writer, e);
                var eventType = e.GetType();
                return(new EventData
                {
                    Version = e.Version,
                    SourceId = e.SourceId.ToString(),
                    Payload = writer.ToString(),
                    SourceType = sourceType.Name,
                    CorrelationId = correlationId,

                    AssemblyName = e.GetType().Assembly.FullName,
                    Namespace = eventType.Namespace,
                    TypeName = eventType.Name,
                    FullName = eventType.FullName
                });
            }
        }
        static EventData Serialize(IVersionedEvent @event, string correlationId)
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }
            var json     = JsonSerializer.SerializeToString(@event);
            var metadata = new Dictionary <string, object> {
                { "correlationId", correlationId }
            };

            return(new EventData(Guid.NewGuid(), @event.GetType().FullName, true, json.ToUtf8Bytes(), metadata.ToJson().ToUtf8Bytes()));
        }
Пример #10
0
        private void Raise(IVersionedEvent @event, bool isNew)
        {
            Action <IVersionedEvent> handler;

            if (_handlers.TryGetValue(@event.GetType(), out handler))
            {
                handler(@event);
            }

            Version = @event.Version;

            if (isNew)
            {
                _uncommittedEvents.Add(@event);
            }
        }
Пример #11
0
        private Event Serialize(IVersionedEvent e, string correlationId)
        {
            Event serialized;

            using (var writer = new StringWriter())
            {
                this.serializer.Serialize(writer, e);
                serialized = new Event
                {
                    AggregateId   = e.SourceId,
                    AggregateType = sourceType,
                    Version       = e.Version,
                    Payload       = writer.ToString(),
                    CorrelationId = correlationId,
                    EventType     = e.GetType().FullName,
                    EventDate     = DateTime.UtcNow
                };
            }
            return(serialized);
        }
Пример #12
0
 private void Invoke(IVersionedEvent @event)
 {
     _handlers[@event.GetType()](@event);
 }
        public void Project(IVersionedEvent e, Action <T> doProjectionOrRebuild)
        {
            if (isLiveProjection)
            {
                using (var context = this.liveContextFactory.Invoke())
                {
                    if (context
                        .ReadModelingEvents
                        .Where(log =>
                               log.SourceId == e.SourceId &&
                               log.SourceType == e.SourceType &&
                               log.Version >= e.Version)
                        .Any())
                    {
                        tracer.TraceAsync("Read model is up to date for event type: " + e.GetType().ToString());
                        return;
                    }

                    doProjectionOrRebuild(context);

                    // Mark as projected in the the subscription log
                    context.ReadModelingEvents.Add(this.BuildProjectedEventEntity(e));

                    context.SaveChanges();
                }
            }
            else
            {
                doProjectionOrRebuild(this.rebuildContext as T);

                this.rebuildContext.AddToUnityOfWork(this.BuildProjectedEventEntity(e));
            }
        }
        public void Consume <Log>(IVersionedEvent e, Action doConsume)
            where Log : class, IProcessedEvent, new()
        {
            if (isLiveProjection)
            {
                using (var context = this.liveContextFactory.Invoke())
                {
                    if (context.Set <Log>()
                        .Where(l =>
                               l.SourceId == e.SourceId &&
                               l.SourceType == e.SourceType &&
                               l.EventType == ((object)e).GetType().FullName&&
                               l.Version >= e.Version)
                        .Any())
                    {
                        tracer.TraceAsync(string.Format("Event {0} was already consumed by {1}", e.GetType().Name, typeof(Log).Name));
                        return;
                    }


                    // Si el proceso esta en vivo, entonces se consume.
                    // Si se esta reconstruyendo el read model, entonces se
                    // omite la consumision (por ejemplo: evitar que se envíen
                    // correos cada vez que se reconstruya el read model.
                    doConsume();

                    // Mark as consumed in the consumers subscription log
                    context.AddToUnityOfWork(this.BuildConsumedEventEntity <Log>(e));

                    context.SaveChanges();
                }
            }
            else
            {
                this.rebuildContext.AddToUnityOfWork(this.BuildConsumedEventEntity <Log>(e));
            }
        }
Пример #15
0
 private Stream Serialize(IVersionedEvent @event)
 {
     return new Stream() {
         Key = new SourceKey(@event.Id, @event.GetType()),
         Version = @event.Version,
         Payload = _binarySerializer.Serialize(@event)
     };
 }
Пример #16
0
        private bool ProcessEvent(HandlerDescriptor handlerDescriptor, IVersionedEvent @event, string eventId,
                                  IDictionary <string, object> items)
        {
            var sourceInfo = (SourceInfo)items[StandardMetadata.SourceInfo];
            var traceInfo  = (TraceInfo)items[StandardMetadata.TraceInfo];

            if (@event.Version > 1)
            {
                var lastPublishedVersion = _publishedVersionStore.GetPublishedVersion(sourceInfo) + 1;
                if (lastPublishedVersion < @event.Version)
                {
                    var envelope = new Envelope <IEvent>(@event, eventId)
                    {
                        Items = items
                    };
                    _eventBus.Send(envelope);

                    if (LogManager.Default.IsDebugEnabled)
                    {
                        LogManager.Default.DebugFormat(
                            "The event cannot be process now as the version is not the next version, it will be handle later. aggregateRootType={0},aggregateRootId={1},lastPublishedVersion={2},eventVersion={3},eventType={4}.",
                            sourceInfo.Type.FullName,
                            sourceInfo.Id,
                            lastPublishedVersion,
                            @event.Version,
                            @event.GetType().FullName);
                    }

                    return(false);
                }

                if (lastPublishedVersion > @event.Version)
                {
                    if (LogManager.Default.IsDebugEnabled)
                    {
                        LogManager.Default.DebugFormat(
                            "The event is ignored because it is obsoleted. aggregateRootType={0},aggregateRootId={1},lastPublishedVersion={2},eventVersion={3},eventType={4}.",
                            sourceInfo.Type.FullName,
                            sourceInfo.Id,
                            lastPublishedVersion,
                            @event.Version,
                            @event.GetType().FullName);
                    }

                    return(false);
                }
            }

            var context = new EventContext(_commandBus, _resultBus);

            context.SourceInfo = sourceInfo;
            context.TraceInfo  = traceInfo;
            if (items.ContainsKey(StandardMetadata.CommandInfo))
            {
                context.CommandInfo = (SourceInfo)items[StandardMetadata.CommandInfo];
            }

            try {
                handlerDescriptor.Invode(context, @event);
                context.Commit();
            }
            catch (Exception ex)
            {
                var commandResult = new CommandResult(HandleStatus.SyncFailed, ex.Message)
                {
                    Result    = _serializer.Serialize(ex.Data),
                    ReplyType = CommandReturnMode.EventHandled
                };
                _resultBus.Send(commandResult, traceInfo);
                return(false);
            }

            _publishedVersionStore.AddOrUpdatePublishedVersion(sourceInfo, @event.Version);

            return(true);
        }