Esempio n. 1
0
        /// <summary>
        /// Sends the provided <paramref name="command"></paramref> and waits for an event of <typeparamref name="TEvent"/> or exits if the specified timeout is expired.
        /// </summary>
        /// <param name="command">The <typeparamref name="TCommand"/> to send.</param>
        /// <param name="condition">A delegate to be executed over and over until it returns the <typeparamref name="TEvent"/> that is desired, return null to keep trying.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="F:System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
        /// <param name="eventReceiver">If provided, is the <see cref="IEventReceiver{TAuthenticationToken}" /> that the event is expected to be returned on.</param>
        public TEvent SendAndWait <TCommand, TEvent>(TCommand command, Func <IEnumerable <IEvent <TAuthenticationToken> >, TEvent> condition, int millisecondsTimeout,
                                                     IEventReceiver <TAuthenticationToken> eventReceiver = null) where TCommand : ICommand <TAuthenticationToken>
        {
            if (eventReceiver != null)
            {
                throw new NotSupportedException("Specifying a different event receiver is not yet supported.");
            }
            if (!PrepareAndValidateCommand(command))
            {
                return((TEvent)(object)null);
            }

            TEvent result = (TEvent)(object)null;

            EventWaits.Add(command.CorrelationId, new List <IEvent <TAuthenticationToken> >());

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseCommand(command)));
            Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));

            SpinWait.SpinUntil(() =>
            {
                IList <IEvent <TAuthenticationToken> > events = EventWaits[command.CorrelationId];

                result = condition(events);

                return(result != null);
            }, millisecondsTimeout);

            return(result);
        }
Esempio n. 2
0
        public void Send <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            ICommandValidator <TAuthenticationToken, TCommand> commandValidator = null;

            try
            {
                commandValidator = DependencyResolver.Resolve <ICommandValidator <TAuthenticationToken, TCommand> >();
            }
            catch (Exception exception)
            {
                Logger.LogDebug("Locating an ICommandValidator failed.", string.Format("{0}\\Handle({1})", GetType().FullName, command.GetType().FullName), exception);
            }

            if (commandValidator != null && !commandValidator.IsCommandValid(command))
            {
                Logger.LogInfo("The provided command is not valid.", string.Format("{0}\\Handle({1})", GetType().FullName, command.GetType().FullName));
                return;
            }

            if (command.AuthenticationToken == null)
            {
                command.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            command.CorrelationId = CorrelationIdHelper.GetCorrelationId();

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseCommand(command)));
            Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));
        }
Esempio n. 3
0
 public static void Example(ServiceBusSettings settings)
 {
     _connection
         = new ServiceBusPublisher <string>("HowToPublish example", settings)
           .SetLog(new LogToConsole())
           .SetSerializer(new TestServiceBusSerializer())
           .Start();
 }
Esempio n. 4
0
        public override void Configure(IFunctionsHostBuilder hostBuilder)
        {
            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddEnvironmentVariables();
            var configuration = configurationBuilder.Build();

            //set up event store
            hostBuilder.Services.AddSingleton <IEventStoreConnection>(s => new EventStoreConnectionFactory(configuration).Create(s));
            hostBuilder.Services.AddSingleton <IEventStore, Infrastructure.EventStore.EventStore>(s =>
            {
                var con        = s.GetRequiredService <IEventStoreConnection>();
                var eventstore = new Infrastructure.EventStore.EventStore(con);
                return(eventstore);
            });

            var configRoot = new ConfigurationBuilder().AddEnvironmentVariables().Build();

            hostBuilder.Services.AddSingleton(sp => configRoot);

            //set up external service bus event publisher
            var externalBusEventPublisher = hostBuilder.Services.BuildServiceProvider().GetService <IPublisher>();

            if (externalBusEventPublisher == null)
            {
                string serviceBusConnectionString = configRoot["HOTEL_MANAGEMENT_SERVICEBUS"];
                string topicName = configRoot["INVENTORY_EVENTS_TOPIC_NAME"];
                externalBusEventPublisher = new ServiceBusPublisher(serviceBusConnectionString, topicName);
                hostBuilder.Services.AddSingleton(externalBusEventPublisher);
            }
            //set up repositories
            RegisterRepositories(hostBuilder, configRoot);
            ////repo factory set up
            var repositoryFactory = new RepositoryFactory(new DependencyResolver(hostBuilder.Services));

            hostBuilder.Services.AddScoped <IRepositoryFactory>(x =>
            {
                return(repositoryFactory);
            });
            //bus wiring
            var bus     = new Bus();
            var builder = new Builder(repositoryFactory);

            //register read model denormalizers
            RegisterReadModelDenormalizers(builder);
            //register builder handler with bus
            bus.RegisterEventHandler(builder.Handle);
            //register event store wrapper client
            var serviceProvider  = hostBuilder.Services.BuildServiceProvider();
            var eventStore       = serviceProvider.GetRequiredService <IEventStore>();
            var eventStoreClient = new EventStoreClient(bus, eventStore, externalBusEventPublisher);

            hostBuilder.Services.AddSingleton <IEventStoreClient>(sp => { return(eventStoreClient); });
            //register bus
            hostBuilder.Services.AddSingleton <IBus>(sp => { return(bus); });
        }
