Exemplo n.º 1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (!_eventsSubscribed)
                {
                    _eventSubscriber
                    .Subscribe <NewProductAddedEvent>()
                    .OnFailure(cf =>
                    {
                        cf.RetryForTimes(5)
                        .ForEachRetryWait(TimeSpan.FromSeconds(5))
                        .ShouldRetry()
                        .ShouldDiscardEventAfterFailures();
                    });

                    using (var scope = _serviceProvider.CreateScope())
                    {
                        await scope.ServiceProvider.GetService <IEventPublisher>().PublishAsync(new NewProductAddedEvent());
                    }

                    await _eventSubscriber.StartListeningAsync();

                    _eventsSubscribed = true;
                }
            }
        }
Exemplo n.º 2
0
        public void Subscribe(IProxy proxy, EventInfo @event, Delegate @delegate)
        {
            var eventDesc = new EventDescriptor
            {
                ServiceId = ((ServiceProxyContext)proxy.Context).Service.Id,
                EventId   = _eventIdProvider.GetId(@event)
            };

            if (@delegate.Target is IProxy subscriberProxy)
            {
                var subscriberProxyContext = (ServiceProxyContext)(subscriberProxy.Context ?? ServiceProxyBuildingContext.CurrentServiceProxyContext);
                var subscriberServiceId    = subscriberProxyContext.Service.Id;
                var subscriberMethodId     = _routineMethodIdProvider.GetId(@delegate.GetMethodInfo());

                var subscriberDesc = new EventSubscriberDescriptor
                {
                    ServiceId = subscriberServiceId,
                    MethodId  = subscriberMethodId
                };

                _eventSubscriber.Subscribe(eventDesc, subscriberDesc);
            }
            else
            {
                throw new NotSupportedException("At this moment event subscribers must be routines of services.");
            }
        }
Exemplo n.º 3
0
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            _eventSubscriber.Subscribe <TrippleReturned>(t => AgeBox.Text  = t.TrippleValue.ToString());
            _eventSubscriber.Subscribe <DoubleReturned>(d => AgeBox.Text   = d.DoubledValue.ToString());
            _eventSubscriber.Subscribe <DoubleReturned>(d => OtherBox.Text = d.DoubledValue.ToString() + d.DoubledValue.ToString());
            _eventSubscriber.Subscribe((NeedData d) => d.InputData + d.InputData);

            DoubleReturned age;

            using (var proxy = new MyServiceClinet())
            {
                age = await proxy.GetAgeAsync();
            }

            AgeBox.Text = age.DoubledValue.ToString();
        }
Exemplo n.º 4
0
 private void SetupSubscription(string eventName)
 {
     if (!_subscriptionsManager.HasSubscriptionsForEvent(eventName))
     {
         _subscriber.Subscribe(eventName);
     }
 }
Exemplo n.º 5
0
        private async Task HandleSubscribe(HttpContext context)
        {
            var         contentType = context.Request.GetContentType();
            ISerializer serializer;

            try
            {
                serializer = GetSerializer(contentType, false);
            }
            catch (ArgumentException)
            {
                await ReplyWithTextError(context.Response, 406, $"The Content-Type '{contentType.MediaType}' is not supported");

                return;
            }

            var envelope = await DeserializeAsync <SubscribeEnvelope>(serializer, context.Request.Body);

            var eventDesc = new EventDescriptor {
                Service = envelope.Service, Event = envelope.Event
            };

            foreach (var subscriber in envelope.Subscribers)
            {
                _eventSubscriber.Subscribe(eventDesc, subscriber);
            }

            context.Response.StatusCode = 200;
        }
Exemplo n.º 6
0
 public void Listen(string serviceId)
 {
     _eventSubscriber.Subscribe <ConfigurationChangedEvent>(ConfigurationChangedEvent.EventName, (eventObj) =>
     {
         Console.WriteLine($"{serviceId}: Configuration for key [{eventObj.Key}] has been changed to [{eventObj.Value}] on [{eventObj.DateTime.ToString()}]");
     });
 }
