/// <summary>
        /// Provides a factory method for building a message serializer.
        /// </summary>
        public override Func<IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
        {
            return mapper =>
            {
                var conventions = settings.Get<Conventions>();
                var serializer = new XmlMessageSerializer(mapper, conventions);

                string customNamespace;
                if (settings.TryGet(CustomNamespaceConfigurationKey, out customNamespace))
                {
                    serializer.Namespace = customNamespace;
                }

                bool skipWrappingRawXml;
                if (settings.TryGet(SkipWrappingRawXml, out skipWrappingRawXml))
                {
                    serializer.SkipWrappingRawXml = skipWrappingRawXml;
                }

                bool sanitizeInput;
                if (settings.TryGet(SanitizeInput, out sanitizeInput))
                {
                    serializer.SanitizeInput = sanitizeInput;
                }

                var registry = settings.Get<MessageMetadataRegistry>();
                var messageTypes = registry.GetAllMessages().Select(m => m.MessageType);

                serializer.Initialize(messageTypes);
                return serializer;
            };
        }
        public static void ApplyContext(this Activity activity, ReadOnlySettings settings,
                                        IReadOnlyDictionary <string, string> contextHeaders)
        {
            var transportDefinition = settings.Get <TransportDefinition>();

            activity.AddTag("messaging.system", transportDefinition.GetType().Name.Replace("Transport", null).ToLowerInvariant());
            activity.AddTag("messaging.destination", settings.LogicalAddress().ToString());
            if (contextHeaders.TryGetValue(Headers.ConversationId, out var conversationId))
            {
                activity.AddTag("messaging.conversation_id", conversationId);
            }

            if (contextHeaders.TryGetValue(Headers.MessageIntent, out var intent) &&
                Enum.TryParse <MessageIntentEnum>(intent, out var intentValue))
            {
                var routingPolicy = settings.Get <TransportInfrastructure>().OutboundRoutingPolicy;

                var kind = GetDestinationKind(intentValue, routingPolicy);

                if (kind != null)
                {
                    activity.AddTag("messaging.destination_kind", kind);
                }
            }

            foreach (var header in contextHeaders.Where(header => header.Key.StartsWith("NServiceBus.")))
            {
                activity.AddTag($"messaging.{header.Key.ToLowerInvariant()}", header.Value);
            }
        }
Exemple #3
0
        /// <summary>
        /// Provides a factory method for building a message serializer.
        /// </summary>
        public override Func <IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
        {
            return(mapper =>
            {
                var conventions = settings.Get <Conventions>();
                var serializer = new XmlMessageSerializer(mapper, conventions);

                string customNamespace;
                if (settings.TryGet(CustomNamespaceConfigurationKey, out customNamespace))
                {
                    serializer.Namespace = customNamespace;
                }

                bool skipWrappingRawXml;
                if (settings.TryGet(SkipWrappingRawXml, out skipWrappingRawXml))
                {
                    serializer.SkipWrappingRawXml = skipWrappingRawXml;
                }

                bool sanitizeInput;
                if (settings.TryGet(SanitizeInput, out sanitizeInput))
                {
                    serializer.SanitizeInput = sanitizeInput;
                }

                var registry = settings.Get <MessageMetadataRegistry>();
                var messageTypes = registry.GetAllMessages().Select(m => m.MessageType);

                serializer.Initialize(messageTypes);
                return serializer;
            });
        }
        public static void ApplyContext(this TelemetrySpan span, ReadOnlySettings settings,
                                        IReadOnlyDictionary <string, string> contextHeaders)
        {
            var transportDefinition = settings.Get <TransportDefinition>();

            span.SetAttribute("messaging.system", transportDefinition.GetType().Name.Replace("Transport", null).ToLowerInvariant());
            span.SetAttribute("messaging.destination", settings.LogicalAddress().ToString());
            if (contextHeaders.TryGetValue(Headers.ConversationId, out var conversationId))
            {
                span.SetAttribute("messaging.conversation_id", conversationId);
            }

            if (contextHeaders.TryGetValue(Headers.MessageIntent, out var intent) &&
                Enum.TryParse <MessageIntentEnum>(intent, out var intentValue))
            {
                var routingPolicy = settings.Get <TransportInfrastructure>().OutboundRoutingPolicy;

                var kind = GetDestinationKind(intentValue, routingPolicy);

                if (kind != null)
                {
                    span.SetAttribute("messaging.destination_kind", kind);
                }
            }
        }
            public HeartbeatStartup(IDispatchMessages messageDispatcher, ReadOnlySettings settings)
            {
                backend = new ServiceControlBackend(messageDispatcher, settings);
                endpointName = settings.EndpointName();
                HostId = settings.Get<Guid>("NServiceBus.HostInformation.HostId");
                Host = settings.Get<string>("NServiceBus.HostInformation.DisplayName");
                Properties = settings.Get<Dictionary<string, string>>("NServiceBus.HostInformation.Properties");

                var interval = ConfigurationManager.AppSettings["Heartbeat/Interval"];
                if (!string.IsNullOrEmpty(interval))
                {
                    heartbeatInterval = TimeSpan.Parse(interval);
                }
                else if (settings.HasSetting("ServiceControl.Heartbeat.Interval"))
                {
                    heartbeatInterval = settings.Get<TimeSpan>("ServiceControl.Heartbeat.Interval");
                }

                ttlTimeSpan = TimeSpan.FromTicks(heartbeatInterval.Ticks*4); // Default ttl

                var ttl = ConfigurationManager.AppSettings["Heartbeat/TTL"];
                if (!string.IsNullOrEmpty(ttl))
                {
                    ttlTimeSpan = TimeSpan.Parse(ttl);
                }
                else if (settings.HasSetting("ServiceControl.Heartbeat.Ttl"))
                {
                    ttlTimeSpan = settings.Get<TimeSpan>("ServiceControl.Heartbeat.Ttl");
                }
            }
