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"));
        }
Exemple #2
0
        private static DocumentStoreInitializer CreateDefaultDocumentStore(ReadOnlySettings settings)
        {
            var p = settings.GetOrDefault <ConnectionParameters>(RavenDbSettingsExtensions.DefaultConnectionParameters);

            if (p != null)
            {
                var storeByParams = new DocumentStore
                {
                    Url             = p.Url,
                    DefaultDatabase = p.DatabaseName ?? settings.EndpointName(),
                    ApiKey          = p.ApiKey,
                    Credentials     = p.Credentials
                };

                return(new DocumentStoreInitializer(storeByParams));
            }

            var initContext = CreateStoreByConnectionStringName(settings, "NServiceBus/Persistence/RavenDB", "NServiceBus/Persistence");

            if (initContext != null)
            {
                return(initContext);
            }

            return(CreateStoreByUrl(settings, "http://localhost:8080"));
        }
                public void Start()
                {
                    context.EndpointNameOfReceivingEndpoint = settings.EndpointName();
                    context.MessageId       = Guid.NewGuid().ToString();
                    context.UniqueMessageId = DeterministicGuid.MakeId(context.MessageId, context.EndpointNameOfReceivingEndpoint).ToString();

                    var transportMessage = new TransportMessage();

                    transportMessage.Headers[Headers.ProcessingEndpoint]                     = context.EndpointNameOfReceivingEndpoint;
                    transportMessage.Headers[Headers.MessageId]                              = context.MessageId;
                    transportMessage.Headers[Headers.ConversationId]                         = "a59395ee-ec80-41a2-a728-a3df012fc707";
                    transportMessage.Headers["$.diagnostics.hostid"]                         = "bdd4b0510bff5a6d07e91baa7e16a804";
                    transportMessage.Headers["$.diagnostics.hostdisplayname"]                = "SELENE";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.ExceptionType"]      = "2014-11-11 02:26:57:767462 Z";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Message"]            = "An error occurred while attempting to extract logical messages from transport message NServiceBus.TransportMessage";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = "System.Exception";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.HelpLink"]           = String.Empty;
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Source"]             = "NServiceBus.Core";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.StackTrace"]         = String.Empty;
                    transportMessage.Headers["NServiceBus.FailedQ"]                          = settings.LocalAddress().ToString();
                    transportMessage.Headers["NServiceBus.TimeOfFailure"]                    = "2014-11-11 02:26:58:000462 Z";
                    transportMessage.Headers["NServiceBus.TimeSent"]                         = "2014-11-11 02:26:01:174786 Z";
                    transportMessage.Headers[Headers.ControlMessageHeader]                   = Boolean.TrueString;
                    transportMessage.Headers[Headers.ReplyToAddress]                         = settings.LocalAddress().ToString();

                    sendMessages.Send(transportMessage, new SendOptions(Address.Parse("error")));
                }
    IDocumentStore CreateDocumentStore(ReadOnlySettings settings)
    {
        string endpointName = settings.EndpointName().ToString();

        DocumentStore store = new DocumentStore
        {
            Url             = "http://localhost:8083", // RavenServerUrl
            DefaultDatabase = endpointName
        };

        var localAddress = settings.LocalAddress();

        // Calculate a ResourceManagerId unique to this endpoint using just LocalAddress
        // Not suitable for side-by-side installations!
        Guid resourceManagerId = DeterministicGuidBuilder(localAddress);

        // Calculate a DTC transaction recovery storage path including the ResourceManagerId
        string programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
        string txRecoveryPath  = Path.Combine(programDataPath, "NServiceBus.RavenDB", resourceManagerId.ToString());

        store.ResourceManagerId          = resourceManagerId;
        store.TransactionRecoveryStorage = new LocalDirectoryTransactionRecoveryStorage(txRecoveryPath);

        return(store);
    }
            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");
                }
            }
        void SetDefaultClientProperties(ReadOnlySettings settings)
        {
            var nsb            = typeof(Endpoint).Assembly.Location;
            var nsbVersion     = FileVersionInfo.GetVersionInfo(nsb);
            var nsbFileVersion = $"{nsbVersion.FileMajorPart}.{nsbVersion.FileMinorPart}.{nsbVersion.FileBuildPart}";

            var rabbitMQ            = typeof(ConnectionConfiguration).Assembly.Location;
            var rabbitMQVersion     = FileVersionInfo.GetVersionInfo(rabbitMQ);
            var rabbitMQFileVersion = $"{rabbitMQVersion.FileMajorPart}.{rabbitMQVersion.FileMinorPart}.{rabbitMQVersion.FileBuildPart}";

            var applicationNameAndPath = Environment.GetCommandLineArgs()[0];
            var applicationName        = Path.GetFileName(applicationNameAndPath);
            var applicationPath        = Path.GetDirectoryName(applicationNameAndPath);

            var hostname = RuntimeEnvironment.MachineName;

            ClientProperties.Add("client_api", "NServiceBus");
            ClientProperties.Add("nservicebus_version", nsbFileVersion);
            ClientProperties.Add("nservicebus.rabbitmq_version", rabbitMQFileVersion);
            ClientProperties.Add("application", applicationName);
            ClientProperties.Add("application_location", applicationPath);
            ClientProperties.Add("machine_name", hostname);
            ClientProperties.Add("user", UserName);
            ClientProperties.Add("endpoint_name", settings.EndpointName());
        }
    protected override Task OnStart(IMessageSession context)
    {
        var mainLogicalAddress = settings.LogicalAddress();
        var endpointInstance   = mainLogicalAddress.EndpointInstance;
        var instanceProperties = endpointInstance.Properties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

        instanceProperties["queue"] = endpointInstance.Endpoint;
        publication = new RoutingInfo
        {
            EndpointName          = settings.EndpointName(),
            Discriminator         = endpointInstance.Discriminator,
            InstanceProperties    = instanceProperties,
            HandledMessageTypes   = hanledMessageTypes.Select(m => m.AssemblyQualifiedName).ToArray(),
            PublishedMessageTypes = publishedMessageTypes.Select(m => m.AssemblyQualifiedName).ToArray(),
            Active = true,
        };

        timer = new Timer(
            callback: state =>
        {
            Publish()
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();
        },
            state: null,
            dueTime: TimeSpan.Zero,
            period: heartbeatPeriod);

        return(Publish());
    }
        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);
        }
        static Func <string, Task> BuildDefaultDiagnosticsWriter(ReadOnlySettings settings)
        {
            if (!settings.TryGet <string>(DiagnosticSettingsExtensions.DiagnosticsPathKey, out var diagnosticsRootPath))
            {
                try
                {
                    diagnosticsRootPath = Path.Combine(Host.GetOutputDirectory(), ".diagnostics");
                }
                catch (Exception e)
                {
                    logger.Error("Unable to determine the diagnostics output directory. Check the attached exception for further information, or configure a custom diagnostics directory using 'EndpointConfiguration.SetDiagnosticsPath()'.", e);
                }
            }

            if (!Directory.Exists(diagnosticsRootPath))
            {
                Directory.CreateDirectory(diagnosticsRootPath);
            }

            var endpointName = settings.EndpointName();

            // Once we have the proper hosting model in place we can skip the endpoint name since the host would
            // know how to handle multi hosting but for now we do this so that multi-hosting users will get a file per endpoint
            var startupDiagnosticsFileName = $"{endpointName}-configuration.txt";
            var startupDiagnosticsFilePath = Path.Combine(diagnosticsRootPath, startupDiagnosticsFileName);

            return(data => AsyncFile.WriteText(startupDiagnosticsFilePath, data));
        }
