Beispiel #1
0
        public void DefaultSerializersAdded_WhenNotSpecifiedByHost()
        {
            var settings     = new BrokerSettings();
            var mockExchange = new Mock <IMessageBroker>();
            MessageBrokerState brokerConfig = null;

            mockExchange.Setup(b => b.Initialize(It.IsAny <MessageBrokerState>()))
            .Callback <MessageBrokerState>(cfg => brokerConfig = cfg);

            ModuleTest.Arrange(config =>
            {
                config.AddPlugin <MockAppHostPlugin>();
            })
            .Act(c =>
            {
                AddTestMocks(c, settings, mockExchange.Object);
                c.Build().Start();
            });

#if NETCOREAPP1_0
            brokerConfig.SerializationMgr.Serializers.Should().HaveCount(1);
            brokerConfig.SerializationMgr.Serializers.Select(s => s.ContentType).Should().Contain(SerializerTypes.Json);
#endif

#if NET461
            brokerConfig.SerializationMgr.Serializers.Should().HaveCount(3);
            brokerConfig.SerializationMgr.Serializers.Select(s => s.ContentType).Should().Contain(SerializerTypes.Json);
            brokerConfig.SerializationMgr.Serializers.Select(s => s.ContentType).Should().Contain(SerializerTypes.Binary);
            brokerConfig.SerializationMgr.Serializers.Select(s => s.ContentType).Should().Contain(SerializerTypes.MessagePack);
#endif
        }
Beispiel #2
0
        public static void AddAdminQueueListener(this IServiceCollection services, IConfiguration configuration)
        {
            var listenerSection = configuration.GetSection("Queue").GetSection("Listener");
            var brokerSection   = configuration.GetSection("Queue").GetSection("Broker");
            var queueSettings   = new ReceiverSettings
            {
                Queue        = listenerSection["Queue"],
                Durable      = bool.Parse(listenerSection["Durable"]),
                AutoAck      = bool.Parse(listenerSection["AutoAck"]),
                Exchange     = listenerSection["Exchange"],
                ExchangeType = listenerSection["ExchangeType"],
                Keys         = listenerSection["RoutingKeys"]?.Split(';')?.ToList()
            };
            var brokerSettings = new BrokerSettings
            {
                Host     = brokerSection["Host"],
                Port     = int.Parse(brokerSection["Port"]),
                User     = brokerSection["User"],
                Password = brokerSection["Password"]
            };

            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddSingleton(brokerSettings);
            services.AddSingleton(queueSettings);
            services.AddHostedService <AdminQueueListener>();
        }
Beispiel #3
0
        public SmcTicketThread(SmcDto smcDto, ClientSettings clientSettings,
                               BrokerSettings brokerSettings, IMqttClientConfiguration mqttClientConfiguration,
                               IMqttClientMethods mqttClientMethods, Topic topic,
                               CommandRules commandRules, IEventService eventService, IForwarderSenderService forwarderSenderService)
        {
            Smc                             = smcDto;
            _eventService                   = eventService;
            _forwarderSenderService         = forwarderSenderService;
            Tickets                         = new ConcurrentPriorityQueue <TicketThreadObject>();
            _executingCommandSemaphore      = new SemaphoreSlim(1, 1);
            _waitingCommandMessageSemaphore = new SemaphoreSlim(1, 1);
            _answerSemaphore                = new SemaphoreSlim(1, 1);

            var localClientSettings = new ClientSettings
            {
                ClientId = clientSettings.ClientId, ClientName = clientSettings.ClientName
            };

            localClientSettings.ClientId   = localClientSettings.ClientId.Replace("serial", smcDto.Serial);
            localClientSettings.ClientName = localClientSettings.ClientName.Replace("serial", smcDto.Serial);
            localClientSettings.DebugMode  = clientSettings.DebugMode;
            localClientSettings.AutoReconnectDelayInSeconds = clientSettings.AutoReconnectDelayInSeconds;
            var localTopic = new Topic {
                Address = topic.Address, QoS = topic.QoS
            };

            localTopic.Address = localTopic.Address
                                 .Replace("{smc-or-meter}", CommandDeviceType.Smc.ToString().ToLower())
                                 .Replace("{serial}", smcDto.Serial);
            _mqttClient = new IoGMqttClient(localClientSettings, brokerSettings, mqttClientConfiguration,
                                            mqttClientMethods);
            _mqttClient.Subscribe(localTopic);
            _mqttClient.MessageReceivedHandler += ReceivedUpdate;
            _commandRules = commandRules;
        }