Exemple #6
0
 public BatchedOperationsToBrokeredMessagesConverter(ReadOnlySettings settings)
 {
     useAliases = settings.Get <bool>(WellKnownConfigurationKeys.Topology.Addressing.UseNamespaceAliasesInsteadOfConnectionStrings);
     namespaceConfigurations = settings.Get <NamespaceConfigurations>(WellKnownConfigurationKeys.Topology.Addressing.Namespaces).Where(n => n.Purpose == NamespacePurpose.Partitioning).ToList();
     defaultAlias            = settings.Get <string>(WellKnownConfigurationKeys.Topology.Addressing.DefaultNamespaceAlias);
     configuredBodyType      = settings.Get <SupportedBrokeredMessageBodyTypes>(WellKnownConfigurationKeys.Serialization.BrokeredMessageBodyType);
 }
        static void RegisterConnectionStringAsNamespace(string connectionString, ReadOnlySettings settings)
        {
            var namespaces = settings.Get <NamespaceConfigurations>(WellKnownConfigurationKeys.Topology.Addressing.Namespaces);
            var alias      = settings.Get <string>(WellKnownConfigurationKeys.Topology.Addressing.DefaultNamespaceAlias);

            namespaces.Add(alias, connectionString, NamespacePurpose.Partitioning);
        }
        void ApplyConventions(ReadOnlySettings settings)
        {
            docStore.Conventions.FindTypeTagName = BackwardsCompatibilityHelper.LegacyFindTypeTagName;

            var store = docStore as DocumentStore;
            if (store == null)
            {
                return;
            }

            // Source: https://github.com/ravendb/ravendb/blob/f56963f23f54b5535eba4f043fb84d5145b11b1d/Raven.Client.Lightweight/Document/DocumentStore.cs#L129
            var ravenDefaultResourceManagerId = new Guid("e749baa6-6f76-4eef-a069-40a4378954f8");

            if (store.ResourceManagerId != ravenDefaultResourceManagerId)
            {
                Logger.Warn("Overriding user-specified documentStore.ResourceManagerId. It's no longer necessary to set this value while using NServiceBus.RavenDB persistence. Consider using busConfiguration.CustomizeDocumentStore(Action<IDocumentStore customize) if this is absolutely necessary, but it is not recommended.");
            }
            if (!(store.TransactionRecoveryStorage is VolatileOnlyTransactionRecoveryStorage))
            {
                Logger.Warn("Overriding user-specified documentStore.TransactionRecoveryStorage. It's no longer necessary to set this value while using NServiceBus.RavenDB persistence. Consider using busConfiguration.CustomizeDocumentStore(Action<IDocumentStore customize) if this is absolutely necessary, but it is not recommended.");
            }

            var resourceManagerId = settings.Get<string>("NServiceBus.LocalAddress") + "-" + settings.Get<string>("EndpointVersion");
            store.ResourceManagerId = DeterministicGuidBuilder(resourceManagerId);

            string path = $@"%LOCALAPPDATA%\NServiceBus.RavenDB\{store.ResourceManagerId}";
            store.TransactionRecoveryStorage = new LocalDirectoryTransactionRecoveryStorage(path);

            bool suppressDistributedTransactions;
            if (settings.TryGet("Transactions.SuppressDistributedTransactions", out suppressDistributedTransactions) && suppressDistributedTransactions)
            {
                store.EnlistInDistributedTransactions = false;
            }
        }
 internal TransactionSettings(ReadOnlySettings settings)
 {
     MaxRetries = 5;
     IsTransactional = settings.Get<bool>("Transactions.Enabled");
     TransactionTimeout = settings.Get<TimeSpan>("Transactions.DefaultTimeout");
     IsolationLevel = settings.Get<IsolationLevel>("Transactions.IsolationLevel");
     SuppressDistributedTransactions = settings.Get<bool>("Transactions.SuppressDistributedTransactions");
     DoNotWrapHandlersExecutionInATransactionScope = settings.Get<bool>("Transactions.DoNotWrapHandlersExecutionInATransactionScope");
 }
 internal TransactionSettings(ReadOnlySettings settings)
 {
     MaxRetries         = 5;
     IsTransactional    = settings.Get <bool>("Transactions.Enabled");
     TransactionTimeout = settings.Get <TimeSpan>("Transactions.DefaultTimeout");
     IsolationLevel     = settings.Get <IsolationLevel>("Transactions.IsolationLevel");
     SuppressDistributedTransactions = settings.Get <bool>("Transactions.SuppressDistributedTransactions");
     DoNotWrapHandlersExecutionInATransactionScope = settings.Get <bool>("Transactions.DoNotWrapHandlersExecutionInATransactionScope");
 }
 public MessageReceiverCreator(IManageMessagingFactoryLifeCycleInternal factories, ReadOnlySettings settings)
 {
     this.factories = factories;
     receiveMode    = settings.Get <ReceiveMode>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.ReceiveMode);
     prefetchCount  = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.PrefetchCount);
     if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessageReceivers.RetryPolicy))
     {
         retryPolicy = settings.Get <RetryPolicy>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.RetryPolicy);
     }
 }
        public static string GetConnectionString(this ReadOnlySettings settings)
        {
            var transportDefinition = settings.Get <TransportDefinition>();
            var instance            = settings.Get(transportSeamSettingsType.FullName);
            var prop = transportSeamSettingsType.GetProperty("TransportConnectionString");

            var transportConnectionString = prop.GetValue(instance, new object[0]);

            return((string)connectionStringGetter.Invoke(transportConnectionString, new object[] { transportDefinition }));
        }
