Exemple #1
0
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transactionMode)
    {
        settings.Set("Transport.ConnectionString", Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString"));
        var connectionString = settings.Get <string>("Transport.ConnectionString");

        settings.Set <Conventions>(new Conventions());
        settings.Set(WellKnownConfigurationKeys.Core.MainSerializerSettingsKey, Tuple.Create <SerializationDefinition, SettingsHolder>(new XmlSerializer(), settings));
        settings.Set("NServiceBus.SharedQueue", settings.Get("NServiceBus.Routing.EndpointName"));
        var topologyName = Environment.GetEnvironmentVariable("AzureServiceBusTransport.Topology", EnvironmentVariableTarget.User);

        topologyName = topologyName ?? Environment.GetEnvironmentVariable("AzureServiceBusTransport.Topology");

        var transportExtension = new TransportExtensions <AzureServiceBusTransport>(settings);

        if (topologyName == "ForwardingTopology")
        {
            transportExtension.UseForwardingTopology();
        }
        else
        {
            transportExtension.UseEndpointOrientedTopology();
        }

        var transport      = new AzureServiceBusTransport();
        var infrastructure = transport.Initialize(settings, connectionString);

        return(new TransportConfigurationResult
        {
            PurgeInputQueueOnStartup = false,
            TransportInfrastructure = infrastructure
        });
    }
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transactionMode)
    {
        settings.Set("Transport.ConnectionString", Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString"));
        var connectionString = settings.Get <string>("Transport.ConnectionString");

        settings.Set <Conventions>(new Conventions());
        settings.Set("NServiceBus.SharedQueue", settings.Get("NServiceBus.Routing.EndpointName"));
        var topologyName = Environment.GetEnvironmentVariable("AzureServiceBusTransport.Topology", EnvironmentVariableTarget.User);

        topologyName = topologyName ?? Environment.GetEnvironmentVariable("AzureServiceBusTransport.Topology");

        if (topologyName == "ForwardingTopology")
        {
#pragma warning disable 618
            settings.Set <ITopology>(new ForwardingTopology());
#pragma warning restore 618
        }
        else
        {
#pragma warning disable 618
            settings.Set <ITopology>(new EndpointOrientedTopology());
#pragma warning restore 618
        }

        var transport      = new AzureServiceBusTransport();
        var infrastructure = transport.Initialize(settings, connectionString);

        return(new TransportConfigurationResult()
        {
            PurgeInputQueueOnStartup = false,
            TransportInfrastructure = infrastructure
        });
    }
        public TopologySection DetermineSendDestination(string destination)
        {
            return(sendDestinations.GetOrAdd(destination, d =>
            {
                var partitioningStrategy = (INamespacePartitioningStrategy)container.Resolve(typeof(INamespacePartitioningStrategy));
                var addressingLogic = (AddressingLogic)container.Resolve(typeof(AddressingLogic));
                var defaultAlias = settings.Get <string>(WellKnownConfigurationKeys.Topology.Addressing.DefaultNamespaceAlias);

                var inputQueueAddress = addressingLogic.Apply(d, EntityType.Queue);

                RuntimeNamespaceInfo[] namespaces = null;
                if (inputQueueAddress.HasSuffix && inputQueueAddress.Suffix != defaultAlias) // sending to specific namespace
                {
                    if (inputQueueAddress.HasConnectionString)
                    {
                        namespaces = new[]
                        {
                            new RuntimeNamespaceInfo(inputQueueAddress.Suffix, inputQueueAddress.Suffix, NamespacePurpose.Routing, NamespaceMode.Active)
                        };
                    }
                    else
                    {
                        NamespaceConfigurations configuredNamespaces;
                        if (settings.TryGet(WellKnownConfigurationKeys.Topology.Addressing.Namespaces, out configuredNamespaces))
                        {
                            var configured = configuredNamespaces.FirstOrDefault(n => n.Alias == inputQueueAddress.Suffix);
                            if (configured != null)
                            {
                                namespaces = new[]
                                {
                                    new RuntimeNamespaceInfo(configured.Alias, configured.ConnectionString, configured.Purpose, NamespaceMode.Active)
                                };
                            }
                        }
                    }
                }
                else // sending to the partition
                {
                    namespaces = partitioningStrategy.GetNamespaces(PartitioningIntent.Sending).ToArray();
                }

                if (namespaces == null)
                {
                    throw new Exception($"Could not determine namespace for destination `{d}`.");
                }
                var inputQueues = namespaces.Select(n => new EntityInfo
                {
                    Path = inputQueueAddress.Name,
                    Type = EntityType.Queue,
                    Namespace = n
                }).ToArray();

                return new TopologySection
                {
                    Namespaces = namespaces,
                    Entities = inputQueues
                };
            }));
        }
        public void Should_be_able_to_set_subscription_description_factory_method()
        {
            Action <SubscriptionDescription> registeredFactory = sd => { };

            extensions.Subscriptions().DescriptionCustomizer(registeredFactory);

            Assert.AreEqual(registeredFactory, settings.Get <TopologySettings>().SubscriptionSettings.DescriptionCustomizer);
        }
 static MessageReceiverNotifierSettings BuildMessageReceiverNotifierSettings(SettingsHolder settings)
 {
     // default values set by DefaultConfigurationValues.Apply - shouldn't hardcode those here, so OK to use settings
     return(new MessageReceiverNotifierSettings(
                ReceiveMode.PeekLock,
                settings.HasExplicitValue <TransportTransactionMode>() ? settings.Get <TransportTransactionMode>() : settings.SupportedTransactionMode(),
                settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.AutoRenewTimeout),
                settings.Get <int>(WellKnownConfigurationKeys.Connectivity.NumberOfClientsPerEntity)));
 }
        public void Should_configure_default_values()
        {
            var feature  = new InstanceMappingFileFeature();
            var settings = new SettingsHolder();

            feature.ConfigureDefaults(settings);

            Assert.That(settings.Get <string>(InstanceMappingFileFeature.FilePathSettingsKey), Is.EqualTo("instance-mapping.xml"));
            Assert.That(settings.Get <TimeSpan>(InstanceMappingFileFeature.CheckIntervalSettingsKey), Is.EqualTo(TimeSpan.FromSeconds(30)));
        }
        public void Should_configure_default_values()
        {
            var feature = new InstanceMappingFileFeature();
            var settings = new SettingsHolder();

            feature.ConfigureDefaults(settings);

            Assert.That(settings.Get<string>(InstanceMappingFileFeature.FilePathSettingsKey), Is.EqualTo("instance-mapping.xml"));
            Assert.That(settings.Get<TimeSpan>(InstanceMappingFileFeature.CheckIntervalSettingsKey), Is.EqualTo(TimeSpan.FromSeconds(30)));
        }
        public ForwardingTopologySectionManager(SettingsHolder settings, ITransportPartsContainer container)
        {
            this.settings  = settings;
            this.container = container;

            namespaceBundleConfigurations = new Lazy <NamespaceBundleConfigurations>(() =>
            {
                var manageNamespaceManagerLifeCycle = container.Resolve <IManageNamespaceManagerLifeCycle>();
                var namespaceConfigurations         = settings.Get <NamespaceConfigurations>(WellKnownConfigurationKeys.Topology.Addressing.Namespaces);
                var bundlePrefix         = settings.Get <string>(WellKnownConfigurationKeys.Topology.Bundling.BundlePrefix);
                var bundleConfigurations = NumberOfTopicsInBundleCheck.Run(manageNamespaceManagerLifeCycle, namespaceConfigurations, bundlePrefix).GetAwaiter().GetResult();
                return(bundleConfigurations);
            });
        }
        public void Run(SettingsHolder settings)
        {
            List <EnabledPersistence> definitions;

            if (!settings.TryGet("PersistenceDefinitions", out definitions))
            {
                if (settings.Get <bool>("Endpoint.SendOnly"))
                {
                    return;
                }

                throw new Exception(errorMessage);
            }

            var enabledPersistences = PersistenceStorageMerger.Merge(definitions, settings);

            var resultingSupportedStorages = new List <Type>();

            foreach (var definition in enabledPersistences)
            {
                var persistenceDefinition = definition.DefinitionType.Construct <PersistenceDefinition>();

                persistenceDefinition.ApplyDefaults(settings);

                foreach (var storageType in definition.SelectedStorages)
                {
                    Logger.DebugFormat("Activating persistence '{0}' to provide storage for '{1}' storage.", definition.DefinitionType.Name, storageType);
                    persistenceDefinition.ApplyActionForStorage(storageType, settings);
                    resultingSupportedStorages.Add(storageType);
                }
            }

            settings.Set("ResultingSupportedStorages", resultingSupportedStorages);
        }
        public override void Initialize()
        {
            var connectionString        = SettingsHolder.Get <string>("NServiceBus.Transport.ConnectionString");
            var connectionConfiguration = new ConnectionStringParser().Parse(connectionString);

            NServiceBus.Configure.Instance.Configurer.RegisterSingleton <IConnectionConfiguration>(connectionConfiguration);
            NServiceBus.Configure.Component <DefaultConnectionManager>(DependencyLifecycle.SingleInstance);

            NServiceBus.Configure.Component <EventSourcedUnitOfWork>(DependencyLifecycle.InstancePerUnitOfWork)
            .ConfigureProperty(p => p.EndpointAddress, Address.Local);
            NServiceBus.Configure.Component <TransactionalUnitOfWork>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.EndpointAddress, Address.Local);

            NServiceBus.Configure.Component <MessageSender>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.EndpointAddress, Address.Local);
            NServiceBus.Configure.Component <MessagePublisher>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.EndpointAddress, Address.Local);

            NServiceBus.Configure.Component <TransactionalModeRouterProjectionCreator>(DependencyLifecycle.InstancePerCall);
            NServiceBus.Configure.Component <EventSourcedModeRouterProjectionCreator>(DependencyLifecycle.InstancePerCall);
            NServiceBus.Configure.Component <ReceiverSinkProjectionCreator>(DependencyLifecycle.InstancePerCall);
            NServiceBus.Configure.Component <CompositeQueueCreator>(DependencyLifecycle.InstancePerCall);

            NServiceBus.Configure.Component <DequeueStrategy>(DependencyLifecycle.InstancePerCall);
            NServiceBus.Configure.Component <SubscriptionManager>(DependencyLifecycle.SingleInstance)
            .ConfigureProperty(p => p.EndpointAddress, Address.Local);

            InfrastructureServices.Enable <IManageEventStoreConnections>();

            Features.Categories.Serializers.SetDefault <JsonNoBomSerialization>();
        }
        public override void Initialize()
        {
            if (!SettingsHolder.GetOrDefault <bool>("ScaleOut.UseSingleBrokerQueue"))
            {
                Address.InitializeLocalAddress(Address.Local.Queue + "." + Address.Local.Machine);
            }

            var connectionString        = SettingsHolder.Get <string>("NServiceBus.Transport.ConnectionString");
            var connectionConfiguration = new ConnectionStringParser().Parse(connectionString);

            NServiceBus.Configure.Instance.Configurer.RegisterSingleton <IConnectionConfiguration>(connectionConfiguration);

            NServiceBus.Configure.Component <RabbitMqDequeueStrategy>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.PurgeOnStartup, ConfigurePurging.PurgeRequested)
            .ConfigureProperty(p => p.PrefetchCount, connectionConfiguration.PrefetchCount);

            NServiceBus.Configure.Component <RabbitMqUnitOfWork>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.UsePublisherConfirms, connectionConfiguration.UsePublisherConfirms)
            .ConfigureProperty(p => p.MaxWaitTimeForConfirms, connectionConfiguration.MaxWaitTimeForConfirms);


            NServiceBus.Configure.Component <RabbitMqMessageSender>(DependencyLifecycle.InstancePerCall);

            NServiceBus.Configure.Component <RabbitMqMessagePublisher>(DependencyLifecycle.InstancePerCall);

            NServiceBus.Configure.Component <RabbitMqSubscriptionManager>(DependencyLifecycle.SingleInstance)
            .ConfigureProperty(p => p.EndpointQueueName, Address.Local.Queue);

            NServiceBus.Configure.Component <RabbitMqQueueCreator>(DependencyLifecycle.InstancePerCall);

            InfrastructureServices.Enable <IRoutingTopology>();
            InfrastructureServices.Enable <IManageRabbitMqConnections>();
        }