Exemplo n.º 7
0
        public static void Subscribe(this IEventSubscriber subscriber, string eventRoute, IEventHandler handler)
        {
            Check.NotNull(subscriber, nameof(subscriber));
            Check.NotNull(eventRoute, nameof(eventRoute));
            Check.NotNull(handler, nameof(handler));

            subscriber.Subscribe(eventRoute, new IEventHandler[] { handler });
        }
Exemplo n.º 8
0
        public static void Subscribe <TEvent>(this IEventSubscriber subscriber, IEventHandler handler)
            where TEvent : IEvent
        {
            Check.NotNull(subscriber, nameof(subscriber));
            Check.NotNull(handler, nameof(handler));

            subscriber.Subscribe(typeof(TEvent).GetEventRoute(), new IEventHandler[] { handler });
        }
Exemplo n.º 9
0
        public static void Subscribe <TEvent>(this IEventSubscriber subscriber, IEnumerable <IEventHandler> handlers)
            where TEvent : IEvent
        {
            Check.NotNull(subscriber, nameof(subscriber));
            Check.NotNull(handlers, nameof(handlers));

            subscriber.Subscribe(typeof(TEvent).GetEventRoute(), handlers);
        }
        /// <summary>
        /// Subscribes to the event indicating that the location has changed.
        /// </summary>
        public void Subscribe()
        {
            if (_eventUnsubscriber != null)
            {
                return;
            }

            _eventUnsubscriber = _subscriber.Subscribe <LocationChangedEvent>(e => OnLocationChanged(e.NewLocation));
        }
Exemplo n.º 11
0
        public static Guid Subscribe <TMessage>([NotNull] this IEventSubscriber bus, Func <TMessage, Task> handler, SubscriptionFactoryOptions <TMessage> options)
        {
            if (bus == null)
            {
                throw new ArgumentNullException(nameof(bus));
            }

            return(bus.Subscribe((message, cancellationToken) => handler?.Invoke(message), options));
        }
Exemplo n.º 12
0
        public static Guid Subscribe <TMessage>([NotNull] this IEventSubscriber bus, Func <TMessage, Task> handler)
        {
            if (bus == null)
            {
                throw new ArgumentNullException(nameof(bus));
            }

            return(bus.Subscribe <TMessage>((message, cancellationToken) => handler(message)));
        }
Exemplo n.º 13
0
        public static void Subscribe <TEvent, TContext>(this IEventSubscriber subscriber, string eventRoute, Func <TEvent, TContext, Task> func)
            where TEvent : IEvent
            where TContext : EventContext
        {
            Check.NotNull(subscriber, nameof(subscriber));
            Check.NotNull(eventRoute, nameof(eventRoute));
            Check.NotNull(func, nameof(func));

            subscriber.Subscribe(eventRoute, new IEventHandler[] { new InternalEventHandler <TEvent, TContext>(func) });
        }
Exemplo n.º 14
0
        public static Guid Subscribe <TMessage>([NotNull] this IEventSubscriber bus, Action <TMessage> handler)
        {
            if (bus == null)
            {
                throw new ArgumentNullException(nameof(bus));
            }

            return(bus.Subscribe <TMessage>((message, cancellationToken) =>
            {
                handler?.Invoke(message);
                return Task.CompletedTask;
            }));
        }
Exemplo n.º 15
0
        protected override async Task OnStart(IMessageSession session)
        {
            Logger.Write(LogLevel.Info, "Starting event consumer");
            await _subscriber.Setup(
                _settings.EndpointName(),
                _settings.Get <int>("ReadSize"),
                _settings.Get <bool>("ExtraStats")).ConfigureAwait(false);


            await _subscriber.Subscribe(_cancellationTokenSource.Token).ConfigureAwait(false);

            _subscriber.Dropped = (reason, ex) =>
            {
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Write(LogLevel.Info, () => $"Event consumer stopped - cancelation requested");
                    return;
                }
                Logger.Warn($"Event consumer stopped due to exception: {ex.Message}.  Will restart", ex);
                Thread.Sleep(CalculateSleep());
                _subscriber.Subscribe(_cancellationTokenSource.Token).Wait();
            };
        }