Exemple #13
0
        protected override async Task OnStart(IMessageSession session)
        {
            Logger.Write(LogLevel.Info, "Starting event consumer");
            await _subscribers.SelectAsync(x => x.Setup(
                                               _settings.EndpointName(),
                                               _settings.Get <int>("ReadSize"),
                                               _settings.Get <bool>("ExtraStats"))
                                           ).ConfigureAwait(false);

            await _subscribers.SelectAsync(x => x.Subscribe(_cancellationTokenSource.Token)).ConfigureAwait(false);
        }
        public DefaultOutgoingBatchRouter(IConvertOutgoingMessagesToBrokeredMessages outgoingMessageConverter, IManageMessageSenderLifeCycle senders, ReadOnlySettings settings, IHandleOversizedBrokeredMessages oversizedMessageHandler)
        {
            this.outgoingMessageConverter = outgoingMessageConverter;
            this.senders  = senders;
            this.settings = settings;
            this.oversizedMessageHandler = oversizedMessageHandler;

            backOffTimeOnThrottle        = settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessageSenders.BackOffTimeOnThrottle);
            maxRetryAttemptsOnThrottle   = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageSenders.RetryAttemptsOnThrottle);
            maximuMessageSizeInKilobytes = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageSenders.MaximumMessageSizeInKilobytes);
        }
        public TopologyOperator(MessageReceiverCreator messageReceiverCreator, BrokeredMessagesToIncomingMessagesConverter brokeredMessageConverter, ReadOnlySettings settings)
        {
            this.brokeredMessageConverter = brokeredMessageConverter;
            this.messageReceiverCreator   = messageReceiverCreator;

            messageReceiverNotifierSettings = new MessageReceiverNotifierSettings(
                settings.Get <ReceiveMode>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.ReceiveMode),
                settings.HasExplicitValue <TransportTransactionMode>() ? settings.Get <TransportTransactionMode>() : settings.SupportedTransactionMode(),
                settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.AutoRenewTimeout),
                settings.Get <int>(WellKnownConfigurationKeys.Connectivity.NumberOfClientsPerEntity));
        }
        public OutgoingBatchRouter(BatchedOperationsToBrokeredMessagesConverter outgoingMessageConverter, MessageSenderLifeCycleManager sendersLifeCycleManager, ReadOnlySettings settings, IHandleOversizedBrokeredMessages oversizedMessageHandler)
        {
            this.outgoingMessageConverter = outgoingMessageConverter;
            this.sendersLifeCycleManager  = sendersLifeCycleManager;
            this.oversizedMessageHandler  = oversizedMessageHandler;

            sendViaFromConfiguration    = settings.Get <bool>(WellKnownConfigurationKeys.Connectivity.SendViaReceiveQueue);
            transportTypeIsNetMessaging = settings.Get <TransportType>(WellKnownConfigurationKeys.Connectivity.TransportType) == TransportType.NetMessaging;

            backOffTimeOnThrottle        = settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessageSenders.BackOffTimeOnThrottle);
            maxRetryAttemptsOnThrottle   = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageSenders.RetryAttemptsOnThrottle);
            maximuMessageSizeInKilobytes = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageSenders.MaximumMessageSizeInKilobytes);
        }