Exemple #12
0
        public IConnection GetPooledConnection()
        {
            if (connection != null)
            {
                return(connection);
            }

            lock (lockObj)
            {
                if (connection != null)
                {
                    return(connection);
                }

                connection          = connectionFactory.CreateConnection();
                connection.ClientID = ClientId();

                if (!SettingsHolder.Get <bool>("Endpoint.SendOnly"))
                {
                    connection.Start();
                }
            }

            return(connection);
        }
Exemple #13
0
        /// <summary>
        /// Enables the given infrastructure service by registering it in the container
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void Enable <T>()
        {
            var serviceType = typeof(T);

            if (Configure.Instance.Configurer.HasComponent <T>())
            {
                Logger.InfoFormat("Infrastructure service {0} was found in the container and will be used instead of the default", serviceType.FullName);
                SetStatusToEnabled(serviceType);

                //todo: We should guide users to register their infrastructure overrides in a more explicit way in the future
                return;
            }

            if (!SettingsHolder.HasSetting <T>())
            {
                throw new ConfigurationErrorsException(string.Format("No explicit settings or default found for service {0}, please configure one explicitly", serviceType.FullName));
            }

            var configAction = SettingsHolder.Get <Action>(serviceType.FullName);

            configAction();

            SetStatusToEnabled(serviceType);

            Logger.DebugFormat("Infrastructure service {0} has been configured", serviceType.FullName);
        }