Esempio n. 5
0
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            if (!AzureBusHelper.PrepareAndValidateEvent(@event, "Azure-ServiceBus"))
            {
                return;
            }

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event)));
            Logger.LogInfo(string.Format("An event was published with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
        }
Esempio n. 6
0
        public void Send <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            if (!PrepareAndValidateCommand(command))
            {
                return;
            }

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseCommand(command)));
            Logger.LogInfo(string.Format("A command was sent of type {0}.", command.GetType().FullName));
        }
Esempio n. 7
0
        public virtual void Publish <TEvent>(TEvent @event)
            where TEvent : IEvent <TAuthenticationToken>
        {
            if (@event.AuthenticationToken == null)
            {
                @event.AuthenticationToken = AuthenticationTokenHelper.GetAuthenticationToken();
            }
            @event.CorrelationId = CorrelationIdHelper.GetCorrelationId();
            @event.TimeStamp     = DateTimeOffset.UtcNow;

            ServiceBusPublisher.Send(new BrokeredMessage(MessageSerialiser.SerialiseEvent(@event)));
            Logger.LogInfo(string.Format("An event was published with the id '{0}' was of type {1}.", @event.Id, @event.GetType().FullName));
        }
Esempio n. 8
0
        protected virtual void TriggerConnectionSettingsChecking()
        {
            Task.Factory.StartNew(() =>
            {
                SpinWait.SpinUntil(() => ConnectionString != ConfigurationManager.GetSetting(MessageBusConnectionStringConfigurationKey));

                Logger.LogInfo("Connecting string settings for the Azure Service Bus changed and will now refresh.");

                // Update the connection string and trigger a restart;
                ConnectionString = ConfigurationManager.GetSetting(MessageBusConnectionStringConfigurationKey);
                Logger.LogDebug(string.Format("Updated connecting string settings set to {0}.", ConnectionString));

                // Let's wrap up using this message bus and start the switch
                if (ServiceBusPublisher != null)
                {
                    ServiceBusPublisher.Close();
                    Logger.LogDebug("Publishing service bus closed.");
                }
                // Let's wrap up using this message bus and start the switch
                if (ServiceBusReceiver != null)
                {
                    ServiceBusReceiver.Close();
                    Logger.LogDebug("Receiving service bus closed.");
                }
                // Restart configuration, we order this intentionally with the receiver first as if this triggers the cancellation we know this isn't a publisher as well
                if (ServiceBusReceiver != null)
                {
                    Logger.LogDebug("Recursively calling into InstantiateReceiving.");
                    InstantiateReceiving();

                    // This will be the case of a connection setting change re-connection
                    if (ReceiverMessageHandler != null && ReceiverMessageHandlerOptions != null)
                    {
                        // Callback to handle received messages
                        Logger.LogDebug("Re-registering onMessage handler.");
                        ServiceBusReceiver.OnMessage(ReceiverMessageHandler, ReceiverMessageHandlerOptions);
                    }
                    else
                    {
                        Logger.LogWarning("No onMessage handler was found to re-bind.");
                    }
                }
                // Restart configuration, we order this intentionally with the publisher second as if this triggers the cancellation there's nothing else to process here
                if (ServiceBusPublisher != null)
                {
                    Logger.LogDebug("Recursively calling into InstantiatePublishing.");
                    InstantiatePublishing();
                }
            });
        }
Esempio n. 9
0
        protected override void TriggerSettingsChecking()
        {
            // Let's wrap up using this message bus and start the switch
            if (ServiceBusPublisher != null)
            {
                ServiceBusPublisher.Close();
                Logger.LogDebug("Publishing service bus closed.");
            }
            foreach (SubscriptionClient serviceBusReceiver in ServiceBusReceivers.Values)
            {
                // Let's wrap up using this message bus and start the switch
                if (serviceBusReceiver != null)
                {
                    serviceBusReceiver.Close();
                    Logger.LogDebug("Receiving service bus closed.");
                }
                // Restart configuration, we order this intentionally with the receiver first as if this triggers the cancellation we know this isn't a publisher as well
                if (serviceBusReceiver != null)
                {
                    Logger.LogDebug("Recursively calling into InstantiateReceiving.");
                    InstantiateReceiving();

                    // This will be the case of a connection setting change re-connection
                    if (ReceiverMessageHandler != null && ReceiverMessageHandlerOptions != null)
                    {
                        // Callback to handle received messages
                        Logger.LogDebug("Re-registering onMessage handler.");
                        ApplyReceiverMessageHandler();
                    }
                    else
                    {
                        Logger.LogWarning("No onMessage handler was found to re-bind.");
                    }
                }
            }
            // Restart configuration, we order this intentionally with the publisher second as if this triggers the cancellation there's nothing else to process here
            if (ServiceBusPublisher != null)
            {
                Logger.LogDebug("Recursively calling into InstantiatePublishing.");
                InstantiatePublishing();
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Publish <see cref="IIntegrationEvent"/> to service bus
 /// </summary>
 /// <param name="publisher"><see cref="ServiceBusPublisher"/></param>
 /// <param name="event"><see cref="IIntegrationEvent"/> that needs to be published</param>
 /// <param name="cancellationToken"><see cref="CancellationToken"/></param>
 /// <returns><see cref="Task"/></returns>
 public static async Task Publish(this ServiceBusPublisher publisher, IIntegrationEvent @event, CancellationToken cancellationToken = default)
 {
     await publisher(@event, cancellationToken);
 }
Esempio n. 11
0
 /// <summary/>
 public ServiceBus(ServiceBusPublisher publisher)
 {
     _publisher = publisher;
 }