Exemple #17
0
        public NamespaceManagerCreator(ReadOnlySettings settings)
        {
            this.settings = settings;

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.NamespaceManagerSettingsFactory))
            {
                settingsFactory = settings.Get <Func <string, NamespaceManagerSettings> >(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.NamespaceManagerSettingsFactory);
            }
            else if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.TokenProviderFactory))
            {
                tokenProviderFactory = settings.Get <Func <string, TokenProvider> >(WellKnownConfigurationKeys.Connectivity.NamespaceManagers.TokenProviderFactory);
            }
        }
        public static TransportTransactionMode SupportedTransactionMode(this ReadOnlySettings settings)
        {
            var namespaces    = settings.Get <NamespaceConfigurations>(WellKnownConfigurationKeys.Topology.Addressing.Namespaces);
            var sendVia       = settings.Get <bool>(WellKnownConfigurationKeys.Connectivity.SendViaReceiveQueue);
            var transportType = settings.Get <TransportType>(WellKnownConfigurationKeys.Connectivity.TransportType);
            var receiveMode   = settings.Get <ReceiveMode>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.ReceiveMode);

            if (namespaces.Count == 1 && sendVia && transportType == TransportType.NetMessaging && receiveMode == ReceiveMode.PeekLock)
            {
                return(TransportTransactionMode.SendsAtomicWithReceive);
            }

            return(receiveMode == ReceiveMode.PeekLock ? TransportTransactionMode.ReceiveOnly : TransportTransactionMode.None);
        }
Exemple #19
0
        static DelayedConfig GetDelayedRetryConfig(ReadOnlySettings settings, bool transactionsOn)
        {
            if (!transactionsOn)
            {
                Logger.Warn("Delayed Retries will be disabled. Delayed retries are not supported when running with TransportTransactionMode.None. Failed messages will be moved to the error queue instead.");
                //Transactions must be enabled since Delayed Retries requires the transport to be able to rollback
                return(new DelayedConfig(0, TimeSpan.Zero));
            }

            var numberOfRetries = settings.Get <int>(NumberOfDelayedRetries);
            var timeIncrease    = settings.Get <TimeSpan>(DelayedRetriesTimeIncrease);

            return(new DelayedConfig(numberOfRetries, timeIncrease));
        }
        public async Task <IMessageReceiver> Create(string entityPath, string namespaceAlias)
        {
            var factory     = factories.Get(namespaceAlias);
            var receiveMode = settings.Get <ReceiveMode>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.ReceiveMode);

            var receiver = await factory.CreateMessageReceiver(entityPath, receiveMode).ConfigureAwait(false);

            receiver.PrefetchCount = settings.Get <int>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.PrefetchCount);

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessageReceivers.RetryPolicy))
            {
                receiver.RetryPolicy = settings.Get <RetryPolicy>(WellKnownConfigurationKeys.Connectivity.MessageReceivers.RetryPolicy);
            }
            return(receiver);
        }
        public MessagingFactoryCreator(IManageNamespaceManagerLifeCycleInternal namespaceManagers, ReadOnlySettings settings)
        {
            this.namespaceManagers = namespaceManagers;
            var transportType      = settings.Get <TransportType>(WellKnownConfigurationKeys.Connectivity.TransportType);
            var batchFlushInterval = settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessagingFactories.BatchFlushInterval);

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessagingFactories.RetryPolicy))
            {
                retryPolicy = settings.Get <RetryPolicy>(WellKnownConfigurationKeys.Connectivity.MessagingFactories.RetryPolicy);
            }

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessagingFactories.MessagingFactorySettingsFactory))
            {
                settingsFactory = settings.Get <Func <string, MessagingFactorySettings> >(WellKnownConfigurationKeys.Connectivity.MessagingFactories.MessagingFactorySettingsFactory);
            }
            else
            {
                settingsFactory = namespaceName =>
                {
                    var factorySettings = new MessagingFactorySettings
                    {
                        TransportType = transportType
                    };

                    switch (transportType)
                    {
                    case TransportType.NetMessaging:
                        factorySettings.NetMessagingTransportSettings = new NetMessagingTransportSettings
                        {
                            BatchFlushInterval = batchFlushInterval
                        };
                        break;

                    case TransportType.Amqp:
                        factorySettings.AmqpTransportSettings = new AmqpTransportSettings
                        {
                            BatchFlushInterval = batchFlushInterval
                        };
                        break;

                    default:
                        break;
                    }

                    return(factorySettings);
                };
            }
        }
