internal StreamEventsSlice(SliceReadStatus status, 
                                   string stream, 
                                   int fromEventNumber, 
                                   ReadDirection readDirection,
                                   ClientMessage.ResolvedIndexedEvent[] events,
                                   int nextEventNumber,
                                   int lastEventNumber,
                                   bool isEndOfStream)
        {
            Ensure.NotNullOrEmpty(stream, "stream");

            Status = status;
            Stream = stream;
            FromEventNumber = fromEventNumber;
            ReadDirection = readDirection;
            if (events == null || events.Length == 0)
                Events = Empty.ResolvedEvents;
            else
            {
                Events = new ResolvedEvent[events.Length];
                for (int i = 0; i < Events.Length; ++i)
                {
                    Events[i] = new ResolvedEvent(events[i]);
                }
            }
            NextEventNumber = nextEventNumber;
            LastEventNumber = lastEventNumber;
            IsEndOfStream = isEndOfStream;
        }
        private void GotEvent(EventStoreCatchUpSubscription sub, ResolvedEvent evt)
        {
            try
            {
                //create local copies of state variables
                var total = _total;
                var checkpoint = evt.Event.EventNumber;

                var amount = (string)JObject.Parse(Encoding.UTF8.GetString(evt.Event.Data))["amount"];
                switch (evt.Event.EventType.ToUpperInvariant())
                {
                    case "CREDIT":
                        total += int.Parse(amount);
                        break;
                    case "DEBIT":
                        total -= int.Parse(amount);
                        break;
                    default:
                        throw new Exception("Unknown Event Type");
                }
                File.WriteAllText(_localFile, checkpoint + "," + total);
                //Update the common state after commit to disk
                _total = total;
                Checkpoint = checkpoint;
            }
            catch (Exception ex)
            {
                _view.ErrorMsg = "Event Exception: " + ex.Message;
            }
            //repaint screen
            _view.Total = _total;
        }
        void EventAppeared(EventStoreCatchUpSubscription sub, ResolvedEvent evnt)
        {
            if (evnt.OriginalStreamId.StartsWith("$"))
                return;
    
            dynamic ev = _adapter.TryGetDomainEvent(evnt);
            if (ev == null)
                return;

            try
            {
                lock (this)
                {
                    Dispatch(ev);
                    _succeded++;
                    _checkPoint = evnt.OriginalPosition.GetValueOrDefault();
                    _lastEventNumber = evnt.OriginalEventNumber;
                    if(ev.Timestamp > LastUpdate)
                        LastUpdate = ev.Timestamp;
                }
            }
            catch (Exception)
            {
                Debugger.Break();
            }
           
        }
 private static void EventAppeared(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
     ResolvedEvent resolvedEvent)
 {
    ;
     var data = Encoding.ASCII.GetString(resolvedEvent.Event.Data);
     Console.WriteLine("Received: " + resolvedEvent.Event.EventStreamId + ":" + resolvedEvent.Event.EventNumber);
     Console.WriteLine(data);
 }
        private void CommandResponseReceived(EventStoreSubscription subscription, ResolvedEvent resolvedEvent)
        {
            if (ResponseReceived == null) return;

            var response = resolvedEvent.ParseJson<CommandResponse>();

            ResponseReceived(this, new CommandResponseEventArgs(response));
        }
        public static object DeserializeEventData(
            this ISerializer serializer,
            ResolvedEvent resolvedEvent)
        {
            IDictionary<string, object> _;

            return serializer.DeserializeEventData(resolvedEvent, out _);
        }
        private void ProcessEvent(EventStoreCatchUpSubscription subscribtion, ResolvedEvent resolvedEvent)
        {
            var alarm = resolvedEvent.ParseJson<IrresponsibleGamblerDetected>();

            Publish(alarm);

            StoreCheckpoint(resolvedEvent);
        }
Exemple #8
0
 private void HandleNewEvent(EventStoreCatchUpSubscription subscription, ResolvedEvent @event)
 {
     // make sure the event fits the ones this handler cares about
     if (!_eventFilter(@event)) { return; }
     var _event = ProcessRawEvent(@event);
     // filter for null event ( didn't have metadata or data )
     if (_event == null) { return; }
     HandleEvent(_event);
 }