Beispiel #4
0
        public void SettingsBrokerName_MustBeUnique()
        {
            var settings     = new BrokerSettings();
            var mockExchange = new Mock <IMessageBroker>();

            settings.Connections = new List <BrokerConnectionSettings>
            {
                new BrokerConnectionSettings {
                    BrokerName = "Broker1"
                },
                new BrokerConnectionSettings {
                    BrokerName = "Broker1"
                }
            };

            ModuleTest.Arrange(config =>
            {
                config.AddPlugin <MockAppHostPlugin>();
            })
            .Test(c =>
            {
                AddTestMocks(c, settings, mockExchange.Object);
                c.Build().Start();
            },
                  (c, e) =>
            {
                e.Should().BeOfType <ContainerException>();
            });
        }
Beispiel #5
0
        // -------------------------- UNIT-TEST SETUP -------------------------------------------

        // Returns a test setup containing a configured MessageBrokerState instance and mocked
        // ConnectionManager.  This simulates the state built by the MessageBrokerModule that is
        // used to initialize a MessageBroker instance and passed to the internal initialization
        // classes to which it delegates.
        public static BrokerStateSetup SetupBrokerState(BrokerSettings brokerSettings = null)
        {
            var serializer  = new JsonBrokerSerializer();
            var brokerState = new MessageBrokerState
            {
                BrokerSettings = brokerSettings ?? new BrokerSettings
                {
                    Connections = new List <BrokerConnectionSettings>
                    {
                        new BrokerConnectionSettings {
                            BrokerName = "MockTestBrokerName", HostName = "TestHost"
                        }
                    }
                }
            };

            var serializers = new Dictionary <string, IBrokerSerializer>
            {
                { serializer.ContentType, serializer }
            };

            var mockConnMgr = new MockConnectionManager(
                new TestLoggerFactory(),
                brokerState.BrokerSettings,
                new Dictionary <string, object>());

            brokerState.ConnectionMgr    = mockConnMgr;
            brokerState.SerializationMgr = new SerializationManager(serializers);
            return(new BrokerStateSetup
            {
                BrokerState = brokerState,
                MockConnMgr = mockConnMgr
            });
        }
        public static void AddIntegrations(this IServiceCollection services, IConfiguration configuration)
        {
            var senderSection = configuration.GetSection("Integration").GetSection("Sender");
            var brokerSection = configuration.GetSection("Integration").GetSection("Broker");

            bool.TryParse(senderSection["Durable"], out var durable);
            var queueSettings = new SenderSettings
            {
                Queue        = senderSection["Queue"],
                Durable      = durable,
                ExchangeType = senderSection["ExchangeType"],
                Exchange     = senderSection["Exchange"]
            };
            var brokerSettings = new BrokerSettings
            {
                Host     = brokerSection["Host"],
                Port     = int.Parse(brokerSection["Port"]),
                User     = brokerSection["User"],
                Password = brokerSection["Password"]
            };

            services.AddScoped((provider) =>
            {
                return(new QueueSender(queueSettings, brokerSettings));
            });
            services.AddScoped <AdministrationNotifier>();
            services.AddScoped <GivingPromoCodeToCustomerNotifier>();
        }
 private void InitializeExchanges(BrokerSettings brokerSettings)
 {
     foreach (IMessageExchange exchange in Exchanges)
     {
         exchange.InitializeSettings(brokerSettings);
     }
 }