Exemple #22
0
        IMessageSerializer GetDefaultSerializer(ReadOnlySettings settings)
        {
            var mainSerializer    = settings.Get <Tuple <SerializationDefinition, SettingsHolder> >("MainSerializer");
            var serializerFactory = mainSerializer.Item1.Configure(settings);

            return(serializerFactory(new MessageMapper()));
        }
        public static string GetConnectionString(ReadOnlySettings settings)
        {
            Contract.Requires(settings != null);
            Contract.Ensures(Contract.Result <string>() != null);

            if (settings.HasSetting(MongoPersistenceConstants.ConnectionStringKey))
            {
                var connectionString =
                    settings.Get <string>(MongoPersistenceConstants.ConnectionStringKey).AssumedNotNull();

                return(connectionString);
            }

            if (ConfigurationManager.ConnectionStrings[MongoPersistenceConstants.DefaultConnectionStringName] != null)
            {
                Logger.InfoFormat(
                    "Using connection string from {0}",
                    MongoPersistenceConstants.DefaultConnectionStringName);
                return(GetConnectionStringFromConfig(MongoPersistenceConstants.DefaultConnectionStringName));
            }

            Logger.InfoFormat("Using connection string from {0}", MongoPersistenceConstants.FallbackConnectionStringName);

            return(GetConnectionStringFromConfig(MongoPersistenceConstants.FallbackConnectionStringName));
        }
        internal void ApplyMappings(ReadOnlySettings settings, Configuration configuration)
        {
            var tableNamingConvention = settings.GetOrDefault <Func <Type, string> >("NHibernate.Sagas.TableNamingConvention");

            var scannedAssemblies = settings.GetAvailableTypes().Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                configuration.AddAssembly(assembly);
            }

            var             allSagaMetadata = settings.Get <SagaMetadataCollection>();
            var             types           = settings.GetAvailableTypes().Except(configuration.ClassMappings.Select(x => x.MappedClass));
            SagaModelMapper modelMapper;

            if (tableNamingConvention == null)
            {
                modelMapper = new SagaModelMapper(allSagaMetadata, types);
            }
            else
            {
                modelMapper = new SagaModelMapper(allSagaMetadata, types, tableNamingConvention);
            }

            configuration.AddMapping(modelMapper.Compile());
        }
        public GatewayHttpListenerInstaller(ReadOnlySettings settings)
        {
            var installerSettings = settings.Get <InstallerSettings>();

            channelManager = installerSettings.ChannelManager;
            enabled        = installerSettings.Enabled;
        }
        public static IDocumentStore Get(ReadOnlySettings settings)
        {
            // The holder is known to be non-null since we set it in the ctor
            var holder = settings.Get <DocumentStoreHolder>();

            if (holder.DocumentStore == null)
            {
                var p = settings.GetOrDefault <ConnectionParameters>(RavenDbSettingsExtensions.DefaultConnectionParameters);
                if (p != null)
                {
                    holder.DocumentStore = new DocumentStore
                    {
                        Url             = p.Url,
                        DefaultDatabase = p.DatabaseName ?? settings.EndpointName(),
                        ApiKey          = p.ApiKey
                    };
                    Helpers.ApplyRavenDBConventions(settings, holder.DocumentStore);
                    holder.DocumentStore.Initialize();
                }
                else
                {
                    holder.DocumentStore = Helpers.CreateDocumentStoreByConnectionStringName(settings, "NServiceBus/Persistence/RavenDB", "NServiceBus/Persistence");

                    if (holder.DocumentStore == null)
                    {
                        holder.DocumentStore = Helpers.CreateDocumentStoreByUrl(settings, "http://localhost:8080");
                    }
                }
            }
            return(holder.DocumentStore);
        }