Exemple #9
0
 dynamic GetDomainEvent(ResolvedEvent evnt)
 {
     var metadata = evnt.Event.Metadata;
     var data = evnt.Event.Data;
     var jmeta = JObject.Parse(Encoding.UTF8.GetString(metadata));
     var eventClrTypeName = jmeta.Property(EventClrTypeHeader).Value;
     dynamic ev = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), Type.GetType((string)eventClrTypeName));
     return ev;
 }
 private void EventAppeard(EventStoreSubscription subscription, ResolvedEvent @event)
 {
     var representation = _deserializer.GetRepresentation(_serializer, @event.OriginalEvent);
     var payload = representation.Payload;
     if (payload != null)
     {
         _self.Tell(payload);
     }
 }
Exemple #11
0
 public dynamic TryGetDomainEvent(ResolvedEvent evnt)
 {
     try
     {
         return GetDomainEvent(evnt);
     }
     catch
     {
         return null;
     }
 }
 public IEnumerable<object> Deserialize(ResolvedEvent resolvedEvent)
 {
     var type = Type.GetType(resolvedEvent.Event.EventType + ", UserService.DomainModel", true);
     using (var stream = new MemoryStream(resolvedEvent.Event.Data))
     {
         using (var reader = new StreamReader(stream))
         {
             yield return JsonSerializer.CreateDefault().Deserialize(reader, type);
         }
     }
 }
       private SyndicationItem MapToFeedItem(ResolvedEvent ev)
       {
           return new SyndicationItem(
               "BeganFollowingEvent",
               Encoding.UTF8.GetString(ev.Event.Data),
 new Uri(RequestContext.Url.Content("/beganfollowing/" +
   ev.Event.EventId)),
 ev.Event.EventId.ToString(),
               DateTime.Now // Event store client does not return timestamp yet
           );
       }
        private static EventEnvelope Map(ResolvedEvent resolvedEvent)
        {
            var bytesAsString = Encoding.UTF8.GetString(resolvedEvent.Event.Data);
            var a = JsonConvert.DeserializeObject(bytesAsString) as IEvent;
            var jsonMetadata = Encoding.UTF8.GetString(resolvedEvent.Event.Metadata);
            var metadata = JsonConvert.DeserializeObject<EventMetadata>(jsonMetadata);
            var typeName = Type.GetType(metadata.Type);
            var @event = (IEvent)JsonConvert.DeserializeObject(bytesAsString, typeName);
            var envelope = new EventEnvelope(@event, metadata);

            return envelope;
        }
 protected override void OnEventReceived(ResolvedEvent resolvedEvent)
 {
     switch (resolvedEvent.OriginalEvent.EventType)
     {
         case UserEventType.UserCreated:
             AddAccount(resolvedEvent.OriginalEvent);
             break;
         case ContactEventType.AccountContactRefreshRequest:
             ProcessRefreshRequest(resolvedEvent.OriginalEvent);
             break;
     }
 }
 public async Task PublishAsync(EventStorePersistentSubscriptionBase subscription, ResolvedEvent resolvedEvent) {
   try {
     object eventObject = resolvedEvent.Event.ToEventObject();
     using (Container.BeginExecutionContextScope()) {
       dynamic publisher = Container.GetInstance<IPublishEvent>();
       await publisher.PublishAsync((dynamic)eventObject).ConfigureAwait(true);
     }
     subscription.Acknowledge(resolvedEvent);
   } catch (Exception ex) {
     subscription.Fail(resolvedEvent, PersistentSubscriptionNakEventAction.Unknown, ex.Message);
   }
 }
 protected override void OnEventReceived(ResolvedEvent resolvedEvent)
 {
     switch (resolvedEvent.OriginalEvent.EventType)
     {
         case UserEventType.UserCreated:
             AddUserToCache(resolvedEvent.OriginalEvent);
             break;
         case UserEventType.AccountRegistered:
             AddAccountToCache(resolvedEvent.OriginalEvent);
             break;
     }
 }
