예제 #1
0
        private object ToEventObject(RecordedEvent eventData)
        {
            var headers   = JsonConvert.DeserializeObject <Dictionary <string, string> >(Encoding.GetString(eventData.Metadata));
            var eventType = Type.GetType(headers[EventTypeHeader]);

            return(JsonConvert.DeserializeObject(Encoding.GetString(eventData.Data), eventType));
        }
예제 #2
0
 public static T GetEvent <T>(this RecordedEvent evt)
 {
     {
         var eventString = Encoding.UTF8.GetString(evt.Data);
         return(JsonConvert.DeserializeObject <T>(eventString));
     }
 }
        public static IMessage ToMessage(this RecordedEvent recordedEvent)
        {
            var data = recordedEvent.Data;

            if (recordedEvent.Metadata.Length > 0)
            {
                var metadata = JObject.Parse(Encoding.UTF8.GetString(recordedEvent.Metadata));
                if (metadata["encoding"].Value <string>() == "gzip")
                {
                    using (var originalStream = new MemoryStream())
                    {
                        using (var compressedStream = new MemoryStream(data))
                            using (var gZipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                            {
                                gZipStream.CopyTo(originalStream);
                            }

                        data = originalStream.ToArray();
                    }
                }
            }

            if (Types.Value.TryGetValue(recordedEvent.EventType, out var factory))
            {
                var message = factory.Value.Invoke();
                message.MergeFrom(data);
                return(message);
            }

            return(null);
        }
예제 #4
0
        private static string GetEventClrTypeName(RecordedEvent eventData)
        {
            var eventClrTypeName = JObject.Parse(Encoding.UTF8.GetString(eventData.Metadata)).Property("EventClrType")
                                   .Value;

            return(eventClrTypeName.ToString());
        }
예제 #5
0
        public static IEnumerable <IEvent> Parse(this RecordedEvent data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            var value = Encoding.UTF8.GetString(data.Data);

            switch (data.EventType)
            {
            case nameof(AccountCreated): return(JsonConvert.DeserializeObject <AccountCreatedEventHandler>(value).Events);

            case nameof(DailyWireTransferLimitChanged): return(JsonConvert.DeserializeObject <DailyWireTransferLimitChangedEventHandler>(value).Events);

            case nameof(CashDeposited): return(JsonConvert.DeserializeObject <CashDepositedHandler>(value).Events);

            case nameof(OverdraftLimitChanged): return(JsonConvert.DeserializeObject <OverdraftLimitChangedEventHandler>(value).Events);

            case nameof(AccountBlocked): return(JsonConvert.DeserializeObject <AccountBlockedEventHandler>(value).Events);

            case nameof(CashWithdrawn): return(JsonConvert.DeserializeObject <CashWithdrawnEventHandler>(value).Events);

            case nameof(AccountUnblocked): return(JsonConvert.DeserializeObject <AccountUnblockedEventHandler>(value).Events);

            case nameof(WireTransfered): return(JsonConvert.DeserializeObject <WireTransferedEventHandler>(value).Events);

            case nameof(ChequeDeposited): return(JsonConvert.DeserializeObject <ChequeDepositedEventHandler>(value).Events);

            default: return(null);
            }
        }
        public IDisposable SubscribeToAllFrom(Position @from, Action <RecordedEvent> eventAppeared, CatchUpSubscriptionSettings settings = null,
                                              Action liveProcessingStarted    = null, Action <SubscriptionDropReason, Exception> subscriptionDropped = null,
                                              UserCredentials userCredentials = null, bool resolveLinkTos = true)
        {
            var current       = (int)@from.CommitPosition;
            var currentEvents = new RecordedEvent[] { };

            lock (_allStream) {
                if (@from == Position.End)
                {
                    current = _allStream.Count - 1;
                }

                if (current < _allStream.Count - 1)
                {
                    var events = new RecordedEvent[_allStream.Count - current];
                    _allStream.CopyTo(events, current);
                    currentEvents = events;
                }
            }

            for (int i = 0; i < currentEvents.Length; i++)
            {
                eventAppeared(currentEvents[i]);
            }

            var subscription = new AllStreamSubscription(current, subscriptionDropped, eventAppeared);

            subscription.BusSubscription = _inboundEventBus.Subscribe(subscription);
            _subscriptions.Add(subscription);
            liveProcessingStarted?.Invoke();
            return(subscription);
        }
예제 #7
0
        private static object DeserializeEvent(RecordedEvent eventData)
        {
            var eventClrTypeName = GetEventClrTypeName(eventData);

            return(JsonConvert.DeserializeObject(Encoding.UTF8.GetString(eventData.Data),
                                                 Type.GetType(eventClrTypeName)));
        }
예제 #8
0
 public override void Handle(TState s, RecordedEvent e)
 {
     if (e.Event is TEvent ev)
     {
         _action(s, ev, (ID)e.StreamID);
     }
 }
예제 #9
0
 private void Handle(TState s, RecordedEvent e)
 {
     foreach (EventRegistration handler in _handlers)
     {
         handler.Handle(s, e);
     }
 }
예제 #10
0
        private IEvent DeserializeEvent(RecordedEvent evt)
        {
            var targetType = GetEventType(evt.EventType);
            var json       = Encoding.UTF8.GetString(evt.Data);

            return(JsonConvert.DeserializeObject(json, targetType) as IEvent);
        }
예제 #11
0
        private static string GetStreamName(string?prefix, RecordedEvent @event)
        {
            var streamName = @event.EventStreamId;

            if (prefix != null && streamName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
            {
                streamName = streamName[(prefix.Length + 1)..];
예제 #12
0
        public static IDomainEvent ToDomainEvent(this RecordedEvent recordedEvent)
        {
            var data = recordedEvent.Data.FromUtf8();
            var meta = recordedEvent.Metadata.FromUtf8();

            var eventHeaders = JsonConvert.DeserializeObject <Dictionary <string, string> >(meta);

            if (!eventHeaders.ContainsKey(EventStoreConstants.EventTypeHeader))
            {
                throw new InvalidOperationException("EventTypeHeader Header not found");
            }

            var typeName = eventHeaders[EventStoreConstants.EventTypeHeader];

            Type eventClrType;

            if (EventTypeMap.Instance.Mappings.ContainsKey(typeName))
            {
                var b = EventTypeMap.Instance.Mappings.TryGetValue(typeName, out eventClrType);
                if (!b)
                {
                    throw new InvalidOperationException("Error with EventTypeMap");
                }
            }
            else
            {
                eventClrType = Type.GetType(typeName, true);
            }

            var o = JsonConvert.DeserializeObject(data, eventClrType);

            return(o as IDomainEvent);
        }
예제 #13
0
        public void Update(RecordedEvent evt)
        {
            var data = evt.Data;

            var dataJson = Encoding.UTF8.GetString(data);

            switch (evt.EventType)
            {
            case "OrderPaymentFailure":
                IsPaid = false;
                break;

            case "OrderPaymentSuccess":
                var order = JsonConvert.DeserializeObject <OrderModel>(dataJson);

                ProductCount = order.Products.Count;

                IsPaid     = true;
                IsPrepared = false;
                break;

            case "OrderPrepared":
                IsPrepared = true;
                break;

            default: break;
            }
        }
예제 #14
0
        public static object Deserialize(this RecordedEvent evt, EventTypeResolver eventTypeResolver)
        {
            var targetType = eventTypeResolver.GetTypeForEventName(evt.EventType);
            var json       = Encoding.UTF8.GetString(evt.Data);

            return(JsonConvert.DeserializeObject(json, targetType));
        }
        internal static TEvent ToDomainEvent <TEvent>(this RecordedEvent recordedEvent)
        {
            var value     = Encoding.UTF8.GetString(recordedEvent.Data);
            var eventType = Type.GetType(recordedEvent.EventType);

            return((TEvent)JsonConvert.DeserializeObject(value, eventType));
        }
예제 #16
0
        public static IEvent DeserializeEvent(this RecordedEvent orginalEvent)
        {
            var eventDataJson = Encoding.UTF8.GetString(orginalEvent.Data);

            if (string.IsNullOrWhiteSpace(eventDataJson) || eventDataJson == "{}")
            {
                throw new Exception("eventDataJson is empty");
            }

            var parsedObject   = JObject.Parse(eventDataJson);
            var metaDataJToken = parsedObject["Metadata"];

            if (metaDataJToken == null)
            {
                throw new Exception("metaDataJToken is null");
            }

            var eventMetadata = metaDataJToken.ToObject <EventMetadata>();
            var eventData     = DeserializeObject(eventDataJson, eventMetadata.CustomMetadata[EventClrTypeHeader]) as IEvent;

            if (eventData == null)
            {
                throw new Exception("eventData is null");
            }

            eventData.Metadata.EventNumber = orginalEvent.EventNumber;
            eventData.Metadata.EventId     = orginalEvent.EventId.ToString();

            return(eventData);
        }
예제 #17
0
        public static T Deserialize <T>(this RecordedEvent recordedEvent)
        {
            var data = recordedEvent.Data;
            var json = Encoding.UTF8.GetString(data);

            return(JsonConvert.DeserializeObject <T>(json));
        }
예제 #18
0
        private object DeserializeEvent(RecordedEvent recoredEvent)
        {
            Type   eventType = Type.GetType(recoredEvent.EventType);
            string dataJson  = Encoding.UTF8.GetString(recoredEvent.Data);

            return(JsonConvert.DeserializeObject(dataJson, eventType));
        }
        private static BankAccountEvent MapEventToDomain(RecordedEvent returnedEvent)
        {
            var eventType  = returnedEvent.EventType;
            var dataString = Encoding.UTF8.GetString(returnedEvent.Data);

            return(DeserializeEvent(eventType, dataString));
        }
예제 #20
0
 private void OnEvent(RecordedEvent recordedEvent, Position position)
 {
     if (Event != null)
     {
         Event(this, new RecordedEventEventArgs(recordedEvent));
     }
 }
예제 #21
0
        public void Record(IEnumerable <IEvent> eventBatch)
        {
            var recordedEvents = new List <RecordedEvent>();

            foreach (var e in eventBatch)
            {
                var timestamp      = DateTime.Now.ToUniversalTime();
                var sequencenumber = timestamp.Ticks.ToString("00000000000000000000") + _eventCounter++.ToSequenceNumber();
                var re             = new RecordedEvent(Guid.NewGuid(),
                                                       timestamp,
                                                       sequencenumber,
                                                       e.Name,
                                                       e.Context,
                                                       e.Data);

                var edoc = new BsonDocument {
                    { "_id", re.Id.ToString() },
                    { "timestamp", re.Timestamp },
                    { "sequencenumber", re.Sequencenumber },
                    { "name", re.Name },
                    { "context", re.Context },
                    { "data", re.Data }
                };
                _eventCol.Insert(edoc);

                recordedEvents.Add(re);
            }
            recordedEvents.ForEach(OnRecorded);
        }
예제 #22
0
        public Option <IEvent> FromEventData(RecordedEvent recordedEvent)
        {
            if (recordedEvent == null)
            {
                throw new ArgumentNullException(nameof(recordedEvent));
            }

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            if (recordedEvent.EventType.StartsWith("$"))
            {
                return(Option.None <IEvent>());
            }

            var json = Encoding.UTF8.GetString(recordedEvent.Data);

            var fromEventData = (IEvent)JsonConvert.DeserializeObject(json, Type.GetType(recordedEvent.EventType), settings);

            return(fromEventData == null
                ? Option.None <IEvent>()
                : Option.Some(fromEventData));
        }
        public void Handle(RecordedEvent recordedEvent, BookOrderResult result)
        {
            var st = Encoding.ASCII.GetString(recordedEvent.Data);
            T   ev = JsonConvert.DeserializeObject <T>(st);

            DoHandle(ev, result);
        }
예제 #24
0
        public TEvent FromEventData <TEvent>(RecordedEvent eventData)
            where TEvent : class, IAggregateEvent
        {
            var json = this._serializer.DeserializeFromBytes(eventData.Data);

            return(this._serializer.Deserialize <TEvent>(json));
        }
        public object Deserialize(RecordedEvent evt)
        {
            var targetType = GetTypeForEventName(evt.EventType);
            var json       = Encoding.UTF8.GetString(evt.Data);

            return(JsonConvert.DeserializeObject(json, targetType));
        }
예제 #26
0
        /// <summary>
        /// Deserialization of <see cref="IEvent"/>
        /// </summary>
        /// <param name="event">Event from EventStore</param>
        /// <returns>Domain event</returns>
        private IEvent Deserialize(RecordedEvent @event)
        {
            string data     = Encoding.UTF8.GetString(@event.Data);
            var    metadata = JsonConvert.DeserializeObject <EventMetadata>(Encoding.UTF8.GetString(@event.Metadata));

            return(JsonConvert.DeserializeObject(data, Type.GetType(metadata.AssemblyQualifiedName)) as IEvent);
        }
예제 #27
0
        public static void VerifyIfMatched(RecordedEvent evnt)
        {
            if (evnt.EventType.StartsWith("TestEvent"))
            {
                var data  = Encoding.UTF8.GetString(evnt.Data);
                var atoms = data.Split('-');
                if (atoms.Length != 3)
                {
                    throw new ApplicationException(string.Format("Invalid TestEvent object: currupted data format: {0}",
                                                                 RecordDetailsString(evnt)));
                }

                var expectedLength = int.Parse(atoms[1]);
                if (expectedLength != atoms[2].Length)
                {
                    throw new ApplicationException(string.Format("Invalid TestEvent object: not expected data length: {0}",
                                                                 RecordDetailsString(evnt)));
                }

                if (new string('#', expectedLength) != atoms[2])
                {
                    throw new ApplicationException(string.Format("Invalid TestEvent object: currupted data: {0}",
                                                                 RecordDetailsString(evnt)));
                }
            }
        }
        public static IDomainEvent ToDomainEvent(this RecordedEvent recordedEvent)
        {
            var serializedEventString = Encoding.UTF8.GetString(recordedEvent.Data);
            var eventMetaData         = EventMetaData.EventMetaDataFrom(recordedEvent);

            return(serializedEventString.ToDomainEventUsing(eventMetaData));
        }
예제 #29
0
        private object DeserializeEvent(RecordedEvent evt)
        {
            var targetType = _eventTypeResolver.GetTypeForEventName(evt.EventType);
            var json       = Encoding.UTF8.GetString(evt.Data);

            return(JsonConvert.DeserializeObject(json, targetType));
        }
예제 #30
0
 private StoredEvent ToStoredEvent(RecordedEvent recordedEvent)
 => new StoredEvent(
     recordedEvent.StreamId,
     recordedEvent.Id,
     recordedEvent.Number,
     recordedEvent.Type,
     recordedEvent.Created,
     (IDomainEvent)_serializer.Deserialize(recordedEvent));
예제 #31
0
 public void Write(string filename, RecordedEvent @event)
 {
     using (var sw = new StreamWriter(filename))
     {
         sw.WriteLine("1.0");
         sw.WriteLine(@event.Id);
         sw.WriteLine(@event.Timestamp.ToString("yyyy-MM-ddThh:mm:ss.fffffff"));
         sw.WriteLine(@event.Sequencenumber);
         sw.WriteLine(@event.Name);
         sw.WriteLine(@event.Context);
         sw.Write(@event.Data);
     }
 }
예제 #32
0
파일: Player.cs 프로젝트: ralfw/NBlackBox
        public IEnumerable<IRecordedEvent> Play()
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    var sb = new StringBuilder("SELECT sequencenumber, id, timestamp, name, context, data FROM events")
                                .AppendFormat(" WHERE sequencenumber >= {0}", fromSequenceNumber);

                    foreach (var nameConstraint in nameConstraints)
                    {
                        var options = String.Join(", ", nameConstraint.Select(SqliteStringEscape));
                        sb.AppendFormat(" AND name in ({0})", options);
                    }

                    foreach (var contextConstraint in contextConstraints)
                    {
                        var options = String.Join(", ", contextConstraint.Select(SqliteStringEscape));
                        sb.AppendFormat(" AND context in ({0})", options);
                    }

                    sb.AppendFormat(" ORDER BY sequencenumber");

                    command.CommandText = sb.ToString();

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var recordedEvent = new RecordedEvent(
                                Guid.Parse(reader.GetString(1)),
                                reader.GetDateTime(2),
                                reader.GetInt64(0).ToSequenceNumber(),
                                reader.GetString(3),
                                reader.GetString(4),
                                reader.GetString(5));
                            yield return recordedEvent;
                        }
                    }
                }
            }
        }
 void AssertRecordedEvent(int version, EventData source, RecordedEvent actual)
 {
     var expected = source.Record(partition, version);
     actual.ShouldMatch(expected.ToExpectedObject());
 }