Exemple #27
0
        /// <summary>
        /// Returns the requested config section using the current configuration source.
        /// </summary>
        public static T GetConfigSection <T>(this ReadOnlySettings settings) where T : class, new()
        {
            Guard.AgainstNull(nameof(settings), settings);
            var typesToScan         = settings.GetAvailableTypes();
            var configurationSource = settings.Get <IConfigurationSource>();

            var sectionOverrideTypes = typesToScan.Where(t => !t.IsAbstract && typeof(IProvideConfiguration <T>).IsAssignableFrom(t)).ToArray();

            if (sectionOverrideTypes.Length > 1)
            {
                throw new Exception($"Multiple configuration providers implementing IProvideConfiguration<{typeof(T).Name}> were found: {string.Join(", ", sectionOverrideTypes.Select(s => s.FullName))}. Ensure that only one configuration provider per configuration section is found to resolve this error.");
            }

            if (sectionOverrideTypes.Length == 0)
            {
                return(configurationSource.GetConfiguration <T>());
            }

            var sectionOverrideType = sectionOverrideTypes[0];

            IProvideConfiguration <T> sectionOverride;

            if (HasConstructorThatAcceptsSettings(sectionOverrideType))
            {
                sectionOverride = (IProvideConfiguration <T>)Activator.CreateInstance(sectionOverrideType, settings);
            }
            else
            {
                sectionOverride = (IProvideConfiguration <T>)Activator.CreateInstance(sectionOverrideType);
            }

            return(sectionOverride.GetConfiguration());
        }
Exemple #28
0
        public void Initialize(ReadOnlySettings settings, TransportInfrastructure transportInfrastructure, PipelineSettings pipelineSettings)
        {
            var unicastBusConfig        = settings.GetConfigSection <UnicastBusConfig>();
            var conventions             = settings.Get <Conventions>();
            var configuredUnicastRoutes = settings.GetOrDefault <ConfiguredUnicastRoutes>();
            var distributorAddress      = settings.GetOrDefault <string>("LegacyDistributor.Address");

            List <DistributionStrategy> distributionStrategies;

            if (settings.TryGet(out distributionStrategies))
            {
                foreach (var distributionStrategy in distributionStrategies)
                {
                    DistributionPolicy.SetDistributionStrategy(distributionStrategy);
                }
            }

            unicastBusConfig?.MessageEndpointMappings.Apply(Publishers, UnicastRoutingTable, transportInfrastructure.MakeCanonicalForm, conventions);
            configuredUnicastRoutes?.Apply(UnicastRoutingTable, conventions);

            pipelineSettings.Register(b =>
            {
                var router = new UnicastSendRouter(settings.GetOrDefault <string>("BaseInputQueueName"), settings.EndpointName(), settings.InstanceSpecificQueue(), distributorAddress, DistributionPolicy, UnicastRoutingTable, EndpointInstances, i => transportInfrastructure.ToTransportAddress(LogicalAddress.CreateRemoteAddress(i)));
                return(new UnicastSendRouterConnector(router));
            }, "Determines how the message being sent should be routed");

            pipelineSettings.Register(new UnicastReplyRouterConnector(), "Determines how replies should be routed");

            EnforceBestPractices = ShouldEnforceBestPractices(settings);
            if (EnforceBestPractices)
            {
                EnableBestPracticeEnforcement(conventions, pipelineSettings);
            }
        }
Exemple #29
0
        public void Initialize(ReadOnlySettings settings, Func <LogicalAddress, string> toTransportAddress, PipelineSettings pipelineSettings, ReceiveConfiguration receiveConfiguration)
        {
            var conventions             = settings.Get <Conventions>();
            var configuredUnicastRoutes = settings.GetOrDefault <ConfiguredUnicastRoutes>();

            if (settings.TryGet(out List <DistributionStrategy> distributionStrategies))
            {
                foreach (var distributionStrategy in distributionStrategies)
                {
                    DistributionPolicy.SetDistributionStrategy(distributionStrategy);
                }
            }

            configuredUnicastRoutes?.Apply(UnicastRoutingTable, conventions);

            pipelineSettings.Register(b =>
            {
                var router = new UnicastSendRouter(receiveConfiguration == null, receiveConfiguration?.QueueNameBase, receiveConfiguration?.InstanceSpecificQueue, DistributionPolicy, UnicastRoutingTable, EndpointInstances, i => toTransportAddress(LogicalAddress.CreateRemoteAddress(i)));
                return(new UnicastSendRouterConnector(router));
            }, "Determines how the message being sent should be routed");

            pipelineSettings.Register(new UnicastReplyRouterConnector(), "Determines how replies should be routed");

            EnforceBestPractices = ShouldEnforceBestPractices(settings);
            if (EnforceBestPractices)
            {
                EnableBestPracticeEnforcement(conventions, pipelineSettings);
            }
        }
        /// <summary>
        /// Returns the requested config section using the current configuration source.
        /// </summary>
        public static T GetConfigSection <T>(this ReadOnlySettings settings) where T : class, new()
        {
            Guard.AgainstNull(nameof(settings), settings);
            var typesToScan         = settings.GetAvailableTypes();
            var configurationSource = settings.Get <IConfigurationSource>();

            // ReSharper disable HeapView.SlowDelegateCreation
            var sectionOverrideType = typesToScan.Where(t => !t.IsAbstract)
                                      .FirstOrDefault(t => typeof(IProvideConfiguration <T>).IsAssignableFrom(t));

            // ReSharper restore HeapView.SlowDelegateCreation

            if (sectionOverrideType == null)
            {
                return(configurationSource.GetConfiguration <T>());
            }

            IProvideConfiguration <T> sectionOverride;

            if (HasConstructorThatAcceptsSettings(sectionOverrideType))
            {
                sectionOverride = (IProvideConfiguration <T>)Activator.CreateInstance(sectionOverrideType, settings);
            }
            else
            {
                sectionOverride = (IProvideConfiguration <T>)Activator.CreateInstance(sectionOverrideType);
            }

            return(sectionOverride.GetConfiguration());
        }
        public static string ToTransportAddress(this ReadOnlySettings settings, string queueName)
        {
            var transportInfrastructure = settings.Get <TransportInfrastructure>();
            var logicalAddress          = LogicalAddress.CreateLocalAddress(queueName, null);

            return(transportInfrastructure.ToTransportAddress(logicalAddress));
        }