Exemple #14
0
        public override void Initialize()
        {
            NServiceBus.Configure.Component <CorrelationIdMutatorForBackwardsCompatibilityWithV3>(DependencyLifecycle.InstancePerCall);
            NServiceBus.Configure.Component <MsmqUnitOfWork>(DependencyLifecycle.SingleInstance);
            NServiceBus.Configure.Component <MsmqDequeueStrategy>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.PurgeOnStartup, ConfigurePurging.PurgeRequested);

            var cfg = NServiceBus.Configure.GetConfigSection <MsmqMessageQueueConfig>();

            var settings = new MsmqSettings();

            if (cfg != null)
            {
                settings.UseJournalQueue    = cfg.UseJournalQueue;
                settings.UseDeadLetterQueue = cfg.UseDeadLetterQueue;

                Logger.Warn(Message);
            }
            else
            {
                var connectionString = SettingsHolder.Get <string>("NServiceBus.Transport.ConnectionString");

                if (connectionString != null)
                {
                    settings = new MsmqConnectionStringBuilder(connectionString).RetrieveSettings();
                }
            }

            NServiceBus.Configure.Component <MsmqMessageSender>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(t => t.Settings, settings);

            NServiceBus.Configure.Component <MsmqQueueCreator>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(t => t.Settings, settings);
        }