Beispiel #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HarmonyMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="harmonyClient">The Harmony client.</param>
        /// <param name="harmonyName">The Harmony name.</param>
        /// <param name="harmonyKeyPressLength">The Harmony key press length.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public HarmonyMqttService(
            ILogger <HarmonyMqttService> logger,
            IClient harmonyClient,
            string harmonyName,
            int harmonyKeyPressLength,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "harmony/" + harmonyName)
        {
            _log            = logger;
            _topicActionMap = new Dictionary <string, string>();
            SubscribedTopics.Add(TopicRoot + "/devices/+/+/+/set");
            SubscribedTopics.Add(TopicRoot + "/activity/set");
            SubscribedTopics.Add(TopicRoot + "/activity/+/set");

            // Setup harmony client
            _client                         = harmonyClient;
            _harmonyName                    = harmonyName;
            _harmonyKeyPressLength          = harmonyKeyPressLength;
            _client.CurrentActivityUpdated += Harmony_CurrentActivityUpdated;

            // Harmony client logging
            _client.MessageSent     += (object sender, MessageSentEventArgs e) => { _log.LogInformation("Harmony Message sent: " + e.Message); };
            _client.MessageReceived += (object sender, MessageReceivedEventArgs e) => { _log.LogInformation("Harmony Message received: " + e.Message); };
            _client.Error           += (object sender, System.IO.ErrorEventArgs e) =>
            {
                var exception = e.GetException();
                _log.LogError(exception, exception.Message);
                throw new Exception("Harmony connection lost");
            };
        }
Beispiel #9
0
 public BrokerService(IOptions <BrokerSettings> settings, ISubscriptionsService subscriptionsService, ILogger <BrokerService> logger)
 {
     this.settings             = settings.Value;
     this.subscriptionsService = subscriptionsService;
     this.logger = logger;
     this.statisticsDataSender = new DataSender <ItemModel>(this.settings.StatisticsUrl);
 }
Beispiel #10
0
        public void ExchangeDefinitions_Discovered()
        {
            var settings     = new BrokerSettings();
            var mockExchange = new Mock <IMessageBroker>();
            MessageBrokerState brokerState = null;

            mockExchange.Setup(b => b.Initialize(It.IsAny <MessageBrokerState>()))
            .Callback <MessageBrokerState>(s => brokerState = s);

            // Define the broker connection and an externally defined queue route key.
            settings.Connections = new List <BrokerConnectionSettings>
            {
                new BrokerConnectionSettings {
                    BrokerName      = "MockTestBrokerName",
                    QueueProperties = new QueuePropertiesSettings[] {
                        new QueuePropertiesSettings {
                            QueueName = "MockTestQueueName", RouteKeys = new [] { "RouteKeyTwo" }
                        }
                    }
                }
            };

            ModuleTest.Arrange(config =>
            {
                config.AddPlugin <MockAppHostPlugin>()
                .AddPluginType <MockTopicExchange>()
                .AddPluginType <MockExchange>();
            })
            .Act(c =>
            {
                c.WithConfig((MessagingConfig config) =>
                {
                    config.AddMessagePublisher <RabbitMqMessagePublisher>();
                });

                AddTestMocks(c, settings, mockExchange.Object);
                c.Build().Start();
            });

            // Verify that module initialized the message broker with the exchanges:
            brokerState.Should().NotBeNull();
            brokerState.BrokerSettings.Should().NotBeNull();
            brokerState.Exchanges.Should().NotBeNull();
            // metadata.Connections.Should().NotBeNull();

            // Verify that the correct exchanges were determined.
            brokerState.Exchanges.Should().HaveCount(2);
            brokerState.Exchanges.Should().Contain(e => e.ExchangeName == "MockDirectExchangeName");
            brokerState.Exchanges.Should().Contain(e => e.ExchangeName == "MockTopicExchangeName");

            // Verify that the externally defined route key was added to the queue:
            var directExchange = brokerState.Exchanges.First(e => e.ExchangeName == "MockDirectExchangeName");
            var queue          = directExchange.Queues.FirstOrDefault();

            queue.Should().NotBeNull();
            queue.RouteKeys.Should().HaveCount(1);
            queue.RouteKeys.Should().Contain(k => k == "RouteKeyTwo");
        }
