private void Connect()
        {
            var position = GetLastCheckpoint(CheckpointStream);

            _eventStoreConnection.SubscribeToStreamFrom(AlarmStream, position, true, ProcessEvent,
                                                        userCredentials: EventStoreCredentials.Default, subscriptionDropped: TryToReconnect);
        }
 public IDisposable Subscribe(IObserver <T> observer)
 {
     _subscription = _connection.SubscribeToStreamFrom(_stream, _lastCheckpoint, _resolveLinkTos, EventAppeared,
                                                       subscriptionDropped: SubscriptionDropped);
     _observer = observer;
     return(Disposable.Create(Stop));
 }
Ejemplo n.º 3
0
        public void Init()
        {
            _logger.LogDebug("--------------- SUBSCRIBE -----------------\nVersion: {0}\nStreamName: {1}\nCatchupPosition: {2}\n--------------- SUBSCRIBE -----------------", Version, GetStreamName(), GetCatchupPosition());

            _eventStoreConnection.SubscribeToStreamFrom(
                GetStreamName(),
                GetCatchupPosition(),
                CatchUpSubscriptionSettings.Default,
                (subscription, @event) =>
            {
                _logger.LogDebug("++++++++ NEW EVENT ++++++++\n{0}\n++++++++ NEW EVENT ++++++++", @event.Event.EventType);
                var methodToInvoke = GetType()
                                     .GetMethod("ApplyEvent", new[]
                {
                    Type.GetType(@event.Event.EventType)
                });
                if (methodToInvoke == null)
                {
                    _logger.LogError($"The view normalizer doesnt know how to handle this event: {@event.Event.EventType}");
                    throw new InvalidOperationException($"The view normalizer doesnt know how to handle this event: {@event.Event.EventType}");
                }

                Version++;     // bump up read model version

                methodToInvoke.Invoke(this, new object[]
                {
                    @event.Event.ToDomainEvent()
                });
            });
        }
Ejemplo n.º 4
0
        private void SetupSubscription(IComponentContext c, IEventStoreConnection esConnection)
        {
            var    freshContext = c.Resolve <IComponentContext>();
            long?  lastPosition;
            string stream = "nalozi";

            using (var scope = freshContext.Resolve <ILifetimeScope>().BeginLifetimeScope())
            {
                var processedRepo = scope.Resolve <IProcessedEventRepository>();
                var lastEvent     = processedRepo.GetLastProcessed(stream);
                lastPosition = lastEvent?.Checkpoint;
            }
            var options         = freshContext.Resolve <IOptions <AppSettings> >();
            var catchUpSettings = new CatchUpSubscriptionSettings(options.Value.EventStoreMaxQueueSize,
                                                                  options.Value.EventStoreReadBatchSize, true, true);

            esConnection.SubscribeToStreamFrom(stream, lastPosition, catchUpSettings,
                                               eventAppeared: async(s, e) =>
            {
                using (var scope = freshContext.Resolve <ILifetimeScope>().BeginLifetimeScope())
                {
                    var eventHandler = scope.Resolve <Persistence.IEventHandler>();
                    await eventHandler.HandleAsync(e);
                }
            },
                                               liveProcessingStarted: null,
                                               subscriptionDropped: (sub, reason, exc) =>
            {
                sub.Stop();
                var conn = freshContext.Resolve <IEventStoreConnection>();
                SetupSubscription(freshContext, conn);
            },
                                               userCredentials: new UserCredentials(options.Value.EVENTSTORE_USERNAME, options.Value.EVENTSTORE_PASSWORD));
        }