Exemple #18
0
 private static void Appeared(EventStoreCatchUpSubscription subscription, ResolvedEvent resolvedEvent)
 {   
     if (resolvedEvent.Event.EventType.Contains("Question") || resolvedEvent.Event.EventType.Contains("Answer"))
     {
         Console.WriteLine("Read event {0} with data: {1}", 
             resolvedEvent.Event.EventType, 
             Encoding.UTF8.GetString(resolvedEvent.Event.Data));
         
         var @event = EventDeserializer.Deserialize(resolvedEvent.Event.EventType, Encoding.UTF8.GetString(resolvedEvent.Event.Data));
         _eventPublisher.Publish(@event);
     }
 }
        private static void StoreCommandData(ResolvedEvent evt, EventContext deserializedEvent, IDocumentSession session)
        {
            var commandId = deserializedEvent.Headers["CommandId"] as string;

            var commandModel = session.Load<CommandStatusModel>(commandId);
            if (commandModel == null)
            {
                commandModel = new CommandStatusModel() { Id = commandId };
                commandModel.Events = new List<EventStatusModel>();
                session.Store(commandModel);
            }
            commandModel.Events.Add(new EventStatusModel() { StreamId = evt.Event.EventStreamId, EventNumber = evt.Event.EventNumber, Type = evt.Event.EventType});
        }
 public Snapshot Deserialize(ResolvedEvent resolvedEvent)
 {
     var type = Type.GetType(resolvedEvent.Event.EventType, true);
     var instance = Activator.CreateInstance(type);
     using (var stream = new MemoryStream(resolvedEvent.Event.Data))
     {
         using (var reader = new BinaryReader(stream))
         {
             ((IBinaryDeserializer) instance).Read(reader);
             return new Snapshot(BitConverter.ToInt32(resolvedEvent.Event.Metadata, 0), instance);
         }
     }
 }
        public static object DeserializeEventData(
            this ISerializer serializer,
            ResolvedEvent resolvedEvent,
            out IDictionary<string, object> headers)
        {
            headers = (IDictionary<string, object>)serializer.Deserialize(Decode(resolvedEvent.Event.Metadata), typeof(Dictionary<string, object>));

            var type = Type.GetType((string)headers[EventMessageHeaders.Type]);

            var @event = serializer.Deserialize(Decode(resolvedEvent.Event.Data), type);

            return @event;
        }
 private void EventAppeared(EventStoreSubscription sub, ResolvedEvent e)
 {
     Log.Debug(_adapterName + " received " + Encoding.UTF8.GetString(e.Event.Data));
     var request = Json.From<SearchRequested>(Encoding.UTF8.GetString(e.Event.Data));
     try
     {
         var response = _endpoint.GetQuoteFor(request);
         Publish(request.ClientResponseStream, response);
     }
     catch (Exception ex)
     {
         Log.Exception(_adapterName + " endpoint caused exception", ex);
     }
 }
 public object Deserialize(ResolvedEvent resolvedEvent)
 {
     var instance =
         (IBinaryDeserializer)
         Activator.CreateInstance(Type.GetType(resolvedEvent.OriginalEvent.EventType, true));
     using (var stream = new MemoryStream(resolvedEvent.Event.Data))
     {
         using (var reader = new BinaryReader(stream))
         {
             instance.Read(reader);
         }
     }
     return instance;
 }
 private void EventAppeared(EventStoreCatchUpSubscription subscription, ResolvedEvent re)
 {
     if (re.OriginalEvent.EventType.StartsWith("$")) return; //skip internal events
     if (re.OriginalEvent.Metadata == null || re.OriginalEvent.Metadata.Any() == false) return;
     try
     {
         var e = re.DeserializeEvent();
         Dispatch(e).Wait();
     }
     catch (Exception exception)
     {
         _log.Error(string.Format("Could not deserialize event {0}", re.OriginalEvent.EventType), exception);
     }
 }
 private void OnEventReceivedImpl(ResolvedEvent resolvedEvent)
 {
     _logger.Trace("{0} Received event and scheduling onto ELS - {1}[{2}] {{ EventType = '{3}'}}",
                         GetType().Name,
                         resolvedEvent.OriginalEvent.EventStreamId, resolvedEvent.OriginalEvent.EventNumber,
                         resolvedEvent.OriginalEvent.EventType);
     _eventLoopScheduler.Schedule(() =>
     {
         _logger.Trace("{0}.OnEventReceived({1}[{2}] {{ EventType = '{3}'}}",
                         GetType().Name,
                         resolvedEvent.OriginalEvent.EventStreamId, resolvedEvent.OriginalEvent.EventNumber,
                         resolvedEvent.OriginalEvent.EventType);
         OnEventReceived(resolvedEvent);
     });
 }