예제 #34
0
        private void OnPackageReceived(TcpTypedConnection connection, TcpPackage package)
        {
            Subscription subscription;
            if(!_subscriptions.TryGetValue(package.CorrelationId, out subscription))
            {
                _log.Error("Unexpected package received : {0} ({1})", package.CorrelationId, package.Command);
                return;
            }

            try
            {
                switch (package.Command)
                {
                    case TcpCommand.StreamEventAppeared:
                        var dto = package.Data.Deserialize<ClientMessage.StreamEventAppeared>();
                        var recordedEvent = new RecordedEvent(dto);
                        var commitPos = dto.CommitPosition;
                        var preparePos = dto.PreparePosition;
                        ExecuteUserCallbackAsync(() => subscription.EventAppeared(recordedEvent, new Position(commitPos, preparePos)));
                        break;
                    case TcpCommand.SubscriptionDropped:
                    case TcpCommand.SubscriptionToAllDropped:
                        Subscription removed;
                        if(_subscriptions.TryRemove(subscription.Id, out removed))
                        {
                            removed.Source.SetResult(null);
                            ExecuteUserCallbackAsync(removed.SubscriptionDropped);
                        }
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(string.Format("Unexpected command : {0}", package.Command));
                }
            }
            catch (Exception e)
            {
                _log.Error(e, "Error on package received");
            }
        }