Exemple #10
0
                public void Start()
                {
                    var transportMessage = new TransportMessage(context.MessageId, new Dictionary <string, string> {
                        { Headers.ProcessingEndpoint, settings.EndpointName() }
                    });

                    sendMessages.Send(transportMessage, new SendOptions("audit"));
                }
 public HostIdFixer(UnicastBus bus, ReadOnlySettings settings)
 {
     Guid hostId = CreateGuid(Environment.MachineName, settings.EndpointName());
     string location = Assembly.GetExecutingAssembly().Location;
     Dictionary<string, string> properties = new Dictionary<string, string>
     {
         {"Location", location}
     };
     bus.HostInformation = new HostInformation(hostId, Environment.MachineName, properties);
 }
        internal static IManageReceiveChannels CreateChannelManager(ReadOnlySettings settings)
        {
            var channels = GatewaySettings.GetConfiguredChannels(settings);

            if (channels.Any())
            {
                return(new ConfigurationBasedChannelManager(channels));
            }

            return(new ConventionBasedChannelManager(settings.EndpointName()));
        }
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 async Task End(Exception ex = null)
 {
     if (ex != null)
     {
         return;
     }
     if (this.CurrentPosition.HasValue)
     {
         await _checkpoints.Save(_settings.EndpointName(), CurrentPosition.Value);
     }
 }
    public void Start()
    {
        var hostId     = CreateGuid(Environment.MachineName, settings.EndpointName());
        var location   = Assembly.GetExecutingAssembly().Location;
        var properties = new Dictionary <string, string>
        {
            { "Location", location }
        };

        bus.HostInformation = new HostInformation(hostId, Environment.MachineName, properties);
    }
        public HostIdFixer(UnicastBus bus, ReadOnlySettings settings)
        {
            var hostId     = CreateGuid(Environment.MachineName, settings.EndpointName());
            var location   = Assembly.GetExecutingAssembly().Location;
            var properties = new Dictionary <string, string>
            {
                { "Location", location }
            };

            bus.HostInformation = new HostInformation(hostId, Environment.MachineName, properties);
        }
        internal static string GetTablePrefix(this ReadOnlySettings settings)
        {
            if (settings.TryGet("SqlPersistence.TablePrefix", out string tablePrefix))
            {
                return(tablePrefix);
            }
            var endpointName = settings.EndpointName();
            var clean        = TableNameCleaner.Clean(endpointName);

            return($"{clean}_");
        }