Exemple #32
0
                protected override Task OnStart(IMessageSession session)
                {
#pragma warning disable 618
                    context.IsForwardingTopology = settings.Get <ITopology>() is ForwardingTopology;
#pragma warning restore 618
                    return(TaskEx.Completed);
                }
Exemple #33
0
 public Task Handle(RequestB message, IMessageHandlerContext context)
 {
     return(context.Reply(new ResponseB
     {
         EndpointInstance = settings.Get <string>("EndpointInstanceDiscriminator")
     }));
 }
        public static string GetConnectionString(ReadOnlySettings settings)
        {
            Contract.Requires(settings != null);
            Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result<string>()));

            if (settings.HasSetting(MongoPersistenceConstants.ConnectionStringKey))
            {
                var connectionString =
                    settings.Get<string>(MongoPersistenceConstants.ConnectionStringKey).AssumedNotNullOrWhiteSpace();

                return connectionString;
            }

            if (ConfigurationManager.ConnectionStrings[MongoPersistenceConstants.DefaultConnectionStringName] != null)
            {
                Logger.InfoFormat(
                    "Using connection string from {0}",
                    MongoPersistenceConstants.DefaultConnectionStringName);
                return GetConnectionStringFromConfig(MongoPersistenceConstants.DefaultConnectionStringName);    
            }

            Logger.InfoFormat("Using connection string from {0}", MongoPersistenceConstants.FallbackConnectionStringName);

            return GetConnectionStringFromConfig(MongoPersistenceConstants.FallbackConnectionStringName);
        }
 public StoreSnapshots(IEventStoreConnection client, ReadOnlySettings nsbSettings, IStreamCache cache, JsonSerializerSettings settings)
 {
     _client      = client;
     _nsbSettings = nsbSettings;
     _settings    = settings;
     _cache       = cache;
     _shouldCache = _nsbSettings.Get <Boolean>("ShouldCacheEntities");
 }
 public static Func<IDbConnection> GetConnectionFactory(ReadOnlySettings settings)
 {
     
     var holder = settings.Get<ConnectionFactoryHolder>();
     if (holder.ConnectionFactory != null) return holder.ConnectionFactory;
     var connectionFactory = CreateConnectionFactory();
     holder.ConnectionFactory = connectionFactory;
     return holder.ConnectionFactory;
 }
        protected override string GetLocalAddress(ReadOnlySettings settings)
        {
            var configSection = settings.GetConfigSection<AzureServiceBusQueueConfig>();
            if (configSection == null)
            {
                //hack: just to get the defaults, we should refactor this to support specifying the values on the NServiceBus/Transport connection string as well
                configSection = new AzureServiceBusQueueConfig();
            }

            ServiceBusEnvironment.SystemConnectivity.Mode = (ConnectivityMode)Enum.Parse(typeof(ConnectivityMode), configSection.ConnectivityMode);

            var queueName = settings.HasSetting("NServiceBus.LocalAddress") ? settings.Get<string>("NServiceBus.LocalAddress") : settings.EndpointName();
            return NamingConventions.QueueNamingConvention(settings, null, queueName, false);
            
        }
        static bool ShouldIndividualize(AzureServiceBusQueueConfig configSection, ReadOnlySettings settings)
        {
            // if this setting is set, then the core is responsible for individualization
            if (settings != null && settings.HasExplicitValue("IndividualizeEndpointAddress"))
            {
                return false;
            }

            // if explicitly set in code
            if (settings != null && settings.HasExplicitValue("ScaleOut.UseSingleBrokerQueue"))
                return !settings.Get<bool>("ScaleOut.UseSingleBrokerQueue");

            // if explicitly set in config
            if (configSection != null)
                return configSection.QueuePerInstance;

            // if default is set
            if (settings != null && !settings.GetOrDefault<bool>("ScaleOut.UseSingleBrokerQueue"))
                return !settings.GetOrDefault<bool>("ScaleOut.UseSingleBrokerQueue");

            return false;
        }
        static DelayedConfig GetDelayedRetryConfig(ReadOnlySettings settings, bool transactionsOn)
        {
            if (!transactionsOn)
            {
                Logger.Warn("Delayed Retries will be disabled. Delayed retries are not supported when running with TransportTransactionMode.None. Failed messages will be moved to the error queue instead.");
                //Transactions must be enabled since Delayed Retries requires the transport to be able to rollback
                return new DelayedConfig(0, TimeSpan.Zero);
            }

            var numberOfRetries = settings.Get<int>(NumberOfDelayedRetries);
            var timeIncrease = settings.Get<TimeSpan>(DelayedRetriesTimeIncrease);

            var retriesConfig = settings.GetConfigSection<SecondLevelRetriesConfig>();
            if (retriesConfig != null)
            {
                numberOfRetries = retriesConfig.Enabled ? retriesConfig.NumberOfRetries : 0;
                timeIncrease = retriesConfig.TimeIncrease;
            }

            return new DelayedConfig(numberOfRetries, timeIncrease);
        }
