コード例 #1
0
        private async Task SubscribeToAll()
        {
            var checkpoint = checkpointProvider.Get();
            var position   = checkpoint.HasValue ? new Position(checkpoint.Value, checkpoint.Value) : Position.Start;

            subscription = await client.SubscribeToAllAsync(position, OnEvent, subscriptionDropped : OnSubscriptionDropped);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: PawelSzatkowski/UPSik
        private async static Task EventArrived(
            StreamSubscription subscription,
            ResolvedEvent resolvedEvent,
            CancellationToken cancellationToken)
        {
            var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray());
            var packages = JsonConvert.DeserializeObject <List <Package> >(jsonData);

            int i = 1;

            foreach (var package in packages)
            {
                Console.WriteLine();
                Console.WriteLine($"{i}.");
                Console.WriteLine($"Package (number: {package.Number}) has been delivered");
                Console.WriteLine($"Sender's e-mail: {package.Sender.Email}");
                Console.WriteLine($"Receiver's name: {package.Receiver.Name} {package.Receiver.Surname}");
                Console.WriteLine($"Receiver's e-mail: {package.Receiver.Email}");
                Console.WriteLine($"Receiver's address:");
                Console.WriteLine($"{package.Receiver.Address.Street} {package.Receiver.Address.HouseNumber}" + "\n" +
                                  $"{package.Receiver.Address.PostCode} {package.Receiver.Address.City}" + "\n" +
                                  $"{package.Receiver.Address.Country}");

                i++;
            }

            SendNotificationEmails(packages);
        }
コード例 #3
0
        private Task HandleNewEvent(StreamSubscription subscription, ResolvedEvent evnt, CancellationToken token)
        {
            if (evnt.Event.EventStreamId.StartsWith('$'))
            {
                // skip system events
                return(Task.CompletedTask);
            }

            IDomainEvent <IDomainEventData> @event;

            try
            {
                @event = ParseEvent(evnt);
            }
            catch
            {
                // TODO: Properly handle this case
                _logger.LogWarning("Unknown event name: {eventName}", evnt.Event.EventType);
                return(Task.CompletedTask);
            }
            _logger.LogDebug("Processed event {position}|{type}.", evnt.OriginalPosition, evnt.Event.EventType);

            _sender.SendEvent(@event);

            return(Task.CompletedTask);
        }
コード例 #4
0
        Future <string> join(string separator = "")
        {
            _Future                result       = new _Future();
            StringBuilder          buffer       = new StringBuilder();
            StreamSubscription <T> subscription = null;
            bool first = true;

            subscription = listen(
                (T element) => {
                if (!first)
                {
                    buffer.Append(separator);
                }

                first = false;
                try {
                    buffer.Append(element);
                }
                catch (Exception e) {
                    _stream._cancelAndErrorWithReplacement(subscription, result, e);
                }
            },
                onError: (e, _) => result._completeError((Exception)e),
                onDone: () => { result._complete(buffer.ToString()); },
                cancelOnError: true);
            return(result.to <string>());
        }
コード例 #5
0
        private async Task HandleEvent(StreamSubscription subscription, ResolvedEvent resolvedEvent,
                                       CancellationToken cancellationToken)
        {
            var domainEvent = _eventSerializer.Deserialize(resolvedEvent);

            if (domainEvent == null)
            {
                return;
            }

            _logger.LogInformation($"PullRequestCommentsProjector handled event: {domainEvent}");
            switch (domainEvent)
            {
            case SingleCommentWasAdded added:
                var comment = new PullRequestComment
                {
                    PullRequestId = added.PullRequestId,
                    CommentId     = added.CommentId,
                    PostedAt      = added.OccurredAt,
                    Author        = added.Author,
                    Text          = added.Text
                };
                await _repository.Save(comment);

                break;
            }
        }
コード例 #6
0
ファイル: SettingsForm.cs プロジェクト: w0pr/blizztv
 public ListviewStreamSubscription(StreamSubscription streamSubscription)
 {
     this._streamSubscription = streamSubscription;
     this.Text = streamSubscription.Name;
     this.SubItems.Add(streamSubscription.Provider);
     this.SubItems.Add(streamSubscription.Slug);
 }