Beispiel #11
0
        private static async Task Main()
        {
            await new HostBuilder()
            .ConfigureAppConfiguration((hostContext, builder) =>
            {
                builder
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            })
            .ConfigureServices((hostContext, services) =>
            {
                var brokerSettings = new BrokerSettings();
                hostContext.Configuration.GetSection("RabbitSettings").Bind(brokerSettings);

                services.AddSingleton <IConsumer <IMoveReservedLimitAmountToRegularAccount>, MoveReservedLimitAmountToRegularAccountConsumer>();

                services.AddMassTransit(configure =>
                {
                    configure.AddConsumer <MoveReservedLimitAmountToRegularAccountConsumer>();

                    configure.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(configureBus =>
                    {
                        var hostBus = configureBus.Host(new Uri(brokerSettings.Host), configureHost =>
                        {
                            configureHost.Username(brokerSettings.User);
                            configureHost.Password(brokerSettings.Password);
                        });

                        configureBus.ReceiveEndpoint(hostBus, brokerSettings.InputQueue, configureEndpoint =>
                        {
                            configureEndpoint.Consumer <MoveReservedLimitAmountToRegularAccountConsumer>(provider);
                        });

                        //configureBus.ConfigureEndpoints(provider);
                        configureBus.UseSerilog();
                        //configureBus.UseInMemoryOutbox();
                        //configureBus.MessageTopology.SetEntityNameFormatter(new CustomEntityFormatter("bankdeposit"));
                    }));

                    //configure.AddRequestClient<IAnalyzeBankDepositTransactionRequest>();
                });

                services.AddMassTransitHostedService();
            })
            .ConfigureLogging((hostContext, configLogging) =>
            {
                configLogging
                .AddSerilog()
                .AddConsole()
                .AddDebug()
                .SetMinimumLevel(LogLevel.Debug);
            })
            .UseConsoleLifetime()
            .Build().StartAsync();
        }
Beispiel #12
0
        // Called by Message Broker when defining exchanges and allows a
        // specific declared application exchange to specific its settings.
        public void InitializeSettings(BrokerSettings brokerSettings)
        {
            SetOptionalScriptSettings();
            OnDeclareExchange();
            OnApplyConventions();

            brokerSettings.ApplyQueueSettings(this);

            ValidateConfiguration();
        }
            public static void PreStart()
            {
                if (!BrokerSettings.IsValid())
                {
                    return;
                }

                AppDomain.CurrentDomain.AssemblyResolve += Broker_AssemblyResolve;

                Assembly.LoadFrom(Path.Combine(HostingEnvironment.ApplicationPhysicalPath,
                                               $"broker/{BrokerSettings.Default.Version}/NVShop.Data.eNVenta.dll"));
            }
        public MockConnectionManager(
            ILoggerFactory logger,
            BrokerSettings brokerSettings,
            IDictionary <string, object> clientProperties) :
            base(logger, brokerSettings, clientProperties)
        {
            this.MockConn    = new Mock <IConnection>();
            this.MockChannel = new Mock <IModel>();

            this.MockConn.Setup(c => c.CreateModel())
            .Returns(MockChannel.Object);
        }
Beispiel #15
0
        public void MessageConsumers_Determined()
        {
            var settings     = new BrokerSettings();
            var mockExchange = new Mock <IMessageBroker>();
            IEnumerable <MessageConsumer> consumers = null;

            mockExchange.Setup(b => b.BindConsumers(It.IsAny <IEnumerable <MessageConsumer> >()))
            .Callback <IEnumerable <MessageConsumer> >(mc => consumers = mc);

            // Define the broker connection and an externally defined queue route key.
            settings.Connections = new List <BrokerConnectionSettings>
            {
                new BrokerConnectionSettings {
                    BrokerName = "MockTestBrokerName"
                }
            };

            ModuleTest.Arrange(config =>
            {
                // Add an exchange definition and consumer service.
                config.AddPlugin <MockAppHostPlugin>()
                .AddPluginType <MockExchange>()
                .AddPluginType <MockMessageConsumer>();
            })
            .Act(c =>
            {
                c.WithConfig((MessagingConfig config) =>
                {
                    config.AddMessagePublisher <RabbitMqMessagePublisher>();
                });

                AddTestMocks(c, settings, mockExchange.Object);
                c.Build().Start();
            });

            consumers.Should().NotBeNull();
            consumers.Should().HaveCount(2);

            // Verify that the consumer event hander that is joining an existing queue on the exchange.
            var joinedConsumer = consumers.FirstOrDefault(c => c.BindingType == QueueBindingTypes.Join);

            joinedConsumer.Should().NotBeNull();
            joinedConsumer.ExchangeName.Should().Be("MockDirectExchangeName");
            joinedConsumer.QueueName.Should().Be("MockTestQueueName");

            // Verify the consumer event handler that is creating an exclusive queue on the exchange.
            var addConsumer = consumers.FirstOrDefault(c => c.BindingType == QueueBindingTypes.Create);

            addConsumer.Should().NotBeNull();
            addConsumer.ExchangeName.Should().Be("MockDirectExchangeName");
            addConsumer.QueueName.Should().BeEmpty(); // The server will assign name.
        }