Exemple #40
0
 public static PersistenceExtentions<RavenDBPersistence> GetDefaultPersistenceExtensions(ReadOnlySettings settings)
 {
     return settings.Get<PersistenceExtentions<RavenDBPersistence>>(DefaultPersistenceExtensionsKey);
 }
Exemple #41
0
 public static IDocumentStore GetDefaultDocumentStore(ReadOnlySettings settings)
 {
     return settings.Get<IDocumentStore>(DefaultDocumentStoreKey);
 }
 public void Apply(ReadOnlySettings settings)
 {
     HostId = settings.Get<Guid>("NServiceBus.HostInformation.HostId");
     Host = settings.Get<string>("NServiceBus.HostInformation.DisplayName");
     EndpointName = settings.EndpointName();
 }
        static string GetDefaultEndpointAddress(ReadOnlySettings settings)
        {
            if (!settings.GetOrDefault<bool>("IndividualizeEndpointAddress"))
            {
                return settings.EndpointName();
            }

            if (!settings.HasSetting("EndpointInstanceDiscriminator"))
            {
                throw new Exception("No endpoint instance discriminator found. This value is usually provided by your transport so please make sure you're on the lastest version of your specific transport or set the discriminator using 'configuration.ScaleOut().UniqueQueuePerEndpointInstance(myDiscriminator)'");
            }

            return settings.EndpointName() + settings.Get<string>("EndpointInstanceDiscriminator");
        }
 public TransportSendInfrastructure Configure(ReadOnlySettings settings)
 {
     var transportInfrastructure = settings.Get<TransportInfrastructure>();
     return transportInfrastructure.ConfigureSendInfrastructure();
 }
        static ImmediateConfig GetImmediateRetryConfig(ReadOnlySettings settings, bool transactionsOn)
        {
            if (!transactionsOn)
            {
                Logger.Warn("Immediate Retries will be disabled. Immediate Retries are not supported when running with TransportTransactionMode.None. Failed messages will be moved to the error queue instead.");
                //Transactions must be enabled since Immediate Retries requires the transport to be able to rollback
                return new ImmediateConfig(0);
            }

            var retriesConfig = settings.GetConfigSection<TransportConfig>();
            var maxImmediateRetries = retriesConfig?.MaxRetries ?? settings.Get<int>(NumberOfImmediateRetries);

            return new ImmediateConfig(maxImmediateRetries);
        }
 internal static bool HasSupportFor(ReadOnlySettings settings, Storage storages)
 {
     return settings.Get<List<Storage>>("ResultingSupportedStorages")
         .Contains(storages);
 }
 protected override string GetLocalAddress(ReadOnlySettings settings)
 {
     return Address.Parse(settings.Get<string>("NServiceBus.LocalAddress")).Queue;
 }
 static bool HasAlternateTimeoutManagerBeenConfigured(ReadOnlySettings settings)
 {
     return settings.Get<TimeoutManagerAddressConfiguration>().TransportAddress != null;
 }