Ejemplo n.º 5
0
        public IJournalSubscription Subscribe(long from, Action <JournalRecord> handler)
        {
            long?checkPoint = null;

            if (from > 0)
            {
                checkPoint = from - 1;
            }

            var ready = false;

            var sub = _connection.SubscribeToStreamFrom(
                stream: _streamName,
                lastCheckpoint: checkPoint,
                settings: new CatchUpSubscriptionSettings(10000, 4096, false, false),
                eventAppeared: (s, re) =>
            {
                _logger.Debug("eventAppeared, recordNumber {0}", re.OriginalEventNumber);
                handler.Invoke(re.Event.ToJournalRecord(_serializer));
            },
                liveProcessingStarted: s =>
            {
                ready = true;
                _logger.Info("liveProcessingStarted");
            });

            return(new EventStoreSubscriptionAdapter(_settings, sub, () => ready));
        }
        private void SubscribeInternal(IEventStoreConnection src, UserCredentials cred)
        {
            long?lastCheckpoint = null;

            if (Status.LastCheckPoint.HasValue && Status.LastCheckPoint != -1)
            {
                lastCheckpoint = Status.LastCheckPoint;
            }

            // if (_useQueue)
            // {
            //     _logger.LogDebug("Start Working in Queue");
            //     await Queue.StartWorkingAsync(HandleAsync, cancellationToken: _cancellationToken).ConfigureAwait(false);
            // }

            var sub = src.SubscribeToStreamFrom(StreamName,
                                                lastCheckpoint,
                                                CatchUpSubscriptionSettings.Default,
                                                EventAppeared,
                                                LiveProcessingStarted,
                                                SubscriptionDropped,
                                                cred);

            _cancellationToken.Register(sub.Stop);
        }
        /// <summary>
        /// Creates the Subscription with EventStore.
        /// </summary>
        /// <param name="streamName">The name of the EventStore Stream we are subscribing to.</param>
        /// <param name="eventStoreStreamSequenceToken"></param>
        /// <returns>An EventStoreSubscription or EventStorePersistentSubscription.</returns>
        private object CreateEventStoreSubscription(string streamName, EventStoreStreamSequenceToken eventStoreStreamSequenceToken)
        {
            object subscription = null;

            if (eventStoreStreamSequenceToken == null || eventStoreStreamSequenceToken.EventNumber == int.MinValue)
            {
                var subscribeTask = m_EventStoreConnection.SubscribeToStreamAsync(streamName, true, EventAppeared,
                                                                                  SubscriptionDropped);
                Task.WaitAll(subscribeTask);
                if (subscribeTask.IsFaulted)
                {
                    throw subscribeTask.Exception;
                }

                subscription = subscribeTask.Result;
            }
            else
            {
                // If we have been provided with a StreamSequenceToken, we can call SubscribeFrom to get previous messages.
                subscription = m_EventStoreConnection.SubscribeToStreamFrom(streamName,
                                                                            eventStoreStreamSequenceToken.EventNumber, new CatchUpSubscriptionSettings(100, 20, false, true), EventAppeared);
            }

            m_Logger.Info($"Subscribed to Stream {streamName}");
            return(subscription);
        }
Ejemplo n.º 8
0
        public IObservable <OccuredEvent> Start(long?position)
        {
            eventSub?.Dispose();
            eventSub  = new Subject <OccuredEvent>();
            activeSub = connection.SubscribeToStreamFrom(StreamName, position, settings, Handle);

            return(eventSub);
        }
Ejemplo n.º 9
0
 public void SubscribeToCatchupStream(string streamName, Action <EventstoreEvent> eventHandler)
 {
     _connection.SubscribeToStreamFrom(streamName, null,
                                       new CatchUpSubscriptionSettings(1, 1, false, false),
                                       (subscription, receivedEvent) => eventHandler(MapEventstoreEvent(receivedEvent)),
                                       subscription => {},
                                       (subscription, reason, arg3) => CatchupSubscriptionDropped(subscription, reason, arg3, streamName, eventHandler),
                                       _userCredentials);
 }