Exemplo n.º 16
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            async void OnCancellation(object?_, CancellationToken ct)
            {
                _discordSocketClient.MessageReceived -= Bot_MessageReceived;
                _discordSocketClient.Log             -= Bot_Log;
                await _discordSocketClient.StopAsync();

                _logger.LogWarning("Stopped Discord Bot");

                _eventSubscriber.Dispose();
            }

            using var scope = _scopeFactory.CreateScope();
            await _commands.AddModulesAsync(typeof(DiscordCommands).Assembly, scope.ServiceProvider);

            if (_discordSocketClient.ConnectionState != ConnectionState.Disconnecting && _discordSocketClient.ConnectionState != ConnectionState.Disconnected)
            {
                return;
            }

            var botToken = _options.BotToken;

            if (string.IsNullOrEmpty(botToken))
            {
                _logger.LogError("Error while getting Discord.BotToken! Check your configuration file");
                return;
            }

            _discordSocketClient.MessageReceived += Bot_MessageReceived;
            _discordSocketClient.Log             += Bot_Log;

            await _discordSocketClient.LoginAsync(TokenType.Bot, botToken);

            await _discordSocketClient.StartAsync();

            await _retryPolicy.ExecuteAsync(async token => await _eventSubscriber.Subscribe(token), stoppingToken);

            _logger.LogWarning("Started Discord Bot");

#if NET5_0
            stoppingToken.Register(_ => OnCancellation(null, stoppingToken), null);
#else
            stoppingToken.Register(OnCancellation, null);
#endif
        }
Exemplo n.º 17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            void OnCancellation(object?_, CancellationToken ct)
            {
                _bot.OnMessage -= Bot_OnMessageReceived;
                _logger.LogWarning("Stopped Slack Bot");
                _eventSubscriber.Dispose();
            }

            _bot.OnMessage += Bot_OnMessageReceived;
            await _bot.Connect(stoppingToken);

            await _retryPolicy.ExecuteAsync(async token => await _eventSubscriber.Subscribe(token), stoppingToken);

            _logger.LogWarning("Started Slack Bot");

#if NET5_0
            stoppingToken.Register(_ => OnCancellation(null, stoppingToken), null);
#else
            stoppingToken.Register(OnCancellation, null);
#endif
        }
Exemplo n.º 18
0
 /// <summary>
 /// Subscribes to the event using the <see cref="IEventSubscriber"/> instance.
 /// </summary>
 /// <returns>The instance to be disposed for unsubscribe.</returns>
 public IDisposable Subscribe()
 {
     return(_subscriber.Subscribe <EventArgs>(OnReceive));
 }
Exemplo n.º 19
0
 protected override void AddEventSubscriptions(IEventSubscriber subscriber)
 {
     base.AddEventSubscriptions(subscriber);
     subscriber.Subscribe <StationResponseEvent, StationResult>(async(response) => await DislayMoreInfo(response));
 }
Exemplo n.º 20
0
 public void Start()
 {
     subscriber.Subscribe();
 }
Exemplo n.º 21
0
 /// <summary>
 /// add event handler for event
 /// </summary>
 /// <typeparam name="TEvent">TEvent</typeparam>
 /// <typeparam name="TEventHandler">TEventHandler</typeparam>
 /// <returns>whether the operation success</returns>
 public static bool Subscribe <TEvent, TEventHandler>(this IEventSubscriber subscriber)
     where TEventHandler : class, IEventHandler <TEvent>
     where TEvent : class, IEventBase
 {
     return(subscriber.Subscribe(typeof(TEvent), typeof(TEventHandler)));
 }
Exemplo n.º 22
0
 protected override void AddEventSubscriptions(IEventSubscriber subscriber)
 {
     base.AddEventSubscriptions(subscriber);
     subscriber.Subscribe <MetarResponseEvent, MetarResult>(async(response) => await UpdateMetarInfo(response));
 }