Exemple #18
0
        public static Address GetMasterNodeAddress(ReadOnlySettings settings)
        {
            var unicastBusConfig = settings.GetConfigSection <UnicastBusConfig>();

            //allow users to override data address in config
            if (unicastBusConfig != null && !string.IsNullOrWhiteSpace(unicastBusConfig.DistributorDataAddress))
            {
                return(Address.Parse(unicastBusConfig.DistributorDataAddress));
            }

            var masterNode = GetMasterNode(settings);

            if (string.IsNullOrWhiteSpace(masterNode))
            {
                return(Address.Parse(settings.EndpointName()));
            }

            ValidateHostName(masterNode);

            return(new Address(settings.EndpointName(), masterNode));
        }
Exemple #19
0
        protected override async Task OnStart(IMessageSession session)
        {
            Logger.Write(LogLevel.Info, "Starting event consumer");
            await _subscribers.WhenAllAsync(x => x.Setup(
                                                _settings.EndpointName(),
                                                _cancellationTokenSource.Token,
                                                Assembly.GetEntryAssembly().GetName().Version)
                                            ).ConfigureAwait(false);


            await _subscribers.WhenAllAsync(x => x.Connect()).ConfigureAwait(false);
        }
        public static Address GetMasterNodeAddress(ReadOnlySettings settings)
        {
            var unicastBusConfig = settings.GetConfigSection<UnicastBusConfig>();

            //allow users to override data address in config
            if (unicastBusConfig != null && !string.IsNullOrWhiteSpace(unicastBusConfig.DistributorDataAddress))
            {
                return Address.Parse(unicastBusConfig.DistributorDataAddress);
            }

            var masterNode = GetMasterNode(settings);

            if (string.IsNullOrWhiteSpace(masterNode))
            {
                return Address.Parse(settings.EndpointName());
            }

            ValidateHostName(masterNode);

            return new Address(settings.EndpointName(), masterNode);
        }
Exemple #21
0
        static DocumentStoreInitializer CreateStoreByUrl(ReadOnlySettings settings, string url)
        {
            var docStore = new DocumentStore
            {
                Url = url
            };

            if (docStore.DefaultDatabase == null)
            {
                docStore.DefaultDatabase = settings.EndpointName();
            }

            return(new DocumentStoreInitializer(docStore));
        }