Ejemplo n.º 10
0
        public EventStoreStreamCatchUpSubscription(IEventStoreConnection connection, string streamName, Action <IEvent> handler)
        {
            _handler = handler;

            _subscription = connection.SubscribeToStreamFrom(
                streamName,
                null, // don't use StreamPosition.Start (see https://groups.google.com/forum/#!topic/event-store/8tpXJMNEMqI),
                CatchUpSubscriptionSettings.Default,
                OnEventAppeared);
        }
Ejemplo n.º 11
0
        public async Task Start(long fromCheckpoint)
        {
            Connection            = EventStoreConnection.Create(ESConnectionConfig.ConnectionString);
            Connection.Connected += Connection_Connected;
            await Connection.ConnectAsync().ConfigureAwait(false);

            long?eventstoreCheckpoint = (fromCheckpoint == 0) ? null : (long?)(fromCheckpoint - 1);

            Subscription = Connection.SubscribeToStreamFrom(StreamName, eventstoreCheckpoint, CatchUpSubscriptionSettings.Default, EventAppeared, LiveProcessingStarted, SubscriptionDropped);
        }
Ejemplo n.º 12
0
 private void SubscribeToStream()
 {
     eventStoreSubscription = connection.SubscribeToStreamFrom(
         streamId,
         position == 0 ? (long?)null : position,
         CatchUpSubscriptionSettings.Default,
         EventAppeared,
         _ => liveProcessingStarted(position)
         );
 }
Ejemplo n.º 13
0
        public void Run()
        {
            connection.ConnectAsync()
            .Wait();

            connection.SubscribeToStreamFrom(
                "Employee",
                0L,
                Settings,
                (subscription, evt) => processor.ProcessEvent(evt));
        }
        private void SubscribeToStream(IEventStoreConnection connection)
        {
            if (_subscription != null)
            {
                _subscription.Stop();
                _subscription = null;
            }

            _subscription = connection.SubscribeToStreamFrom(_streamName, _checkpoint,
                                                             CatchUpSubscriptionSettings.Default,
                                                             EventAppeared, LiveProcessingStarted, SubscriptionDropped);
        }
Ejemplo n.º 15
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var settings     = new CatchUpSubscriptionSettings(100, 100, false, true);
            var subscription = _connection.SubscribeToStreamFrom(EvelynEvents, null, settings, OnEventAppeared, OnLiveProcessingStarted, OnSubscriptionDropped);

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
            }

            subscription.Stop();
        }
Ejemplo n.º 16
0
        public void Start()
        {
            if (subscriber != null)
            {
                logger.LogError("Subscriber already started");
            }

            Task convertAndPlayEvent(EventStoreCatchUpSubscription sub, ResolvedEvent storeEvent) => playEvent(ToEvent(storeEvent));
            void logStart(EventStoreCatchUpSubscription sub) => LiveProcessingStarted(sub, DateTime.Now);

            this.subscriber = connection.SubscribeToStreamFrom(CategoryStreamName, StreamPosition.Start, CatchUpSubscriptionSettings.Default, convertAndPlayEvent, logStart, SubscriptionDropped);
        }
Ejemplo n.º 17
0
        static void MeasureLines(IEventStoreConnection con, UserCredentials credentials)
        {
            var stream = "lines_of_Budgets-a208105f_d5ba_475e_bb23_e7012945d332";
            var w      = Stopwatch.StartNew();

            var sub = con.SubscribeToStreamFrom(stream, null, true, Appeared, Live, null, userCredentials);

            mre.WaitOne();
            w.Stop();

            Console.WriteLine("read {0} events, in {1}. {2}", count, w.Elapsed, count / w.Elapsed.TotalSeconds);
            Console.ReadLine();
        }
Ejemplo n.º 18
0
        static void MeasureLines(IEventStoreConnection con, UserCredentials credentials)
        {
            var stream = "lines_of_Budgets-a208105f_d5ba_475e_bb23_e7012945d332";
            var w = Stopwatch.StartNew();

            var sub = con.SubscribeToStreamFrom(stream, null, true, Appeared, Live, null, userCredentials);

            mre.WaitOne();
            w.Stop();

            Console.WriteLine("read {0} events, in {1}. {2}", count, w.Elapsed, count / w.Elapsed.TotalSeconds);
            Console.ReadLine();
        }