コード例 #7
0
        async Task HandleEvent(StreamSubscription streamSubscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken)
        {
            if (resolvedEvent.Event.EventType.StartsWith("$"))
            {
                return;
            }

            var evt = resolvedEvent.Deserialize();

            if (evt == null)
            {
                return;
            }

            using (var scope = _serviceProvider.CreateScope())
            {
                var publisher = scope.ServiceProvider.GetRequiredService <IPublisher>();

                var domainProjectionType = typeof(DomainEventProjection <>).MakeGenericType(evt.GetType());
                var domainProjection     = Activator.CreateInstance(domainProjectionType, evt) ??
                                           throw new Exception($"Unable to create domain event projection for event {evt.GetType()}");

                await publisher.Publish(domainProjection, cancellationToken);

                _checkpoint.UpdatePosition(resolvedEvent.Event.Position.CommitPosition);

                await scope.ServiceProvider.GetRequiredService <ICheckpointProvider>()
                .StoreCheckpoint(_checkpoint, cancellationToken);
            }
        }
コード例 #8
0
        /// <summary>
        /// Formats a notification string with the necessary parameters
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string GetNotificationMessage(ILiveBotStream stream, StreamSubscription subscription, ILiveBotUser user = null, ILiveBotGame game = null)
        {
            string RoleMention = "";

            if (subscription.DiscordRole != null)
            {
                if (subscription.DiscordRole.Name == "@everyone")
                {
                    RoleMention = "@everyone";
                }
                else
                {
                    RoleMention = MentionUtils.MentionRole(subscription.DiscordRole.DiscordId);
                }
            }

            var tempUser = user ?? stream.User;
            var tempGame = game ?? stream.Game;

            return(subscription.Message
                   .Replace("{Name}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Username}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Game}", EscapeSpecialDiscordCharacters(tempGame.Name), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Title}", EscapeSpecialDiscordCharacters(stream.Title), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{URL}", stream.StreamURL ?? "", ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Role}", RoleMention, ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Trim());
        }
コード例 #9
0
        public async Task <string> ChangeSubscription(int id)
        {
            if (id == null)
            {
                return("error");
                //return NotFound();
            }

            StreamSubscription sub = _context.StreamSubscriptions.Where(ss => ss.ID == id).FirstOrDefault();

            DateTime start   = DateTime.Now;
            string   @return = "error";

            if (sub != null)
            {
                switch (sub.Subscribed)
                {
                case SubscriptionState.Subscribed:
                    sub.Subscribed = SubscriptionState.Unsubscribed;
                    @return        = "false";
                    break;

                case SubscriptionState.Unsubscribed:
                    sub.Subscribed = SubscriptionState.Subscribed;
                    @return        = "true";
                    break;
                }
                await _context.SaveChangesAsync();
            }
            return(@return);
            //return RedirectToAction(nameof(Subscriptions));
        }
コード例 #10
0
        protected async Task Handler(StreamSubscription sub, ResolvedEvent re, CancellationToken cancellationToken) {
            _debugLog?.Invoke(
                "Subscription {Subscription} got an event {@Event}",
                sub.SubscriptionId,
                re
            );

            _lastProcessedPosition = GetPosition(re);

            if (re.Event.EventType.StartsWith("$")) {
                await Store();
            }

            try {
                var evt = _eventSerializer.Deserialize(re.Event.Data.Span, re.Event.EventType);

                if (evt != null) {
                    _debugLog?.Invoke("Handling event {Event}", evt);

                    await Task.WhenAll(
                        _projections.Select(
                            x => x.HandleEvent(evt, (long?) re.OriginalPosition?.CommitPosition)
                        )
                    );
                }
            }
            catch (Exception e) {
                _log.LogWarning(e, "Error when handling the event {Event}", re.Event.EventType);
            }

            await Store();

            Task Store() => StoreCheckpoint(GetPosition(re), cancellationToken);
        }
コード例 #11
0
        private async Task EventAppeared(StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken)
        {
            _logger.LogInformation("{eventType}@{preparePosition}", resolvedEvent.Event.EventType, resolvedEvent.Event.Position.PreparePosition);

            var e = EventSerializer.Deserialize(resolvedEvent);

            await ExecuteProjectionHandlers(e);
        }
コード例 #12
0
 private void SubscriptionDropped(StreamSubscription _, SubscriptionDroppedReason reason, Exception ex)
 {
     if (ex == null)
     {
         return;
     }
     _completed.TrySetException(ex);
 }
コード例 #13
0
 void _unsubscribe()
 {
     if (_subscription != null)
     {
         _subscription.cancel();
         _subscription = null;
     }
 }
コード例 #14
0
 internal _ForwardingStreamSubscription(_ForwardingStream <S, T> _stream,
                                        Action <T> onData, Action <object, string> onError, Action onDone, bool cancelOnError
                                        )
     : base(onData, onError, onDone, cancelOnError)
 {
     this._stream  = _stream;
     _subscription = _stream._source
                     .listen(_handleData, onError: _handleError, onDone: _handleDone);
 }