Exemple #22
0
            protected override async Task OnStart(IMessageSession session)
            {
                Logger.Write(LogLevel.Info, "Starting domain");
                await session.Publish <DomainAlive>(x =>
                {
                    x.Endpoint = _settings.InstanceSpecificQueue();
                    x.Instance = Aggregates.Defaults.Instance;
                }).ConfigureAwait(false);

                Logger.Write(LogLevel.Info, "Starting snapshot consumer");
                await _subscriber.Setup(_settings.EndpointName()).ConfigureAwait(false);

                await _subscriber.Subscribe(_cancellationTokenSource.Token).ConfigureAwait(false);
            }
        void ApplyConventions(ReadOnlySettings settings)
        {
            if (DocumentIdConventionsExtensions.NeedToApplyDocumentIdConventionsToDocumentStore(settings))
            {
                var sagasEnabled = settings.IsFeatureActive(typeof(Sagas));
                var timeoutsEnabled = settings.IsFeatureActive(typeof(TimeoutManager));
                var idConventions = new DocumentIdConventions(docStore, settings.GetAvailableTypes(), settings.EndpointName(), sagasEnabled, timeoutsEnabled);
                docStore.Conventions.FindTypeTagName = idConventions.FindTypeTagName;
            }

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

            bool suppressDistributedTransactions;
            if (settings.TryGet("Transactions.SuppressDistributedTransactions", out suppressDistributedTransactions) && suppressDistributedTransactions)
            {
                store.EnlistInDistributedTransactions = false;
            }
            else 
            {
                if (store.JsonRequestFactory == null) // If the DocStore has not been initialized yet
                {
                    if (store.ResourceManagerId == Guid.Empty || store.ResourceManagerId == ravenDefaultResourceManagerId)
                    {
                        var resourceManagerId = settings.LocalAddress();
                        store.ResourceManagerId = DeterministicGuidBuilder(resourceManagerId);
                    }

                    // If using the default (Volatile - null should be impossible) then switch to IsolatedStorage
                    // Leave alone if LocalDirectoryTransactionRecoveryStorage!
                    if (store.TransactionRecoveryStorage == null || store.TransactionRecoveryStorage is VolatileOnlyTransactionRecoveryStorage)
                    {
                        store.TransactionRecoveryStorage = new IsolatedStorageTransactionRecoveryStorage();
                    }
                }

                var dtcSettingsNotIdeal = store.ResourceManagerId == Guid.Empty ||
                                          store.ResourceManagerId == ravenDefaultResourceManagerId ||
                                          !(store.TransactionRecoveryStorage is LocalDirectoryTransactionRecoveryStorage);

                if (dtcSettingsNotIdeal)
                {
                    Logger.Warn("NServiceBus has detected that a RavenDB DocumentStore is being used with Distributed Transaction Coordinator transactions, but without the recommended production-safe settings for ResourceManagerId or TransactionStorageRecovery. Refer to \"Setting RavenDB DTC settings manually\" in the NServiceBus documentation for more information.");
                }
            }
        }
        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);
            
        }
        internal static string DetermineStorageQueueName(ReadOnlySettings settings)
        {
            var configuredQueueName = settings.GetConfiguredMsmqPersistenceSubscriptionQueue();

            if (!string.IsNullOrEmpty(configuredQueueName))
            {
                return(configuredQueueName);
            }
            ThrowIfUsingTheOldDefaultSubscriptionsQueue(configuredQueueName);

            var defaultQueueName = $"{settings.EndpointName()}.Subscriptions";

            Logger.Info($"The queue used to store subscriptions has not been configured, the default '{defaultQueueName}' will be used.");
            return(defaultQueueName);
        }
Exemple #26
0
        public static IDocumentStore CreateDocumentStoreByUrl(ReadOnlySettings settings, string url)
        {
            var docStore = new DocumentStore {
                Url = url
            };

            if (docStore.DefaultDatabase == null)
            {
                docStore.DefaultDatabase = settings.EndpointName();
            }

            ApplyRavenDBConventions(settings, docStore);

            return(docStore.Initialize());
        }