Beispiel #16
0
        public void ExchangeBrokerNameNotConfigured_Exception()
        {
            var emptySettings = new BrokerSettings();
            var stateSetup    = BrokerTest.SetupBrokerState(emptySettings);
            var brokerSetup   = BrokerTest.SetupMessageBroker();
            var exchange      = new MockExchange();

            exchange.InitializeSettings(emptySettings);
            stateSetup.BrokerState.Exchanges = new[] { exchange };
            stateSetup.BrokerState.BrokerSettings.Connections.Clear();

            Assert.Throws <BrokerException>(() => brokerSetup.Initialize(stateSetup.BrokerState));
        }
        public ConnectionManager(
            ILoggerFactory loggerFactory,
            BrokerSettings brokerSettings,
            IDictionary <string, object> clientProperties)
        {
            Check.NotNull(loggerFactory, nameof(loggerFactory));
            Check.NotNull(brokerSettings, nameof(brokerSettings));
            Check.NotNull(clientProperties, nameof(clientProperties));

            _logger           = loggerFactory.CreateLogger <ConnectionManager>();
            _brokerSettings   = brokerSettings;
            _clientProperties = clientProperties;

            _connections = GetConnections(brokerSettings);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NeatoMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="neatoClient">Neato client.</param>
        /// <param name="neatoName">Neato name.</param>
        /// <param name="refreshInterval">Refresh interval.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public NeatoMqttService(
            ILogger <NeatoMqttService> logger,
            IRobot neatoClient,
            string neatoName,
            int refreshInterval,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "neato/" + neatoName)
        {
            _log             = logger;
            _refreshInterval = refreshInterval * 1000;

            SubscribedTopics.Add(TopicRoot + "/+/set");

            _client = neatoClient;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EcobeeMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="ecobeeClient">The Ecobee client.</param>
        /// <param name="ecobeeName">The target Ecobee name.</param>
        /// <param name="refreshInterval">The refresh interval.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public EcobeeMqttService(
            ILogger <EcobeeMqttService> logger,
            Client ecobeeClient,
            string ecobeeName,
            int refreshInterval,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "ecobee/" + ecobeeName)
        {
            _log             = logger;
            _refreshInterval = refreshInterval * 1000;
            SubscribedTopics.Add(TopicRoot + "/+/+/set");

            _client = ecobeeClient;
            _revisionStatusCache = new Dictionary <string, RevisionStatus>();
            _thermostatStatus    = new Dictionary <string, ThermostatStatus>();
        }
Beispiel #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApexMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="apexClient">Apex client.</param>
        /// <param name="apexName">Apex name.</param>
        /// <param name="refreshInterval">Refresh interval.</param>
        /// <param name="publishOnlyChangedValues">Only publish values when they change from previous value.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public ApexMqttService(
            ILogger <ApexMqttService> logger,
            Client apexClient,
            string apexName,
            int refreshInterval,
            bool publishOnlyChangedValues,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "apex/" + apexName)
        {
            _log                      = logger;
            _refreshInterval          = refreshInterval * 1000;
            _publishOnlyChangedValues = publishOnlyChangedValues;
            SubscribedTopics.Add(TopicRoot + "/outlets/+/set");
            SubscribedTopics.Add(TopicRoot + "/feedCycle/set");

            _client = apexClient;
        }
Beispiel #21
0
 public ThreadService(IMqttClientMethods mqttClientMethods, IMqttClientConfiguration mqttClientConfiguration,
                      IOptions <Forwarder> forwarderConfig, IServiceProvider serviceProvider, ISmcService smcService,
                      IOptions <CommandRules> commandRules, IEventService eventService,
                      IForwarderSenderService forwarderSenderService, IMeterService meterService)
 {
     _mqttClientConfiguration = mqttClientConfiguration;
     _mqttClientMethods       = mqttClientMethods;
     _brokerSettings          = forwarderConfig.Value.Mqtt.BrokerSettings;
     _baseClientSettings      = forwarderConfig.Value.Mqtt.CommandsBaseClientSettings;
     _subscribeTopic          = forwarderConfig.Value.Mqtt.BaseCommandsSubscribeTopic;
     _smcService   = smcService;
     _commandRules = commandRules.Value;
     _eventService = eventService;
     _eventService.AThreadIsShuttingDown += AThreadIsShuttingDown;
     _forwarderSenderService              = forwarderSenderService;
     _meterService = meterService;
 }