Exemple #15
0
        /// <summary>
        /// Performs the installation providing permission for the given user.
        /// </summary>
        /// <param name="identity">The user for under which the queue will be created.</param>
        public void Install(string identity)
        {
            if (SettingsHolder.Get <bool>("Endpoint.SendOnly"))
            {
                return;
            }

            if (ConfigureQueueCreation.DontCreateQueues)
            {
                return;
            }

            var wantQueueCreatedInstances = Configure.Instance.Builder.BuildAll <IWantQueueCreated>().ToList();

            foreach (var wantQueueCreatedInstance in wantQueueCreatedInstances.Where(wantQueueCreatedInstance => !wantQueueCreatedInstance.IsDisabled))
            {
                if (wantQueueCreatedInstance.Address == null)
                {
                    throw new InvalidOperationException(string.Format("IWantQueueCreated implementation {0} returned a null address", wantQueueCreatedInstance.GetType().FullName));
                }

                QueueCreator.CreateQueueIfNecessary(wantQueueCreatedInstance.Address, identity);
                Logger.DebugFormat("Verified that the queue: [{0}] existed", wantQueueCreatedInstance.Address);
            }
        }
Exemple #16
0
        public void FinalizeConfiguration()
        {
            NServiceBus.Configure.Component <MessageProcessor>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.PurgeOnStartup, ConfigurePurging.PurgeRequested);

            if (!SettingsHolder.Get <bool>("Transactions.Enabled"))
            {
                NServiceBus.Configure.Component <ActiveMQMessageDefer>(DependencyLifecycle.InstancePerCall);
                NServiceBus.Configure.Component <ActiveMqSchedulerManagement>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(p => p.Disabled, false);
                NServiceBus.Configure.Component <ActiveMqSchedulerManagementJobProcessor>(DependencyLifecycle.SingleInstance);
                NServiceBus.Configure.Component <ActiveMqSchedulerManagementCommands>(DependencyLifecycle.SingleInstance);

                RegisterNoneTransactionSessionFactory(connectionConfiguration[UriKey]);
            }
            else
            {
                var transportConfig = NServiceBus.Configure.GetConfigSection <TransportConfig>();

                if (SettingsHolder.Get <bool>("Transactions.SuppressDistributedTransactions"))
                {
                    RegisterActiveMQManagedTransactionSessionFactory(transportConfig, connectionConfiguration[UriKey]);
                }
                else
                {
                    RegisterDTCManagedTransactionSessionFactory(transportConfig, connectionConfiguration);
                }
            }
        }
        void ConfigureMessageRegistry(List <Type> knownMessages)
        {
            var messageRegistry = new MessageMetadataRegistry
            {
                DefaultToNonPersistentMessages = !SettingsHolder.Get <bool>("Endpoint.DurableMessages")
            };

            knownMessages.ForEach(messageRegistry.RegisterMessageType);

            Configure.Instance.Configurer.RegisterSingleton <MessageMetadataRegistry>(messageRegistry);
            Configure.Instance.Configurer.ConfigureComponent <LogicalMessageFactory>(DependencyLifecycle.SingleInstance);

            if (!Logger.IsInfoEnabled)
            {
                return;
            }

            var messageDefinitions = messageRegistry.GetAllMessages().ToList();

            Logger.InfoFormat("Number of messages found: {0}", messageDefinitions.Count());

            if (!Logger.IsDebugEnabled)
            {
                return;
            }

            Logger.DebugFormat("Message definitions: \n {0}",
                               string.Concat(messageDefinitions.Select(md => md.ToString() + "\n")));
        }