コード例 #15
0
 void _handleDone()
 {
     try {
         _subscription = null;
         _transformerSink.close();
     }
     catch (Exception e) {
         _addError(e, e.StackTrace);
     }
 }
コード例 #16
0
ファイル: Realtime.cs プロジェクト: EventStore/replicator
        void HandleDrop(StreamSubscription subscription, SubscriptionDroppedReason reason, Exception?exception)
        {
            if (reason == SubscriptionDroppedReason.Disposed)
            {
                return;
            }

            _started = false;
            Task.Run(Start);
        }
コード例 #17
0
 /// <summary>
 /// Removes the specified stream from the cache.
 /// </summary>
 /// <param name="streamId">The stream identifier.</param>
 /// <returns>The <see cref="Task"/></returns>
 public static async Task UnregisterStream(string streamId)
 {
     if (subscriptions.ContainsKey(streamId))
     {
         StreamSubscription subscription = null;
         while (!subscriptions.TryRemove(streamId, out subscription))
         {
             await Task.Delay(1);
         }
     }
 }
コード例 #18
0
 /// <summary>
 /// Unsubscribes from a topic.
 /// </summary>
 /// <param name="streamId">The stream identifier.</param>
 /// <param name="topic">The topic.</param>
 public static void UnsubscribeFromTopic(string streamId, string topic)
 {
     if (!string.IsNullOrEmpty(topic) && subscriptions.ContainsKey(streamId))
     {
         StreamSubscription subscriptionStream = subscriptions[streamId];
         if (subscriptionStream.Topics.Contains(topic))
         {
             subscriptionStream.Topics.Remove(topic);
         }
     }
 }
コード例 #19
0
        /// <summary>
        /// Start the subscription to EventStoreDB
        /// </summary>
        /// <param name="cancellationToken"></param>
        public async Task Start(CancellationToken cancellationToken)
        {
            var filter = new SubscriptionFilterOptions(EventTypeFilter.ExcludeSystemEvents());

            _subscription = await _client.SubscribeToAllAsync(Position.Start,
                                                              EventAppeared,
                                                              subscriptionDropped : SubscriptionDropped,
                                                              filterOptions : filter,
                                                              resolveLinkTos : true,
                                                              cancellationToken : cancellationToken);
        }