Exemple #27
0
        public static ReceiveConfiguration Build(ReadOnlySettings settings, TransportComponent.Configuration transportConfiguration)
        {
            var isSendOnlyEndpoint = settings.Get <bool>("Endpoint.SendOnly");

            if (isSendOnlyEndpoint)
            {
                if (settings.HasExplicitValue(ReceiveSettingsExtensions.CustomLocalAddressKey))
                {
                    throw new Exception($"Specifying a base name for the input queue using `{nameof(ReceiveSettingsExtensions.OverrideLocalAddress)}(baseInputQueueName)` is not supported for send-only endpoints.");
                }
                return(null);
            }

            var endpointName   = settings.EndpointName();
            var discriminator  = settings.GetOrDefault <string>("EndpointInstanceDiscriminator");
            var queueNameBase  = settings.GetOrDefault <string>(ReceiveSettingsExtensions.CustomLocalAddressKey) ?? endpointName;
            var purgeOnStartup = settings.GetOrDefault <bool>("Transport.PurgeOnStartup");

            //note: This is an old hack, we are passing the endpoint name to bind but we only care about the properties
            var mainInstanceProperties = transportConfiguration.BindToLocalEndpoint(new EndpointInstance(endpointName)).Properties;

            var logicalAddress = LogicalAddress.CreateLocalAddress(queueNameBase, mainInstanceProperties);

            var localAddress = transportConfiguration.ToTransportAddress(logicalAddress);

            string instanceSpecificQueue = null;

            if (discriminator != null)
            {
                instanceSpecificQueue = transportConfiguration.ToTransportAddress(logicalAddress.CreateIndividualizedAddress(discriminator));
            }

            var transactionMode = GetRequiredTransactionMode(settings);

            var pushRuntimeSettings = GetDequeueLimitations(settings);

            return(new ReceiveConfiguration(
                       logicalAddress,
                       queueNameBase,
                       localAddress,
                       instanceSpecificQueue,
                       transactionMode,
                       pushRuntimeSettings,
                       purgeOnStartup,
                       settings.GetOrDefault <Notification <ReceivePipelineCompleted> >() ?? new Notification <ReceivePipelineCompleted>()));
        }
Exemple #28
0
        protected override Task OnStart(IBusContext context)
        {
            publication = new HandledMessageDeclaration
            {
                EndpointName           = settings.EndpointName().ToString(),
                UserDiscriminator      = settings.EndpointInstanceName().UserDiscriminator,
                TransportDiscriminator = settings.EndpointInstanceName().TransportDiscriminator,
                HandledMessageTypes    = hanledMessageTypes.Select(m => m.AssemblyQualifiedName).ToArray(),
                Active = true,
            };

            timer = new Timer(state =>
            {
                Publish().ConfigureAwait(false).GetAwaiter().GetResult();
            }, null, heartbeatPeriod, heartbeatPeriod);

            return(Publish());
        }
                public void Start()
                {
                    context.EndpointNameOfReceivingEndpoint = settings.EndpointName();
                    context.MessageId       = Guid.NewGuid().ToString();
                    context.UniqueMessageId = DeterministicGuid.MakeId(context.MessageId, context.EndpointNameOfReceivingEndpoint).ToString();

                    var transportMessage = new TransportMessage(context.MessageId, new Dictionary <string, string>());

                    transportMessage.Headers[Headers.ProcessingEndpoint] = context.EndpointNameOfReceivingEndpoint;
                    transportMessage.Headers["NServiceBus.ExceptionInfo.ExceptionType"]      = "2014-11-11 02:26:57:767462 Z";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Message"]            = "An error occurred while attempting to extract logical messages from transport message NServiceBus.TransportMessage";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = "System.Exception";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Source"]             = "NServiceBus.Core";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.StackTrace"]         = String.Empty;
                    transportMessage.Headers["NServiceBus.FailedQ"]       = settings.LocalAddress().ToString();
                    transportMessage.Headers["NServiceBus.TimeOfFailure"] = "2014-11-11 02:26:58:000462 Z";

                    sendMessages.Send(transportMessage, new SendOptions("error"));
                }
Exemple #30
0
        static DocumentStoreInitializer CreateStoreByConnectionStringName(ReadOnlySettings settings, params string[] connectionStringNames)
        {
#if NET452
            var connectionStringName = GetFirstNonEmptyConnectionString(connectionStringNames);
            if (!string.IsNullOrWhiteSpace(connectionStringName))
            {
                var docStore = new DocumentStore
                {
                    ConnectionStringName = connectionStringName
                };
                if (docStore.DefaultDatabase == null)
                {
                    docStore.DefaultDatabase = settings.EndpointName();
                }

                return(new DocumentStoreInitializer(docStore));
            }
#endif
            return(null);
        }