Exemple #18
0
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transactionMode)
    {
        var result    = new TransportConfigurationResult();
        var transport = new RabbitMQTransport();

        var connectionString = Environment.GetEnvironmentVariable("RabbitMQTransport_ConnectionString");

        if (string.IsNullOrEmpty(connectionString))
        {
            throw new Exception("The 'RabbitMQTransport_ConnectionString' environment variable is not set.");
        }

        connectionStringBuilder = new DbConnectionStringBuilder {
            ConnectionString = connectionString
        };

        queueBindings = settings.Get <QueueBindings>();

        new TransportExtensions <RabbitMQTransport>(settings).UseConventionalRoutingTopology();
        result.TransportInfrastructure  = transport.Initialize(settings, connectionStringBuilder.ConnectionString);
        isTransportInitialized          = true;
        result.PurgeInputQueueOnStartup = true;

        transportTransactionMode = result.TransportInfrastructure.TransactionMode;
        requestedTransactionMode = transactionMode;

        //work around for TransportTests not calling Start
        result.TransportInfrastructure.Start();

        return(result);
    }
Exemple #19
0
        public override void Initialize()
        {
            OracleAQTransport.CustomizeAddress();

            string defaultConnectionString = SettingsHolder.Get <string>("NServiceBus.Transport.ConnectionString");

            var collection = ConfigurationManager
                             .ConnectionStrings
                             .Cast <ConnectionStringSettings>()
                             .Where(x => x.Name.StartsWith("NServiceBus/Transport/"))
                             .ToDictionary(x => x.Name.Replace("NServiceBus/Transport/", string.Empty), y => y.ConnectionString);

            if (string.IsNullOrEmpty(defaultConnectionString))
            {
                throw new ArgumentException("OracleAQ Transport connection string cannot be empty or null");
            }

            NServiceBus.Configure.Component <DefaultQueueNamePolicy>(DependencyLifecycle.SingleInstance);

            NServiceBus.Configure.Component <OracleAQPurger>(DependencyLifecycle.SingleInstance)
            .ConfigureProperty(p => p.ConnectionString, defaultConnectionString);

            NServiceBus.Configure.Component <OracleAQQueueCreator>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.ConnectionString, defaultConnectionString);

            NServiceBus.Configure.Component <OracleAQMessageSender>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.DefaultConnectionString, defaultConnectionString)
            .ConfigureProperty(p => p.ConnectionStringCollection, collection);

            NServiceBus.Configure.Component <OracleAQDequeueStrategy>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.ConnectionString, defaultConnectionString)
            .ConfigureProperty(p => p.PurgeOnStartup, ConfigurePurging.PurgeRequested);
        }
        public void Should_default_to_msmq_if_no_other_transport_is_configured()
        {
            var handler = new DefaultTransportForHost();

            handler.Run();

            Assert.True(SettingsHolder.Get <TransportDefinition>("NServiceBus.Transport.SelectedTransport") is Msmq);
        }
        public void Should_set_DeliveryCount_for_subscriptions_to_10_attempts_for_no_immediate_retries_configured()
        {
            var settingsHolder = new SettingsHolder();

            new DefaultConfigurationValues().Apply(settingsHolder);

            Assert.That(settingsHolder.Get <int>(WellKnownConfigurationKeys.Topology.Resources.Subscriptions.MaxDeliveryCount), Is.EqualTo(10));
        }
 public TransactionSettings()
 {
     MaxRetries                     = 5;
     IsTransactional                = SettingsHolder.Get <bool>("Transactions.Enabled");
     TransactionTimeout             = SettingsHolder.Get <TimeSpan>("Transactions.DefaultTimeout");
     IsolationLevel                 = SettingsHolder.Get <IsolationLevel>("Transactions.IsolationLevel");
     DontUseDistributedTransactions = SettingsHolder.Get <bool>("Transactions.SuppressDistributedTransactions");
     DoNotWrapHandlersExecutionInATransactionScope = SettingsHolder.Get <bool>("Transactions.DoNotWrapHandlersExecutionInATransactionScope");
 }