Ejemplo n.º 19
0
        public void Start()
        {
            HasLoaded = false;
            _connection = EventStore.ClientAPI.EventStoreConnection.Create(_endpoint);
            var ct = _connection.ConnectAsync();
            ct.Wait();
            _checkPoint = Position.Start;
            if (string.IsNullOrEmpty(_streamName))
                _subscription = _connection.SubscribeToAllFrom(_checkPoint, false, EventAppeared, Live, SubscriptionDropped, _credentials);
            else
                _subscription = _connection.SubscribeToStreamFrom(_streamName, _lastEventNumber, true, EventAppeared, Live, SubscriptionDropped, _credentials);

        }
Ejemplo n.º 20
0
        private async Task SubscribeProjection(IEventStoreProjection currentEventStoreProjection, AppFunc chain, IDictionary <string, object> environment)
        {
            environment.Log("Subscribing projection: {0}", LogLevel.Debug, currentEventStoreProjection.ProjectionName);

            var bufferSettings = environment.GetSettings <ProjectionSettings>().GetBufferSettings();

            while (true)
            {
                if (!running)
                {
                    return;
                }

                if (_projectionSubscriptions.ContainsKey(currentEventStoreProjection.ProjectionName))
                {
                    _projectionSubscriptions[currentEventStoreProjection.ProjectionName].Close();
                    _projectionSubscriptions.Remove(currentEventStoreProjection.ProjectionName);
                }

                try
                {
                    var eventNumberManager = environment.Resolve <IManageEventNumbersForProjections>();

                    var messageProcessor    = new MessageProcessor();
                    var messageSubscription = Observable
                                              .FromEvent <DeSerializationResult>(x => messageProcessor.MessageArrived += x, x => messageProcessor.MessageArrived -= x)
                                              .Buffer(TimeSpan.FromSeconds(bufferSettings.Seconds), bufferSettings.NumberOfEvents)
                                              .Subscribe(async x => await PushEventsToProjections(chain, currentEventStoreProjection, x, environment).ConfigureAwait(false));

                    var eventStoreSubscription = _eventStoreConnection.SubscribeToStreamFrom(currentEventStoreProjection.ProjectionName,
                                                                                             await eventNumberManager.GetLastEvent(currentEventStoreProjection.ProjectionName, environment).ConfigureAwait(false), CatchUpSubscriptionSettings.Default,
                                                                                             (subscription, evnt) => messageProcessor.OnMessageArrived(_eventSerialization.DeSerialize(evnt)),
                                                                                             subscriptionDropped: async(subscription, reason, exception) => await SubscriptionDropped(chain, currentEventStoreProjection, reason, exception, environment).ConfigureAwait(false));

                    _projectionSubscriptions[currentEventStoreProjection.ProjectionName] = new ProjectionSubscription(messageSubscription, eventStoreSubscription);

                    return;
                }
                catch (Exception ex)
                {
                    if (!running)
                    {
                        return;
                    }

                    environment.Log(ex, "Couldn't subscribe projection: {0}. Retrying in 5 seconds.", LogLevel.Warn, currentEventStoreProjection.ProjectionName);

                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 21
0
        public void Run_PassesEventsToProcessor()
        {
            sut.Run();

            A.CallTo(() => connection.ConnectAsync()).MustHaveHappened()
            .Then(A.CallTo(() => connection.SubscribeToStreamFrom(
                               "Employee",
                               0L,
                               sut.Settings,
                               A <Func <EventStoreCatchUpSubscription, ResolvedEvent, Task> > ._,
                               null,
                               null,
                               null)).MustHaveHappened());
        }
        public void Subscribe(IActorRef subscriber, string stream, long?from, int max,
                              Func <ResolvedEvent, object> resolved)
        {
            if (!_subscriptions.TryGetValue(subscriber, out var subscriptions))
            {
                subscriptions = new HashSet <EventStoreCatchUpSubscription>();
                _subscriptions.Add(subscriber, subscriptions);
                _context.WatchWith(subscriber, new Unsubscribe(stream, subscriber));
            }

            try
            {
// need to have this since ES Catchup Subscription needs null for from when user wants to
                // read from begging of the stream
                long?nullable = null;

                var self = _context.Self;

                var subscription = _conn.SubscribeToStreamFrom(
                    stream,
                    from.HasValue && from.Value == 0 ? nullable : from,
                    new CatchUpSubscriptionSettings(max * 2, 500, false, true),
                    (sub, @event) =>
                {
                    var p = resolved(@event);
                    if (p != null)
                    {
                        subscriber.Tell(p, self);
                    }
                },
                    _ => subscriber.Tell(CaughtUp.Instance, self),
                    (_, reason, exception) =>
                {
                    var msg = $"Subscription dropped due reason {reason.ToString()}";
                    subscriber.Tell(new SubscriptionDroppedException(msg, exception), self);
                });


                subscriptions.Add(subscription);
            }
            catch (Exception)
            {
                if (subscriptions.Count == 0)
                {
                    _context.Unwatch(subscriber);
                }

                throw;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     subscribe to a stream and count the events in it
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private async Task <TestResult> CountEvents(IEventStoreConnection connection, EventStoreConnectionConfiguration configuration)
        {
            _output.WriteLine($"Counting all Events in Stream '{configuration.Stream}'", 1);

            var startTime = DateTime.Now;
            var stopTime  = DateTime.Now;

            // subscribe to the stream to count the number of events contained in it
            connection.SubscribeToStreamFrom(configuration.Stream,
                                             StreamCheckpoint.StreamStart,
                                             new CatchUpSubscriptionSettings(128, 256, false, true, "ConfigService.CLI.ConnectionTest"),
                                             (subscription, @event) => { _countedEvents += 1; },
                                             subscription =>
            {
                _output.WriteLine($"Subscription to '{subscription.SubscriptionName}' opened", 1);
                stopTime = DateTime.Now;
                _liveProcessingEvents = true;
            },
                                             (subscription, reason, exception) =>
            {
                _output.WriteLine(
                    $"Subscription to '{subscription.SubscriptionName}' dropped: " +
                    $"{reason}; {exception.GetType().Name} {exception.Message}", 1);
                stopTime             = DateTime.Now;
                _subscriptionDropped = true;
            });

            do
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
            } while (!_liveProcessingEvents && !_subscriptionDropped);

            if (_subscriptionDropped)
            {
                _output.WriteLine($"Counted '{_countedEvents}' events in {FormatTime(stopTime - startTime)} before Subscription was dropped", 1);
                return(new TestResult
                {
                    Result = false,
                    Message = "Subscription was dropped"
                });
            }

            _output.WriteLine($"Counted '{_countedEvents}' events in {FormatTime(stopTime - startTime)}", 1);

            return(new TestResult
            {
                Result = true,
                Message = string.Empty
            });
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Initializes the in-memory names list with all names that exist in the "FullName" events category and
        /// sets up the service to subscribe to all future FullName events to update the names list.
        /// </summary>
        public static async Task <bool> Init(IEventStoreConnection eventStoreConnection, INameProjector nameProjector)
        {
            _connection     = eventStoreConnection;
            _modelProjector = nameProjector;
            _names          = new ConcurrentDictionary <string, NameDTO>();
            _nameIds        = new ConcurrentBag <string>();

            // Subscribe to the FullName category event stream for all events now and in the future
            var eventStreamName = "$ce-FullName";
            var catchupSettings = new CatchUpSubscriptionSettings(4096, 4096, true, true);

            _connection.SubscribeToStreamFrom(eventStreamName, null, catchupSettings, HandleEventFromSubscription, null, ReconnectToStreamSubscription);

            return(true);
        }
        public void CatchupSubscriptionToStreamHandlesManyEventsWithSmallBatchSize()
        {
            var mre = new ManualResetEvent(false);

            _conn.SubscribeToStreamFrom(_streamName, null, _settings, (sub, evnt) => {
                if (evnt.OriginalEventNumber % 1000 == 0)
                {
                    Console.WriteLine("Processed {0} events", evnt.OriginalEventNumber);
                }
            }, (sub) => { mre.Set(); }, null, new UserCredentials("admin", "changeit"));

            if (!mre.WaitOne(TimeSpan.FromMinutes(10)))
            {
                Assert.Fail("Timed out waiting for test to complete");
            }
        }
Ejemplo n.º 26
0
        public void Start()
        {
            HasLoaded   = false;
            _connection = EventStore.ClientAPI.EventStoreConnection.Create(_endpoint);
            var ct = _connection.ConnectAsync();

            ct.Wait();
            _checkPoint = Position.Start;
            if (string.IsNullOrEmpty(_streamName))
            {
                _subscription = _connection.SubscribeToAllFrom(_checkPoint, false, EventAppeared, Live, SubscriptionDropped, _credentials);
            }
            else
            {
                _subscription = _connection.SubscribeToStreamFrom(_streamName, _lastEventNumber, true, EventAppeared, Live, SubscriptionDropped, _credentials);
            }
        }
Ejemplo n.º 27
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var topicsLastCheckpoint = await _checkpointRepository.GetAsync("groups");

            var settings = new CatchUpSubscriptionSettings(
                maxLiveQueueSize: 10000,
                readBatchSize: 500,
                verboseLogging: false,
                resolveLinkTos: false,
                subscriptionName: "Events-Groups");

            _subscription = _eventStore.SubscribeToStreamFrom(
                stream: "Groups",
                lastCheckpoint: topicsLastCheckpoint?.PreparePosition,
                settings: settings,
                eventAppeared: async(sub, @event) =>
            {
                if (@event.OriginalEvent.EventType.StartsWith("$"))
                {
                    return;
                }

                try
                {
                    await _mediator.Publish(new Notification
                    {
                        Event = JsonSerializer.Deserialize(Encoding.UTF8.GetString(@event.OriginalEvent.Data), Type.GetType(Encoding.UTF8.GetString(@event.OriginalEvent.Metadata)))
                    });

                    await _checkpointRepository.SaveAsync("groups", @event.OriginalPosition.GetValueOrDefault());
                }
                catch (Exception exception)
                {
                    _logger.LogError(exception, exception.Message);
                }
            },
                liveProcessingStarted: (sub) =>
            {
                _logger.LogInformation("{SubscriptionName} subscription started.", sub.SubscriptionName);
            },
                subscriptionDropped: (sub, subDropReason, exception) =>
            {
                _logger.LogWarning("{SubscriptionName} dropped. Reason: {SubDropReason}.", sub.SubscriptionName, subDropReason);
            });
        }
Ejemplo n.º 28
0
        void SubscribeToStream(StreamId streamId,
                               Func <Checkpoint> checkpoint,
                               CatchUpSubscriptionSettings settings,
                               Func <EventStoreCatchUpSubscription, ResolvedEvent, Task> eventAppeared,
                               Action <EventStoreCatchUpSubscription> liveProcessingStarted,
                               Action <SubscriptionDropReason, Exception> subscriptionDropped)
        {
            _loggingAdaptor.Information("Subscribing to {0} stream starting at checkpoint {1}",
                                        streamId.ToString(),
                                        checkpoint().ToString());

            _eventStoreConnection.SubscribeToStreamFrom(streamId.Id,
                                                        checkpoint().ToEventNumber(),
                                                        settings,
                                                        OnEventAppeared(eventAppeared),
                                                        OnLiveProcessingStarted(liveProcessingStarted),
                                                        OnSubscriptionDropped(subscriptionDropped));
        }
 /// <summary>
 /// Subscribes to a single event stream. Existing events from
 /// lastCheckpoint onwards are read from the stream
 /// and presented to the user of <see cref="EventStoreCatchUpSubscription"/>
 /// as if they had been pushed.
 ///
 /// Once the end of the stream is read the subscription is
 /// transparently (to the user) switched to push new events as
 /// they are written.
 ///
 /// The action liveProcessingStarted is called when the
 /// <see cref="EventStoreCatchUpSubscription"/> switches from the reading
 /// phase to the live subscription phase.
 /// </summary>
 /// <param name="stream">The stream to subscribe to</param>
 /// <param name="lastCheckpoint">The event number from which to start.
 ///
 /// To receive all events in the stream, use <see cref="StreamCheckpoint.StreamStart" />.
 /// If events have already been received and resubscription from the same point
 /// is desired, use the event number of the last event processed which
 /// appeared on the subscription.
 ///
 /// NOTE: Using <see cref="StreamPosition.Start" /> here will result in missing
 /// the first event in the stream.</param>
 /// <param name="target">The connection to subscribe to</param>
 /// <param name="eventAppeared">An action invoked when a new event is received over the subscription</param>
 /// <param name="liveProcessingStarted">An action invoked when the subscription switches to newly-pushed events</param>
 /// <param name="subscriptionDropped">An action invoked if the subscription is dropped</param>
 /// <param name="userCredentials">User credentials to use for the operation</param>
 /// <param name="settings">The <see cref="CatchUpSubscriptionSettings"/> for the subscription</param>
 /// <returns>An <see cref="EventStoreSubscription"/> representing the subscription</returns>
 public static EventStoreStreamCatchUpSubscription SubscribeToStreamFrom(
     this IEventStoreConnection target,
     string stream,
     long?lastCheckpoint,
     CatchUpSubscriptionSettings settings,
     Action <EventStoreCatchUpSubscription, ResolvedEvent> eventAppeared,
     Action <EventStoreCatchUpSubscription> liveProcessingStarted = null,
     Action <EventStoreCatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped = null,
     UserCredentials userCredentials = null) =>
 target.SubscribeToStreamFrom(
     stream,
     lastCheckpoint,
     settings,
     ToTask(eventAppeared),
     liveProcessingStarted,
     subscriptionDropped,
     userCredentials
     );
        private async Task Connect()
        {
            _connection = _connectionProvider.GetConnection();
            await _connection.ConnectAsync();


            Func <EventStoreCatchUpSubscription, ResolvedEvent, Task> processEvent = (subscriptionBase, resolvedEvent) => {
                return(HandleEvent(resolvedEvent));
            };

            Func <ESSubscription, ResolvedEvent, Task> processEventAlt = (subscriptionBase, resolvedEvent) => {
                return(HandleEvent(resolvedEvent));
            };

            var streamId = _streamId == null ? $"$ce-{_aggregateType.ToUpper()}" : _streamId.Id;

            if (_startPosition == StreamPosition.End)
            {
                _subscriptionBase = await _connection.SubscribeToStreamAsync(
                    streamId,
                    true,
                    processEventAlt,
                    subscriptionDropped : SubscriptionDropped);

                _connected = true;
                _status    = SubscriptionConnectionStatus.Connected;
            }
            else
            {
                _catchUpSubscriptionBase = _connection.SubscribeToStreamFrom(
                    streamId,
                    0,
                    new CatchUpSubscriptionSettings(
                        CatchUpSubscriptionSettings.Default.MaxLiveQueueSize,
                        CatchUpSubscriptionSettings.Default.ReadBatchSize,
                        false,
                        true,
                        CatchUpSubscriptionSettings.Default.SubscriptionName),
                    processEvent,
                    subscriptionDropped: SubscriptionDropped);
                _connected = true;
                _status    = SubscriptionConnectionStatus.Connected;
            }
        }
Ejemplo n.º 31
0
        private void ConnectToEventstore()
        {
            latestPosition = Position.Start;

            var subs = connection.SubscribeToAllFrom(latestPosition, true, HandleEvent);


            //subscribe to the stream of fraud alert
            connection.SubscribeToStreamFrom("PossiblyStolenCardClients", 0, true,

                                             (sub, e) =>
            {
                var jsonString = Encoding.UTF8.GetString(e.Event.Data);

                JObject o = JObject.Parse(jsonString);

                var clientID = (string)o["ClientID"];

                Bus.Publish(new ClientPossiblyStolen()
                {
                    ClientID = clientID
                });

                var ci = indexer.Get <ClientInformation>(clientID);

                if (ci == null)
                {
                    ci = new ClientInformation()
                    {
                        ID = clientID
                    }
                }
                ;

                ci.PossiblyStolen = true;

                indexer.Index(ci);
            }
                                             );


            Console.WriteLine("Indexing service started");
        }
Ejemplo n.º 32
0
        public void LinkTo(IEventStoreConnection connection, Guid identifier)
        {
            connection.SubscribeToStreamFrom(
                "remote_control-" + Identifier.ToString("N"),
                EventNumber,
                CatchUpSubscriptionSettings.Default,
                (EventStoreCatchUpSubscription EventStoreCatchUpSubscription, ResolvedEvent ResolvedEvent) =>
            {
                switch (ResolvedEvent.Event.EventType)
                {
                case nameof(Events.BrightnessChanged):
                    var BrightnessChanged = JsonConvert.DeserializeObject(
                        Encoding.UTF8.GetString(ResolvedEvent.Event.Data),
                        typeof(Events.BrightnessChanged)
                        ) as Events.BrightnessChanged;
                    Brightness += BrightnessChanged.Change;
                    EventNumber = ResolvedEvent.Event.EventNumber;
                    break;

                case nameof(Events.ColorChanged):
                    var ColorChanged = JsonConvert.DeserializeObject(
                        Encoding.UTF8.GetString(ResolvedEvent.Event.Data),
                        typeof(Events.ColorChanged)
                        ) as Events.ColorChanged;
                    Color      += ColorChanged.Change;
                    EventNumber = ResolvedEvent.Event.EventNumber;
                    break;
                }
            },
                (EventStoreCatchUpSubscription EventStoreCatchUpSubscription) =>
            {
            },
                (EventStoreCatchUpSubscription EventStoreCatchUpSubscription, SubscriptionDropReason SubscriptionDropReason, Exception Exception) =>
            {
                Console.WriteLine(
                    "The subscription was dropped because of: {0}",
                    SubscriptionDropReason
                    );
                NotifyPropertyChanged(null);
            },
                null
                );
        }
        //TODO: Need restore point configuration
        private static void Start(ProjectionGatewayConfiguration projectionGatewayConfiguration, IEventStoreConnection eventStoreConnection)
        {
            projectionGatewayConfiguration.Locator.Register(() => eventStoreConnection);
            eventStoreConnection.ConnectAsync().Wait();

            foreach (var subscription in projectionGatewayConfiguration.Subscriptions)
            {
                var eventHandlers = subscription.Value;
                eventStoreConnection.SubscribeToStreamFrom(
                    stream: subscription.Key + "View",
                    lastCheckpoint: StreamCheckpoint.StreamStart,
                    resolveLinkTos: true,
                    eventAppeared: (upSubscription, @event) =>
                    {
                        var eventType = Type.GetType(@event.Event.EventType);
                        var deserializedEvent = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(@event.Event.Data), eventType);
                        eventHandlers
                            .Single(x => x.EventType == eventType)
                            .EventHandler(deserializedEvent);
                    });
            }
        }