Exemple #31
0
        public static IDocumentStore CreateDocumentStoreByConnectionStringName(ReadOnlySettings settings, params string[] connectionStringNames)
        {
            var connectionStringName = GetFirstNonEmptyConnectionString(connectionStringNames);

            if (!string.IsNullOrWhiteSpace(connectionStringName))
            {
                var docStore = new DocumentStore
                {
                    ConnectionStringName = connectionStringName
                };
                if (docStore.DefaultDatabase == null)
                {
                    docStore.DefaultDatabase = settings.EndpointName();
                }
                ApplyRavenDBConventions(settings, docStore);

                return(docStore.Initialize());
            }
            return(null);
        }
        static Func <string, Task> BuildDefaultDiagnosticsWriter(ReadOnlySettings settings)
        {
            if (!settings.TryGet <string>(DiagnosticSettingsExtensions.DiagnosticsPathKey, out var diagnosticsRootPath))
            {
                diagnosticsRootPath = Path.Combine(Host.GetOutputDirectory(), ".diagnostics");
            }

            if (!Directory.Exists(diagnosticsRootPath))
            {
                Directory.CreateDirectory(diagnosticsRootPath);
            }

            var endpointName = settings.EndpointName();

            // Once we have the proper hosting model in place we can skip the endpoint name since the host would
            // know how to handle multi hosting but for now we do this so that multi-hosting users will get a file per endpoint
            var startupDiagnosticsFileName = $"{endpointName}-configuration.txt";
            var startupDiagnosticsFilePath = Path.Combine(diagnosticsRootPath, startupDiagnosticsFileName);

            return(data => AsyncFile.WriteText(startupDiagnosticsFilePath, data));
        }
Exemple #33
0
        protected override async Task OnStart(IMessageSession session)
        {
            Logger.Write(LogLevel.Info, "Starting event consumer");
            await _subscriber.Setup(
                _settings.EndpointName(),
                _settings.Get <int>("ReadSize"),
                _settings.Get <bool>("ExtraStats")).ConfigureAwait(false);


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

            _subscriber.Dropped = (reason, ex) =>
            {
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Write(LogLevel.Info, () => $"Event consumer stopped - cancelation requested");
                    return;
                }
                Logger.Warn($"Event consumer stopped due to exception: {ex.Message}.  Will restart", ex);
                Thread.Sleep(CalculateSleep());
                _subscriber.Subscribe(_cancellationTokenSource.Token).Wait();
            };
        }
        public async Task CommitAsync(Func <Task> next)
        {
            var clientOutboxTransaction = _unitOfWorkContext.Get <IClientOutboxTransaction>();
            var transportOperations     = _unitOfWorkContext.GetEvents().Select(e => new TransportOperation(GuidComb.NewGuidComb(), e)).ToList();
            var clientOutboxMessage     = transportOperations.Any() ? new ClientOutboxMessageV2(GuidComb.NewGuidComb(), _settings.EndpointName(), transportOperations) : null;

            if (clientOutboxMessage != null)
            {
                await _clientOutboxStorage.StoreAsync(clientOutboxMessage, clientOutboxTransaction).ConfigureAwait(false);
            }

            await next().ConfigureAwait(false);

            if (clientOutboxMessage != null)
            {
                var tasks = clientOutboxMessage.TransportOperations.Select(o =>
                {
                    if (o.Message.IsCommand())
                    {
                        return(SendMessage(o));
                    }
                    else
                    {
                        return(PublishMessage(o));
                    }
                });

                await Task.WhenAll(tasks).ConfigureAwait(false);

                await _clientOutboxStorage.SetAsDispatchedAsync(clientOutboxMessage.MessageId, clientOutboxTransaction).ConfigureAwait(false);
            }
        }
 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");
        }
Exemple #37
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);
            }
        }
 protected override string GetLocalAddress(ReadOnlySettings settings)
 {
     return settings.EndpointName();
 }