Exemple #23
0
        public void CreateQueueIfNecessary(Address address, string account)
        {
            var durable = SettingsHolder.Get <bool>("Endpoint.DurableMessages");

            using (var channel = ConnectionManager.GetConnection(ConnectionPurpose.Administration).CreateModel())
            {
                channel.QueueDeclare(address.Queue, durable, false, false, null);
            }
        }
        public void Should_be_able_to_set_the_brokered_message_body_type()
        {
            var settings   = new SettingsHolder();
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.BrokeredMessageBodyType(SupportedBrokeredMessageBodyTypes.Stream);

            Assert.AreEqual(SupportedBrokeredMessageBodyTypes.Stream, settings.Get <SupportedBrokeredMessageBodyTypes>(WellKnownConfigurationKeys.Serialization.BrokeredMessageBodyType));
        }
        protected AzureServiceBusTransportInfrastructure(SettingsHolder settings)
        {
            TransactionMode  = settings.SupportedTransactionMode();
            Settings         = settings;
            TopologySettings = settings.GetOrCreate <TopologySettings>();

            var individualizationStrategyType = (Type)Settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Individualization.Strategy);

            individualization = individualizationStrategyType.CreateInstance <IIndividualizationStrategy>(Settings);

            var compositionStrategyType = (Type)Settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Composition.Strategy);
            var compositionStrategy     = compositionStrategyType.CreateInstance <ICompositionStrategy>(Settings);

            var sanitizationStrategyType = (Type)Settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Sanitization.Strategy);
            var sanitizationStrategy     = sanitizationStrategyType.CreateInstance <ISanitizationStrategy>(Settings);

            addressingLogic = new AddressingLogic(sanitizationStrategy, compositionStrategy);
        }
        public void Should_be_able_to_set_whether_send_via_receive_queue_should_be_used()
        {
            var settings   = new SettingsHolder();
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.SendViaReceiveQueue(false);

            Assert.AreEqual(false, settings.Get <bool>(WellKnownConfigurationKeys.Connectivity.SendViaReceiveQueue));
        }
        public void Merge_ShouldMergeContentFromSource()
        {
            var settings = new SettingsHolder();
            settings.SetDefault("SomeDefaultSetting", "Value1");
            settings.Set("SomeSetting", "Value1");

            var mergeFrom = new SettingsHolder();
            mergeFrom.SetDefault("SomeDefaultSettingThatGetsMerged", "Value1");
            mergeFrom.Set("SomeSettingThatGetsMerged", "Value1");

            settings.Merge(mergeFrom);

            var result1 = settings.Get<string>("SomeDefaultSettingThatGetsMerged");
            var result2 = settings.Get<string>("SomeSettingThatGetsMerged");

            Assert.AreEqual("Value1", result1);
            Assert.AreEqual("Value1", result2);
        }
        public void Should_be_able_to_set_number_of_clients_per_entity()
        {
            var settings   = new SettingsHolder();
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

            extensions.NumberOfClientsPerEntity(4);

            Assert.AreEqual(4, settings.Get <int>(WellKnownConfigurationKeys.Connectivity.NumberOfClientsPerEntity));
        }
        void InitializeContainer(SettingsHolder settings)
        {
            // runtime components
            container.Register <ReadOnlySettings>(() => settings);
            container.Register <ITopologySectionManager>(() => topologySectionManager);
            container.RegisterSingleton <NamespaceManagerCreator>();
            container.RegisterSingleton <NamespaceManagerLifeCycleManager>();
            container.RegisterSingleton <MessagingFactoryCreator>();
            container.RegisterSingleton <MessagingFactoryLifeCycleManager>();
            container.RegisterSingleton <MessageReceiverCreator>();
            container.RegisterSingleton <MessageReceiverLifeCycleManager>();
            container.RegisterSingleton <MessageSenderCreator>();
            container.RegisterSingleton <MessageSenderLifeCycleManager>();
            container.RegisterSingleton <AzureServiceBusQueueCreator>();
            container.RegisterSingleton <AzureServiceBusTopicCreator>();
            container.RegisterSingleton <AzureServiceBusForwardingSubscriptionCreator>();

            container.RegisterSingleton <DefaultConnectionStringToNamespaceAliasMapper>();

            var brokeredMessagesToIncomingMessagesConverterType = settings.Get <Type>(WellKnownConfigurationKeys.BrokeredMessageConventions.ToIncomingMessageConverter);

            container.Register(brokeredMessagesToIncomingMessagesConverterType);
            var batchedOperationsToBrokeredMessagesConverterType = settings.Get <Type>(WellKnownConfigurationKeys.BrokeredMessageConventions.FromOutgoingMessageConverter);

            container.Register(batchedOperationsToBrokeredMessagesConverterType);

            container.Register <TopologyCreator>();
            container.Register <Batcher>();

            var oversizedMessageHandler = (IHandleOversizedBrokeredMessages)settings.Get(WellKnownConfigurationKeys.Connectivity.MessageSenders.OversizedBrokeredMessageHandlerInstance);

            container.Register <IHandleOversizedBrokeredMessages>(() => oversizedMessageHandler);

            container.RegisterSingleton <DefaultOutgoingBatchRouter>();
            container.RegisterSingleton <TopologyOperator>();
            container.Register <MessageReceiverNotifier>();
            container.RegisterSingleton <SubscriptionManager>();
            container.RegisterSingleton <TransportResourcesCreator>();
            container.RegisterSingleton <Dispatcher>();
            container.Register <MessagePump>();

            container.Register <AddressingLogic>();

            var compositionStrategyType = (Type)settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Composition.Strategy);

            container.Register(compositionStrategyType);

            var individualizationStrategyType = (Type)settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Individualization.Strategy);

            container.Register(individualizationStrategyType);

            var partitioningStrategyType = (Type)settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Partitioning.Strategy);

            container.Register(partitioningStrategyType);

            var sanitizationStrategyType = (Type)settings.Get(WellKnownConfigurationKeys.Topology.Addressing.Sanitization.Strategy);

            container.Register(sanitizationStrategyType);
        }
        public void Should_be_able_to_set_custom_converter()
        {
            var settings   = new SettingsHolder();
            var extensions = new TransportExtensions <AzureServiceBusTransport>(settings);

#pragma warning disable 618
            extensions.UseBrokeredMessageToIncomingMessageConverter <ConvertBrokeredMessagesToIncomingMessages>();
#pragma warning restore 618
            Assert.AreEqual(typeof(ConvertBrokeredMessagesToIncomingMessages), settings.Get <Type>(WellKnownConfigurationKeys.BrokeredMessageConventions.ToIncomingMessageConverter));
        }
        /// <summary>
        /// Forward messages that have repeatedly failed to another endpoint.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static Configure MessageForwardingInCaseOfFault(this Configure config)
        {
            if (ErrorQueue != null)
            {
                return(config);
            }
            if (SettingsHolder.Get <bool>("Endpoint.SendOnly"))
            {
                return(config);
            }

            ErrorQueue = Address.Undefined;

            var section = Configure.GetConfigSection <MessageForwardingInCaseOfFaultConfig>();

            if (section != null)
            {
                if (string.IsNullOrWhiteSpace(section.ErrorQueue))
                {
                    throw new ConfigurationErrorsException(
                              "'MessageForwardingInCaseOfFaultConfig' configuration section is found but 'ErrorQueue' value is missing." +
                              "\n The following is an example for adding such a value to your app config: " +
                              "\n <MessageForwardingInCaseOfFaultConfig ErrorQueue=\"error\"/> \n");
                }

                Logger.Debug("Error queue retrieved from <MessageForwardingInCaseOfFaultConfig> element in config file.");

                ErrorQueue = Address.Parse(section.ErrorQueue);

                config.Configurer.ConfigureComponent <FaultManager>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(fm => fm.ErrorQueue, ErrorQueue);

                return(config);
            }


            var errorQueue = RegistryReader <string> .Read("ErrorQueue");

            if (!string.IsNullOrWhiteSpace(errorQueue))
            {
                Logger.Debug("Error queue retrieved from registry settings.");
                ErrorQueue = Address.Parse(errorQueue);

                config.Configurer.ConfigureComponent <FaultManager>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(fm => fm.ErrorQueue, ErrorQueue);
            }

            if (ErrorQueue == Address.Undefined)
            {
                throw new ConfigurationErrorsException("Faults forwarding requires an error queue to be specified. Please add a 'MessageForwardingInCaseOfFaultConfig' section to your app.config" +
                                                       "\n or configure a global one using the powershell command: Set-NServiceBusLocalMachineSettings -ErrorQueue {address of error queue}");
            }

            return(config);
        }
        public void Should_have_configured_storage_maxsize()
        {
            var settings            = new SettingsHolder();
            var persistenceSettings = new PersistenceExtensions <InMemoryPersistence>(settings);

#pragma warning disable 0618
            persistenceSettings.GatewayDeduplicationCacheSize(42);

            Assert.AreEqual(42, settings.Get <int>(InMemoryGatewayPersistence.MaxSizeKey));
#pragma warning restore 0618
        }
        public void Run(Configure config)
        {
            settingsHolder = config.Settings;
            var suppressDtc = settingsHolder.Get<bool>("Transactions.SuppressDistributedTransactions");
            if (IsTransportSupportingDtc() && !suppressDtc)
            {
                // there is no issue with the timeout persistence when using dtc
                return;
            }

            var timeoutPersister = TryResolveTimeoutPersister();
            if (timeoutPersister == null)
            {
                // no timeouts used
                return;
            }

            if (!(timeoutPersister is IPersistTimeoutsV2) && !UserSuppressedTimeoutPersistenceWarning())
            {
                throw new Exception("You are using an outdated timeout persistence which can lead to message loss! Please update the configured timeout persistence. You can suppress this warning by configuring your bus using 'config.SuppressOutdatedTimeoutPersistenceWarning()' or by adding 'NServiceBus/suppress-outdated-timeout-persistence-warning' with value 'true' to the appSettings section of your application configuration file.");
            }
        }