Beispiel #22
0
        // Sets mock broker settings and mock message broker.  These specified instances will be
        // registered overriding the default instances.
        private ContainerTest AddTestMocks(IAppContainer container, BrokerSettings settings, IMessageBroker broker)
        {
            container.WithConfig <AutofacRegistrationConfig>(config =>
            {
                config.Build = builder =>
                {
                    builder.RegisterInstance(settings)
                    .As <BrokerSettings>()
                    .SingleInstance();

                    builder.RegisterInstance(broker)
                    .As <IMessageBroker>()
                    .SingleInstance();
                };
            });

            return(new ContainerTest((AppContainer)container));
        }
Beispiel #23
0
        public CommandThread(MeterDto meterDto, ClientSettings clientSettings, BrokerSettings brokerSettings,
                             IMqttClientConfiguration mqttClientConfiguration, IMqttClientMethods mqttClientMethods, Topic topic,
                             IServiceProvider serviceProvider, CommandRules commandRules)
        {
            MeterDto           = meterDto;
            _mutex             = new Semaphore(0, 10000);
            _answeredSemaphore = new Semaphore(1, 1);
            _commandQueue      = new ConcurrentQueue <Command>();
            _serviceProvider   = serviceProvider;
            _commandRules      = commandRules;


            clientSettings.ClientId   = clientSettings.ClientId.Replace("serial", meterDto.Serial);
            clientSettings.ClientName = clientSettings.ClientName.Replace("serial", meterDto.Serial);
            topic.Address             = topic.Address.Replace("{smc-or-meter}", "meter").Replace("{serial}", meterDto.Serial);
            _mqttClient = new IoGMqttClient(clientSettings, brokerSettings, mqttClientConfiguration, mqttClientMethods);
            _mqttClient.Subscribe(topic);
            _mqttClient.MessageReceivedHandler += ReceivedCommandAnswer;
        }
        private IDictionary <string, BrokerConnection> GetConnections(BrokerSettings settings)
        {
            if (settings.Connections == null)
            {
                return(new Dictionary <string, BrokerConnection>());
            }

            IEnumerable <string> duplicateBrokerNames = settings.Connections
                                                        .WhereDuplicated(c => c.BrokerName);

            if (duplicateBrokerNames.Any())
            {
                throw new BrokerException(
                          $"The following broker names are specified more than " +
                          $"once: {String.Join(", ", duplicateBrokerNames)}.");
            }

            return(settings.Connections
                   .Select(s => new BrokerConnection(s))
                   .ToDictionary(c => c.Settings.BrokerName));
        }
        public static void AddMassTransitWithRabbitMq(this IServiceCollection services, IConfiguration configuration)
        {
            BankDepositSaga = configuration.GetSection("SagasSettings").GetSection("BankDepositSaga").GetChildren()
                              .Select(item => new KeyValuePair <string, string>(item.Key, item.Value))
                              .ToDictionary(x => x.Key, x => x.Value);

            var brokerSettings = new BrokerSettings();

            configuration.GetSection("BrokerSettings").Bind(brokerSettings);

            services.AddSingleton <BankDepositTransactionStateMachine>();
            services.AddSingleton <ISagaRepository <BankDepositTransactionSaga>, InMemorySagaRepository <BankDepositTransactionSaga> >();

            services.AddMassTransit(configure =>
            {
                configure.AddSaga <BankDepositTransactionSaga>();
                configure.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(configureBus =>
                {
                    var host = configureBus.Host(new Uri(brokerSettings.Host), configureHost =>
                    {
                        configureHost.Username(brokerSettings.User);
                        configureHost.Password(brokerSettings.Password);
                    });

                    configureBus.ReceiveEndpoint(host, brokerSettings.InputQueue, configureEndpoint =>
                    {
                        var machine    = provider.GetService <BankDepositTransactionStateMachine>();
                        var repository = provider.GetService <ISagaRepository <BankDepositTransactionSaga> >();

                        configureEndpoint.StateMachineSaga(machine, repository);
                    });

                    //configureBus.UseInMemoryOutbox();
                    configureBus.UseSerilog();
                    //configureBus.MessageTopology.SetEntityNameFormatter(new CustomEntityFormatter("bankdeposit"));
                }));
            });

            services.AddMassTransitHostedService();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="messageHub">Message hub.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        /// <param name="deviceRepository">Device repository.</param>
        /// <param name="stateCache">State cache,</param>
        public MqttService(
            ILogger <MqttService> logger,
            IMessageHub messageHub,
            BrokerSettings brokerSettings,
            IGoogleDeviceRepository deviceRepository,
            StateCache stateCache)
            : base(logger, brokerSettings, "google/home")
        {
            _log              = logger ?? throw new ArgumentException(nameof(logger));
            _messageHub       = messageHub ?? throw new ArgumentException(nameof(messageHub));
            _deviceRepository = deviceRepository ?? throw new ArgumentException(nameof(deviceRepository));
            _stateCache       = stateCache ?? throw new ArgumentException(nameof(stateCache));

            // Subscribe to google home based topics
            SubscribedTopics.Add(TopicRoot + "/#");

            // Subscribe to all monitored state topics
            foreach (var topic in _stateCache.Keys)
            {
                SubscribedTopics.Add(topic);
            }
        }