Exemple #26
0
        protected override void When()
        {
            _connection.ConnectToPersistentSubscription(TestStreamName, GroupName, (x, y) =>
            {
                replayedParkedEvent = y;
                _eventParked.Set();
            },
                                                        (x, y, z) => { },
                                                        DefaultData.AdminCredentials);

            //Replayed parked messages
            var response = MakePost(SubscriptionPath + "/replayParked", _admin);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
 internal AllEventsSlice(ReadDirection readDirection, Position fromPosition, Position nextPosition, ClientMessage.ResolvedEvent[] events)
 {
     ReadDirection = readDirection;
     FromPosition = fromPosition;
     NextPosition = nextPosition;
     if (events == null)
         Events = EmptyEvents;
     else
     {
         Events = new ResolvedEvent[events.Length];
         for (int i = 0; i < Events.Length; ++i)
         {
             Events[i] = new ResolvedEvent(events[i]);
         }
     }
 }
        private void Appeared(EventStoreSubscription subscription, ResolvedEvent data)
        {
            var recordedEvent = data.Event;
            if (IsSystemStream(recordedEvent.EventStreamId)) return;

            var linkedStream = data.Link != null ? data.Link.EventStreamId : null;
            if (IsSystemStream(linkedStream)) return;

            var eventDefinition = _knownEventsProvider.Get(recordedEvent);

            _console.Log(
                eventDefinition.Color,
                "{0}: {1} ({2})",
                recordedEvent.EventType,
                eventDefinition.Parse(),
                FormatStream(linkedStream, recordedEvent));
        }
Exemple #29
0
        public void OnEventAppeared(EventStoreCatchUpSubscription subscription, ResolvedEvent resolvedEvent, Action<object,DateTime> callback)
        {
            var type = _typeLocator.Locate(resolvedEvent.Event.EventType);

            if (null == type) {
                _logger.LogDebug("[{0}] unknown type", _streamName);
                return;
            }

            callback(
                JsonConvert.DeserializeObject(
                    Encoding.UTF8.GetString(resolvedEvent.Event.Data),
                    type
                ),
                resolvedEvent.Event.Created
            );
        }
        private static void SendToClient(ResolvedEvent e, string connectionId)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<LiveEmotivSessionHub>();
            var theClient = context.Clients.Client(connectionId);
            var data = Encoding.UTF8.GetString(e.Event.Data);
            var metadata = Encoding.UTF8.GetString(e.Event.Metadata);

            theClient.handleEvent(new
                {
                    eventId = e.Event.EventId,
                    eventNumber = e.Event.EventNumber,
                    eventStreamId = e.Event.EventStreamId,
                    eventType = e.Event.EventType,
                    data,
                    metadata
                });
        }
Exemple #31
0
        public void should_be_able_to_subscribe_to_all_with_volatile_subscription()
        {
            var evnt = new EventData(Guid.NewGuid(), "EventType", false, new byte[10], new byte[15]);

            EventStore.ClientAPI.ResolvedEvent receivedEvent = new EventStore.ClientAPI.ResolvedEvent();
            var mre = new ManualResetEvent(false);

            _store.SubscribeToAllAsync(true, (s, e) => {
                receivedEvent = e;
                mre.Set();
            }, userCredentials: DefaultData.AdminCredentials).Wait();

            _store.AppendToStreamAsync(_volatileStreamTwo, intMaxValue + 2, evnt).Wait();
            Assert.That(mre.WaitOne(TimeSpan.FromSeconds(5)), "Timed out waiting for events to appear");

            Assert.AreEqual(evnt.EventId, receivedEvent.Event.EventId);
        }
 private static void StoreViewBuilderData(ResolvedEvent evt, IDocumentSession session)
 {
     ViewBuilderData mainData;
     mainData = session.Load<ViewBuilderData>("main");
     if (mainData == null)
     {
         mainData = new ViewBuilderData();
         session.Store(mainData, "main");
     }
     if (evt.OriginalPosition.HasValue)
     {
         var pos = evt.OriginalPosition.Value;
         mainData.CommitPosition = pos.CommitPosition;
         mainData.PreparePosition = pos.PreparePosition;
         Debug.WriteLine("Position stored");
     }
 }