コード例 #20
0
        public Future forEach(Action <T> action)
        {
            _Future future = new _Future();
            StreamSubscription <T> subscription = null;

            subscription = listen(
                (T element) => {
                // TODO(floitsch): the type should be 'void' and inferred.
                _stream._runUserCode <object>(() => {
                    action(element);
                    return(default);
コード例 #21
0
        internal _SinkTransformerStreamSubscription(Stream <S> source, _async._SinkMapper <S, T> mapper,
                                                    Action <T> onData, Action <object, string> onError, Action onDone, bool cancelOnError)
        // We set the adapter's target only when the user is allowed to send data.
            : base(onData, onError, onDone, cancelOnError)
        {
            _EventSinkWrapper <T> eventSink = new _EventSinkWrapper <T>(this);

            _transformerSink = mapper(eventSink);
            _subscription    =
                source.listen(_handleData, onError: _handleError, onDone: _handleDone);
        }
コード例 #22
0
        private async static Task EventArrived(
            StreamSubscription subscription,
            ResolvedEvent resolvedEvent,
            CancellationToken cancellationToken)
        {
            var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray());

            var book = JsonConvert.DeserializeObject <Book>(jsonData);

            Console.WriteLine(jsonData);
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: lukszyn/DeliveryApp
        private async static Task EventArrived(
            StreamSubscription subscription,
            ResolvedEvent resolvedEvent,
            CancellationToken cancellationToken)
        {
            var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray());

            var packageData = JsonConvert.DeserializeObject <PackageData>(jsonData);

            SendEmail(packageData);
        }
コード例 #24
0
        public override StreamSubscription <T> listen(Action <T> onData,
                                                      Action <object, string> onError = null, Action onDone = null, bool cancelOnError = false)
        {
            //cancelOnError = cancelOnError;
            StreamSubscription <T> result = _onListen(_stream, cancelOnError);

            result.onData(onData);
            result.onError(onError);
            result.onDone(onDone);
            return(result);
        }
コード例 #25
0
        protected override Future _onCancel()
        {
            if (_isSubscribed)
            {
                StreamSubscription <S> subscription = _subscription;
                _subscription = null;
                return(subscription.cancel());
            }

            return(null);
        }
コード例 #26
0
            async Task EventAppeared(StreamSubscription _, ResolvedEvent resolvedEvent, CancellationToken c)
            {
                if (resolvedEvent.Event.EventType.StartsWith("$"))
                {
                    return;
                }

                var @event = resolvedEvent.Deserialize() !;
                await Task.WhenAll(
                    _subscriptions.Select(x => x.Project(@event))
                    );
            }
コード例 #27
0
        async Task Subscribe()
        {
            var room = system.StreamOf <ChatRoomMessage>("sms", RoomName);

            subscription = await room.Subscribe((message, _) =>
            {
                if (message.User != UserName)
                {
                    Console.WriteLine(message.Text);
                }
            });
        }
コード例 #28
0
        // ------------------------------------------------------------------
        // Stream interface.

        public override StreamSubscription <T> listen(
            Action <T> onData, Action <object, string> onError = null, Action onDone = null, bool cancelOnError = false)
        {
            // void onData(T data),
            // {Function onError, void onDone(), bool cancelOnError}) {
            cancelOnError = Equals(true, cancelOnError);
            StreamSubscription <T> subscription =
                _createSubscription(onData, onError, onDone, cancelOnError);

            _onListen(subscription);
            return(subscription);
        }
コード例 #29
0
        async Task Subscribe()
        {
            var room = system.StreamOf(Constants.StreamProviderNameDefault, Constants.StreamNameSpaceCustomers);

            subscription = await room.Subscribe <ChatRoomMessage>(message =>
            {
                if (message.User != UserName)
                {
                    Console.WriteLine(message.Text);
                }
            });
        }
コード例 #30
0
ファイル: ChatClient.cs プロジェクト: zloom/Orleankka
        public async Task Join()
        {
            subscription = await room.Subscribe <ChatRoomMessage>(message =>
            {
                if (message.User != UserName)
                {
                    Console.WriteLine(message.Text);
                }
            });

            await user.Tell(new Join { Room = RoomName });
        }
コード例 #31
0
 private void SubscriptionDropped(StreamSubscription subscription, SubscriptionDroppedReason reason,
                                  Exception?exception)
 {
     if (exception != null)
     {
         _logger.LogError($"PullRequestCommentsProjector dropped due to: {reason}", exception);
     }
     else
     {
         _logger.LogInformation($"PullRequestCommentsProjector dropped due to: {reason}");
     }
 }
コード例 #32
0
ファイル: AddStream.cs プロジェクト: w0pr/blizztv
        protected override void ParseSubscription()
        {
            if (txtName.Text.Trim() == "" || txtSlug.Text.Trim() == "")
            {
                MessageBox.Show(i18n.FillStreamNameAndUrlFieldsMessage, i18n.AllFieldsRequiredTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false));
                return;
            }

            StreamProvider provider = null;
            this.InvokeHandler(() => { provider = (StreamProvider)Providers.Instance.Dictionary[comboBoxProviders.SelectedItem.ToString().ToLower()]; });
            string streamKey = string.Format("{0}@{1}", txtSlug.Text, provider.Name.ToLower());

            if (Subscriptions.Instance.Dictionary.ContainsKey(streamKey))
            {
                MessageBox.Show(string.Format(i18n.StreamSubscriptionAlreadyExistsMessage, Subscriptions.Instance.Dictionary[streamKey].Name), i18n.SubscriptionExists, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false));
                return;
            }

            try
            {
                var subscription = new StreamSubscription { Name = txtName.Text, Slug = txtSlug.Text, Provider=provider.Name };

                using (var stream = StreamFactory.CreateStream(subscription))
                {
                    if (!stream.IsValid())
                    {
                        MessageBox.Show(i18n.ErrorParsingStreamMessage, i18n.ErrorParsingStreamTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false));
                        return;
                    }
                }

                this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(true, subscription));
            }
            catch (Exception)
            {
                MessageBox.Show(i18n.ErrorParsingStreamMessage, i18n.ErrorParsingStreamTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false));
            }
        }
コード例 #33
0
ファイル: JustinTV.cs プロジェクト: w0pr/blizztv
 public JustinTv(StreamSubscription subscription)
     : base(subscription)
 {
 }
コード例 #34
0
ファイル: Own3DTV.cs プロジェクト: w0pr/blizztv
 public Own3Dtv(StreamSubscription subscription)
     : base(subscription)
 {
 }
コード例 #35
0
ファイル: LiveStream.cs プロジェクト: w0pr/blizztv
 public LiveStream(StreamSubscription subscription)
     : base(subscription)
 {
 }