Beispiel #27
0
        public void ExchangesDecared_RabbitMqPublisher_MustBeRegistered()
        {
            var settings     = new BrokerSettings();
            var mockExchange = new Mock <IMessageBroker>();

            ModuleTest.Arrange(config =>
            {
                config.AddPlugin <MockAppHostPlugin>()
                .AddPluginType <MockDirectExchange>();
            })
            .Test(c =>
            {
                AddTestMocks(c, settings, mockExchange.Object);
                c.Build().Start();
            },
                  (c, e) =>
            {
                c.GetTestLogger()
                .HasSingleEntryFor(RabbitMqLogEvents.BROKER_CONFIGURATION, LogLevel.Warning)
                .Should().BeTrue();
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TiVoMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="tivoClient">TiVo client.</param>
        /// <param name="tivoName">TiVo name.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public TiVoMqttService(
            ILogger <TiVoMqttService> logger,
            IClient tivoClient,
            string tivoName,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "tivo/" + tivoName)
        {
            _log = logger;
            SubscribedTopics.Add(TopicRoot + "/controls/+/set");

            _client = tivoClient;
            _client.EventReceived += TiVo_EventReceived;

            // TiVo client logging
            _client.MessageSent     += (object sender, MessageSentEventArgs e) => { _log.LogInformation("TiVo Message sent: " + e.Message); };
            _client.MessageReceived += (object sender, MessageReceivedEventArgs e) => { _log.LogInformation("TiVo Message received: " + e.Message); };
            _client.Error           += (object sender, System.IO.ErrorEventArgs e) =>
            {
                var exception = e.GetException();
                _log.LogError(exception, exception.Message);
                System.Environment.Exit(1);
            };
        }
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            var typeFinder = new WebAppTypeFinder();

            container.RegisterInstance <ITypeFinder>(typeFinder);

            // Exclude FS-Dependencies if Broker-Path is not set
            if (!BrokerSettings.IsValid())
            {
                typeFinder.AssemblySkipLoadingPattern += "|NVShop.Data.FS|NVShop.Data.eNVenta";
            }

            var types = typeFinder.FindClassesOfType <IDependencyRegistrar>();

            var instances = types.Select(Activator.CreateInstance)
                            .Cast <IDependencyRegistrar>()
                            .OrderBy(t => t.Order)
                            .ToList();

            foreach (var instance in instances)
            {
                instance.Register(container);
            }
        }
        // Creates the message broker that initializes the exchanges and
        // determines the queues that should be created.
        public override void StartModule(IContainer container, ILifetimeScope scope)
        {
            _brokerSettings   = GetBrokerSettings(scope);
            _connManager      = CreateConnectionManager();
            _messageBroker    = scope.Resolve <IMessageBroker>();
            _messageConsumers = GetQueueConsumers(scope);

            InitializeExchanges(_brokerSettings);

            _messageBroker.Initialize(new MessageBrokerState
            {
                ConnectionMgr    = _connManager,
                SerializationMgr = CreateSerializationManager(),

                BrokerSettings = _brokerSettings,
                Exchanges      = Exchanges,
                RpcTypes       = GetRpcCommandTypes()
            });

            _messageBroker.ConfigurePublishers();
            _messageBroker.BindConsumers(_messageConsumers);

            SaveExchangeMetadata(scope);
        }