Exemple #33
0
        public async Task should_be_able_to_subscribe_to_stream_with_volatile_subscription()
        {
            var evnt = new EventData(Guid.NewGuid(), "EventType", false, new byte[10], new byte[15]);

            EventStore.ClientAPI.ResolvedEvent receivedEvent = new EventStore.ClientAPI.ResolvedEvent();
            var mre = new ManualResetEvent(false);
            await _store.SubscribeToStreamAsync(_volatileStreamOne, true, (s, e) => {
                receivedEvent = e;
                mre.Set();
                return(Task.CompletedTask);
            });

            await _store.AppendToStreamAsync(_volatileStreamOne, intMaxValue + 2, evnt);

            Assert.That(mre.WaitOne(TimeSpan.FromSeconds(5)), "Timed out waiting for events to appear");

            Assert.AreEqual(evnt.EventId, receivedEvent.Event.EventId);
        }
 private Task HandleEvent(EventStoreSubscription sub, ResolvedEvent resolvedEvent)
 {
     _receivedEvent = resolvedEvent;
     _resetEvent.Set();
     return(Task.CompletedTask);
 }
 /// <summary>
 /// Try to process a single <see cref="ResolvedEvent"/>.
 /// </summary>
 /// <param name="e">The <see cref="ResolvedEvent"/> to process.</param>
 protected abstract void TryProcess(ResolvedEvent e);
Exemple #36
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="event"></param>
 /// <param name="retryCount"></param>
 internal PersistentSubscriptionResolvedEvent(ResolvedEvent @event, int?retryCount)
 {
     Event      = @event;
     RetryCount = retryCount;
 }
Exemple #37
0
 /// <summary>
 /// Mark a message failed processing. The server will be take action based upon the action paramter
 /// </summary>
 /// <param name="event">The event to mark as failed</param>
 /// <param name="action">The <see cref="PersistentSubscriptionNakEventAction"></see> action to take</param>
 /// <param name="reason">A string with a message as to why the failure is occurring</param>
 public void Fail(ResolvedEvent @event, PersistentSubscriptionNakEventAction action, string reason)
 {
     _subscription.NotifyEventsFailed(new[] { @event.OriginalEvent.EventId }, action, reason);
 }
Exemple #38
0
 /// <summary>
 /// Try to process a single <see cref="ResolvedEvent"/>.
 /// </summary>
 /// <param name="e">The <see cref="ResolvedEvent"/> to process.</param>
 protected abstract Task TryProcessAsync(ResolvedEvent e);
Exemple #39
0
 private void OnEventAppeared(EventStoreSubscription subscription, ResolvedEvent resolvedEvent)
 {
     Enqueue(resolvedEvent);
 }
Exemple #40
0
 /// <summary>
 /// Acknowledge that a message have completed processing (this will tell the server it has been processed)
 /// </summary>
 /// <remarks>There is no need to ack a message if you have Auto Ack enabled</remarks>
 /// <param name="event">The <see cref="ResolvedEvent"></see> to acknowledge</param>
 public void Acknowledge(ResolvedEvent @event)
 {
     _subscription.NotifyEventsProcessed(new[] { @event.OriginalEvent.EventId });
 }
 private void HandleEvent(EventStoreSubscription sub, ResolvedEvent resolvedEvent)
 {
     _receivedEvent = resolvedEvent;
     _resetEvent.Set();
 }