示例#1
0
        public void SetUp()
        {
            var builder = new NHibernateSagaStorage();

            var cfg = new Configuration()
                      .DataBaseIntegration(x =>
            {
                x.Dialect <MsSql2012Dialect>();
                x.ConnectionString = Consts.SqlConnectionString;
            });

            var types = new[] { typeof(SagaWithAbstractBaseClassActualSaga), typeof(SagaWithAbstractBaseClass), typeof(ContainSagaData), typeof(MyOwnAbstractBase) };

            var allMetadata = new SagaMetadataCollection();

            allMetadata.Initialize(types);

            var settings = new SettingsHolder();

            settings.Set("TypesToScan", types);
            settings.Set <SagaMetadataCollection>(allMetadata);

            builder.ApplyMappings(settings, cfg);
            sessionFactory = cfg.BuildSessionFactory() as SessionFactoryImpl;
        }
        public void Clear_ShouldDisposeAllDisposables()
        {
            var firstOverrideDisposable = new SomeDisposable();
            var secondOverrideDisposable = new SomeDisposable();
            var firstDefaultDisposable = new SomeDisposable();
            var secondDefaultDisposable = new SomeDisposable();

            var all = new[]
            {
                firstDefaultDisposable,
                secondDefaultDisposable,
                firstOverrideDisposable,
                secondOverrideDisposable
            };

            var settings = new SettingsHolder();
            settings.Set("1.Override", firstOverrideDisposable);
            settings.Set("2.Override", secondOverrideDisposable);
            settings.SetDefault("1.Default", firstDefaultDisposable);
            settings.SetDefault("2.Default", secondDefaultDisposable);

            settings.Clear();

            Assert.IsTrue(all.All(x => x.Disposed));
        }
示例#3
0
        public void GetTopicName_caches()
        {
            var called = 0;

            string Generator(Type eventType, string prefix)
            {
                called++;
                return($"{prefix}{eventType.Name}");
            }

            var settings = new SettingsHolder();

            settings.Set(SettingsKeys.TopicNamePrefix, "PREFIX");
            settings.Set(SettingsKeys.TopicNameGenerator, (Func <Type, string, string>)Generator);

            var configuration = new TransportConfiguration(settings);

            var metadataRegistry = settings.SetupMessageMetadataRegistry();
            var metadata         = metadataRegistry.GetMessageMetadata(typeof(Event));

            var cache = new TopicCache(null, metadataRegistry, configuration);

            cache.GetTopicName(metadata);
            cache.GetTopicName(metadata);

            Assert.AreEqual(1, called);
        }
        public void SetUp()
        {
            var builder = new NHibernateSagaStorage();

            var cfg = new Configuration()
                      .DataBaseIntegration(x =>
            {
                x.Dialect <MsSql2012Dialect>();
                x.ConnectionString = Consts.SqlConnectionString;
            });

            var settings = new SettingsHolder();

            var metaModel = new SagaMetadataCollection();
            var types     = new [] { typeof(TestSaga), typeof(TestSagaData), typeof(TestComponent), typeof(PolymorphicPropertyBase),
                                     typeof(AlsoDerivedFromTestSagaWithTableNameAttributeActualSaga), typeof(AlsoDerivedFromTestSagaWithTableNameAttribute),
                                     typeof(DerivedFromTestSagaWithTableNameAttributeActualSaga), typeof(DerivedFromTestSagaWithTableNameAttribute),
                                     typeof(TestSagaWithTableNameAttributeActualSaga), typeof(TestSagaWithTableNameAttribute),
                                     typeof(SagaWithVersionedPropertyAttributeActualSaga), typeof(SagaWithVersionedPropertyAttribute),
                                     typeof(SagaWithoutVersionedPropertyAttributeActualSaga), typeof(SagaWithoutVersionedPropertyAttribute),
                                     typeof(object) };

            metaModel.Initialize(types);
            settings.Set <SagaMetadataCollection>(metaModel);

            settings.Set("TypesToScan", types);
            builder.ApplyMappings(settings, cfg);
            sessionFactory = cfg.BuildSessionFactory() as SessionFactoryImpl;

            persisterForTestSaga = sessionFactory.GetEntityPersisterFor <TestSagaData>();
        }
示例#5
0
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transactionMode)
    {
        LogManager.UseFactory(new ConsoleLoggerFactory());

        if (settings.TryGet <MessageMetadataRegistry>(out var registry) == false)
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance;

            var conventions = settings.GetOrCreate <Conventions>();
            registry = (MessageMetadataRegistry)Activator.CreateInstance(typeof(MessageMetadataRegistry), flags, null, new object[] { new Func <Type, bool>(t => conventions.IsMessageType(t)) }, CultureInfo.InvariantCulture);

            settings.Set(registry);
        }

        var methodName = TestContext.CurrentContext.Test.MethodName;

        if (methodName == nameof(When_on_error_throws.Should_reinvoke_on_error_with_original_exception))
        {
            throw new IgnoreException("ASQ uses a circuit breaker that is triggered after specific period of time. Critical errors are not reported immediately");
        }

        settings.Set(AzureStorageQueueTransport.SerializerSettingsKey, Tuple.Create <SerializationDefinition, SettingsHolder>(new XmlSerializer(), settings));

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

        transportExtension.SanitizeQueueNamesWith(BackwardsCompatibleQueueNameSanitizerForTests.Sanitize);

        return(new TransportConfigurationResult
        {
            TransportInfrastructure = new AzureStorageQueueTransport().Initialize(settings, Testing.Utillities.GetEnvConfiguredConnectionString()),
            PurgeInputQueueOnStartup = false
        });
    }
        public void Specific_stores_should_mask_default()
        {
            using (var db = new ReusableDB())
            {
                var settings = new SettingsHolder();
                settings.Set("Transactions.SuppressDistributedTransactions", true);
                settings.Set("TypesToScan", new Type[0]);
                settings.Set("NServiceBus.Routing.EndpointName", "FakeEndpoint");
                settings.Set("NServiceBus.Transport.TransportInfrastructure", new FakeRavenDBTransportInfrastructure(TransportTransactionMode.None));
                settings.Set("Endpoint.SendOnly", true);

                DocumentStoreManager.SetDocumentStore <StorageType.GatewayDeduplication>(settings, db.NewStore("GatewayDeduplication"));
                DocumentStoreManager.SetDocumentStore <StorageType.Outbox>(settings, db.NewStore("Outbox"));
                DocumentStoreManager.SetDocumentStore <StorageType.Sagas>(settings, db.NewStore("Sagas"));
                DocumentStoreManager.SetDocumentStore <StorageType.Subscriptions>(settings, db.NewStore("Subscriptions"));
                DocumentStoreManager.SetDocumentStore <StorageType.Timeouts>(settings, db.NewStore("Timeouts"));
                DocumentStoreManager.SetDefaultStore(settings, db.NewStore("Default"));

                var readOnly = settings as ReadOnlySettings;

                Assert.AreEqual("GatewayDeduplication", DocumentStoreManager.GetDocumentStore <StorageType.GatewayDeduplication>(readOnly).Identifier);
                Assert.AreEqual("Outbox", DocumentStoreManager.GetDocumentStore <StorageType.Outbox>(readOnly).Identifier);
                Assert.AreEqual("Sagas", DocumentStoreManager.GetDocumentStore <StorageType.Sagas>(readOnly).Identifier);
                Assert.AreEqual("Subscriptions", DocumentStoreManager.GetDocumentStore <StorageType.Subscriptions>(readOnly).Identifier);
                Assert.AreEqual("Timeouts", DocumentStoreManager.GetDocumentStore <StorageType.Timeouts>(readOnly).Identifier);
            }
        }
示例#7
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
        });
    }
        static void SetTransportSpecificFlags(SettingsHolder settings, string poisonQueue)
        {
            //To satisfy requirements of various transports

            //MSMQ
            settings.Set("errorQueue", poisonQueue); //Not SetDefault Because MSMQ transport verifies if that value has been explicitly set

            //RabbitMQ
            settings.SetDefault("RabbitMQ.RoutingTopologySupportsDelayedDelivery", true);

            //SQS
            settings.SetDefault("NServiceBus.AmazonSQS.DisableSubscribeBatchingOnStart", true);

            //ASB
            var builder = new ConventionsBuilder(settings);

            builder.DefiningEventsAs(type => true);
            settings.Set(builder.Conventions);

            //ASQ and ASB
            var serializer = Tuple.Create(new NewtonsoftSerializer() as SerializationDefinition, new SettingsHolder());

            settings.SetDefault("MainSerializer", serializer);

            //SQS and ASQ
            bool isMessageType(Type t) => true;

            var ctor = typeof(MessageMetadataRegistry).GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(Func <Type, bool>) }, null);

#pragma warning disable CS0618 // Type or member is obsolete
            settings.SetDefault <MessageMetadataRegistry>(ctor.Invoke(new object[] { (Func <Type, bool>)isMessageType }));
#pragma warning restore CS0618 // Type or member is obsolete
        }
示例#9
0
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transportTransactionMode)
    {
#if !NETFRAMEWORK
        if (transportTransactionMode == TransportTransactionMode.TransactionScope)
        {
            NUnit.Framework.Assert.Ignore("TransactionScope not supported in .NET Core");
        }
#endif
        this.settings = settings;
        settings.Set(transportTransactionMode);
        settings.Set("NServiceBus.SharedQueue", settings.EndpointName());
        var delayedDeliverySettings = new DelayedDeliverySettings(settings);
        delayedDeliverySettings.TableSuffix("Delayed");

        var pubSubSettings = new SubscriptionSettings();
        pubSubSettings.DisableSubscriptionCache();
        settings.Set(pubSubSettings);

        connectionString = Environment.GetEnvironmentVariable("SqlServerTransportConnectionString");
        if (string.IsNullOrEmpty(connectionString))
        {
            connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
        }

        var logicalAddress = LogicalAddress.CreateLocalAddress(settings.ErrorQueueAddress(), new Dictionary <string, string>());
        var localAddress   = settings.EndpointName();
        return(new TransportConfigurationResult
        {
            TransportInfrastructure = new SqlServerTransportInfrastructure("nservicebus", settings, connectionString, () => localAddress, () => logicalAddress, false)
        });
    }
        public void SetUp()
        {
            var builder    = new NHibernateSagaStorage();
            var properties = SQLiteConfiguration.InMemory();

            var configuration = new Configuration().AddProperties(properties);
            var settings      = new SettingsHolder();

            var metaModel = new SagaMetadataCollection();
            var types     = new [] { typeof(TestSaga), typeof(TestSagaData), typeof(TestComponent), typeof(PolymorphicPropertyBase),
                                     typeof(AlsoDerivedFromTestSagaWithTableNameAttributeActualSaga), typeof(AlsoDerivedFromTestSagaWithTableNameAttribute),
                                     typeof(DerivedFromTestSagaWithTableNameAttributeActualSaga), typeof(DerivedFromTestSagaWithTableNameAttribute),
                                     typeof(TestSagaWithTableNameAttributeActualSaga), typeof(TestSagaWithTableNameAttribute),
                                     typeof(SagaWithVersionedPropertyAttributeActualSaga), typeof(SagaWithVersionedPropertyAttribute),
                                     typeof(SagaWithoutVersionedPropertyAttributeActualSaga), typeof(SagaWithoutVersionedPropertyAttribute),
                                     typeof(object) };

            metaModel.Initialize(types);
            settings.Set <SagaMetadataCollection>(metaModel);

            settings.Set("TypesToScan", types);
            builder.ApplyMappings(settings, configuration);
            sessionFactory = configuration.BuildSessionFactory() as SessionFactoryImpl;

            persisterForTestSaga = sessionFactory.GetEntityPersisterFor <TestSagaData>();
        }
    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
        });
    }
示例#12
0
        public async Task GetTopicArn_caches()
        {
            var settings = new SettingsHolder();

            settings.Set(SettingsKeys.TopicNamePrefix, "PREFIX");
            settings.Set(SettingsKeys.TopicNameGenerator, (Func <Type, string, string>)TopicNameGenerator);

            var configuration = new TransportConfiguration(settings);
            var snsClient     = new MockSnsClient();

            var metadataRegistry = settings.SetupMessageMetadataRegistry();

            var cache = new TopicCache(snsClient, metadataRegistry, configuration);

            await cache.GetTopicArn(typeof(Event));

            var requestsSent = new List <string>(snsClient.FindTopicRequests);

            snsClient.FindTopicRequests.Clear();

            await cache.GetTopicArn(typeof(Event));

            Assert.IsEmpty(snsClient.FindTopicRequests);
            CollectionAssert.AreEqual(new List <string> {
                "PREFIXEvent"
            }, requestsSent);
        }
示例#13
0
        public void It_can_try_to_obtain_the_error_queue_name_from_the_registry()
        {
            var settingsHolder = new SettingsHolder();

            settingsHolder.Set <IConfigurationSource>(new ConfigurationSource());
            settingsHolder.Set("TypesToScan", new List <Type>());
            Assert.Throws <ConfigurationErrorsException>(() => ErrorQueueSettings.GetConfiguredErrorQueue(settingsHolder));
        }
        private SettingsHolder DefaultSettings()
        {
            var settings = new SettingsHolder();

            settings.Set("NServiceBus.LocalAddress", "FakeAddress");
            settings.Set("EndpointVersion", "FakeVersion");
            settings.Set("NServiceBus.Routing.EndpointName", "FakeEndpoint");
            settings.Set <SingleSharedDocumentStore>(new SingleSharedDocumentStore());

            return(settings);
        }
        private SettingsHolder DefaultSettings()
        {
            var settings = new SettingsHolder();
            settings.Set("NServiceBus.LocalAddress", "FakeAddress");
            settings.Set("EndpointVersion", "FakeVersion");
            settings.SetDefault("Transactions.SuppressDistributedTransactions", false);
            settings.Set("NServiceBus.Routing.EndpointName", "FakeEndpoint");
            settings.Set<SingleSharedDocumentStore>(new SingleSharedDocumentStore());

            return settings;
        }
        public void Should_be_able_to_determine_if_delivery_constraint_is_supported()
        {
            var settings = new SettingsHolder();
            var fakeTransportDefinition = new FakeTransportDefinition();
            settings.Set<TransportDefinition>(fakeTransportDefinition);
            settings.Set<TransportInfrastructure>(fakeTransportDefinition.Initialize(settings, null));

            var context = new FeatureConfigurationContext(settings, null, null);
            var result = context.Settings.DoesTransportSupportConstraint<DeliveryConstraint>();
            Assert.IsTrue(result);
        }
        public void Should_allow_startup_if_EnableTimeoutManager_setting_is_not_set_and_timeout_manager_feature_is_disabled()
        {
            settings.Set(typeof(TimeoutManager).FullName, FeatureState.Disabled);

            var result = DelayInfrastructure.CheckForInvalidSettings(settings);

            Assert.True(result.Succeeded);
        }
示例#18
0
        public override TransportInfrastructure Initialize(SettingsHolder settings, string connectionString)
        {
            connectionString = connectionString.RemoveCustomSchemaPart(out var customSchema);

            if (customSchema != null)
            {
                settings.Set("SqlServer.DisableConnectionStringValidation", true);
                settings.Set("SqlServer.SchemaName", customSchema);
            }

            return(base.Initialize(settings, connectionString));
        }
        static IReadOnlySettings PrepareSettings(string endpointName = "DefaultEndpoint", string configuredStorageQueueName = null)
        {
            var settings = new SettingsHolder();

            settings.Set("NServiceBus.Routing.EndpointName", endpointName);

            if (!string.IsNullOrEmpty(configuredStorageQueueName))
            {
                settings.Set(MsmqSubscriptionStorageConfigurationExtensions.MsmqPersistenceQueueConfigurationKey, configuredStorageQueueName);
            }

            return(settings);
        }
        public void Should_be_able_to_determine_if_delivery_constraint_is_supported()
        {
            var settings = new SettingsHolder();
            var fakeTransportDefinition = new FakeTransportDefinition();

            settings.Set <TransportDefinition>(fakeTransportDefinition);
            settings.Set <TransportInfrastructure>(fakeTransportDefinition.Initialize(settings, null));

            var context = new FeatureConfigurationContext(settings, null, null, null);
            var result  = context.Settings.DoesTransportSupportConstraint <DeliveryConstraint>();

            Assert.IsTrue(result);
        }
        public void DoesntThrow_when_voron_combined_with_dtc_including_confirmation()
        {
            using (var documentStore = new DocumentStore { Url = "http://localhost:8083" })
            using (documentStore.SetupVoronTest())
            {

                var settings = new SettingsHolder();
                settings.Set<TransportInfrastructure>(new FakeRavenDBTransportInfrastructure(TransportTransactionMode.TransactionScope));
                settings.Set("RavenDB.IConfirmToUseAStorageEngineWhichDoesntSupportDtcWhilstLeavingDistributedTransactionSupportEnabled", true);

                Assert.DoesNotThrow(() => StorageEngineVerifier.VerifyStorageEngineSupportsDtcIfRequired(documentStore, settings));
            }
        }
    public XmlSerializerFacade(params Type[] objectTypes)
    {
        mapper = new MessageMapper();
        var settings    = new SettingsHolder();
        var conventions = CreateTestConventions(settings);

        // evil hack
        settings.Set <MessageMetadataRegistry>((MessageMetadataRegistry)Activator.CreateInstance(typeof(MessageMetadataRegistry), BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { conventions }, null));
        settings.Set <Conventions>(conventions);
        settings.Set("TypesToScan", objectTypes);

        serializer = new XmlSerializer().Configure(settings)(mapper);
        mapper.Initialize(objectTypes);
    }
示例#23
0
    public TransportConfigurationResult Configure(SettingsHolder settings, TransportTransactionMode transportTransactionMode)
    {
        this.settings = settings;
        settings.Set("NServiceBus.SharedQueue", settings.EndpointName());
        settings.Set <LogicalAddress>(LogicalAddress.CreateLocalAddress(settings.EndpointName(), new Dictionary <string, string>()));
        var delayedDeliverySettings = new DelayedDeliverySettings();

        delayedDeliverySettings.TableSuffix("Delayed");
        settings.Set <DelayedDeliverySettings>(delayedDeliverySettings);
        return(new TransportConfigurationResult
        {
            TransportInfrastructure = new SqlServerTransport().Initialize(settings, ConnectionString)
        });
    }
        public void Preserves_FifoQueue_WithPreTruncate(string destination, string expected)
        {
            var settings = new SettingsHolder();

            settings.Set(SettingsKeys.PreTruncateQueueNames, true);
            settings.Set(SettingsKeys.QueueNamePrefix, string.Empty);

            var configuration = new TransportConfiguration(settings);

            var result = QueueNameHelper.GetSqsQueueName(destination, configuration);

            Console.WriteLine(result);
            Assert.AreEqual(expected, result);
        }
示例#25
0
        public static void Init()
        {
            var config = Configure.Instance;

            var masterNodeAddress = config.GetMasterNodeAddress();

            var distributorControlAddress = masterNodeAddress.SubScope("distributor.control");

            var unicastBusConfig = Configure.GetConfigSection <UnicastBusConfig>();

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

            config.Configurer.ConfigureComponent <ReadyMessageSender>(DependencyLifecycle.SingleInstance)
            .ConfigureProperty(p => p.DistributorControlAddress, distributorControlAddress);

            Address.OverridePublicReturnAddress(distributorControlAddress);

            config.Configurer.ConfigureComponent <ReturnAddressRewriter>(
                DependencyLifecycle.SingleInstance)
            .ConfigureProperty(r => r.DistributorDataAddress, masterNodeAddress);

            SettingsHolder.Set("Worker.Enabled", true);
            SettingsHolder.Set("Distributor.Version", 1);
            SettingsHolder.Set("MasterNode.Address", masterNodeAddress);
        }
示例#26
0
    public static SettingsHolder BuildWithSerializer()
    {
        var settings = new SettingsHolder();

        settings.Set(WellKnownConfigurationKeys.Core.MainSerializerSettingsKey, Tuple.Create <SerializationDefinition, SettingsHolder>(new XmlSerializer(), settings));
        return(settings);
    }
示例#27
0
        /// <summary>
        ///  Register a explicit service provider
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configAction"></param>
        public static void RegisterServiceFor <T>(Action configAction)
        {
            var serviceType = typeof(T);

            SettingsHolder.Set <T>(configAction);
            Logger.InfoFormat("Explicit provider for infrastructure service {0} has been set to custom action", serviceType.FullName);
        }
        public async Task Should_not_throw_if_user_provided_a_custom_namespace_manager()
        {
            var settings = new SettingsHolder();

            var namespaces = new NamespaceConfigurations
            {
                { "name1", ConnectionStringValue.Build("namespace1"), NamespacePurpose.Partitioning },
                { "name2", ConnectionStringValue.Build("namespace2"), NamespacePurpose.Partitioning }
            };

            settings.Set(WellKnownConfigurationKeys.Topology.Addressing.Namespaces, namespaces);

#pragma warning disable 618
            var namespaceManager = A.Fake <INamespaceManager>();
#pragma warning restore 618
            A.CallTo(() => namespaceManager.CanManageEntities()).Returns(Task.FromResult(true));
#pragma warning disable 618
            var manageNamespaceLifeCycle = A.Fake <IManageNamespaceManagerLifeCycle>();
#pragma warning restore 618
            A.CallTo(() => manageNamespaceLifeCycle.Get(A <string> .Ignored)).Returns(namespaceManager);

            var namespaceBundleConfigurations = await NumberOfTopicsInBundleCheck.Run(manageNamespaceLifeCycle, namespaces, "bundle");

            Assert.That(namespaceBundleConfigurations.Count(), Is.Zero);
        }
        public RabbitMQTransportInfrastructure(SettingsHolder settings, string connectionString)
        {
            this.settings = settings;

            var connectionConfiguration = ConnectionConfiguration.Create(connectionString, settings.EndpointName());

            X509CertificateCollection clientCertificates;

            settings.TryGet(SettingsKeys.ClientCertificates, out clientCertificates);
            connectionFactory = new ConnectionFactory(connectionConfiguration, clientCertificates);

            routingTopology = CreateRoutingTopology();

            routingTopologySupportsDelayedDelivery = routingTopology is ISupportDelayedDelivery;
            settings.Set(SettingsKeys.RoutingTopologySupportsDelayedDelivery, routingTopologySupportsDelayedDelivery);

            bool usePublisherConfirms;

            if (!settings.TryGet(SettingsKeys.UsePublisherConfirms, out usePublisherConfirms))
            {
                usePublisherConfirms = true;
            }

            settings.TryGet(SettingsKeys.DisableTimeoutManager, out disableTimeoutManager);

            bool allEndpointsSupportDelayedDelivery;

            settings.TryGet(SettingsKeys.AllEndpointsSupportDelayedDelivery, out allEndpointsSupportDelayedDelivery);

            channelProvider = new ChannelProvider(connectionFactory, routingTopology, usePublisherConfirms, allEndpointsSupportDelayedDelivery);

            RequireOutboxConsent = false;
        }
示例#30
0
        public async Task Should_namespaces_that_dont_have_manage_rights()
        {
            var settings = new SettingsHolder();

            var namespaces = new NamespaceConfigurations
            {
                { "name1", ConnectionStringValue.Build("namespace1"), NamespacePurpose.Partitioning },
                { "name2", ConnectionStringValue.Build("namespace2"), NamespacePurpose.Partitioning }
            };

            settings.Set(WellKnownConfigurationKeys.Topology.Addressing.Namespaces, namespaces);

            var trueNamespaceManager = A.Fake <INamespaceManager>();

            A.CallTo(() => trueNamespaceManager.CanManageEntities()).Returns(Task.FromResult(true));
            var falseNamespaceManager = A.Fake <INamespaceManager>();

            A.CallTo(() => falseNamespaceManager.CanManageEntities()).Returns(Task.FromResult(false));
            var manageNamespaceLifeCycle = A.Fake <IManageNamespaceManagerLifeCycle>();

            A.CallTo(() => manageNamespaceLifeCycle.Get("name1")).Returns(trueNamespaceManager);
            A.CallTo(() => manageNamespaceLifeCycle.Get("name2")).Returns(falseNamespaceManager);

            var result = await ManageRightsCheck.Run(manageNamespaceLifeCycle, settings);

            CollectionAssert.Contains(result, "name2");
            CollectionAssert.DoesNotContain(result, "name1");
        }
示例#31
0
        public async Task Should_only_count_topics_following_bundle_pattern()
        {
            var bundlePrefix = $"bundle{DateTime.Now.Ticks}-";

            nonBundledTopic = $"{bundlePrefix}x";

            namespaceManager = new NamespaceManagerAdapterInternal(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value), AzureServiceBusConnectionString.Value);

            try
            {
                await namespaceManager.CreateTopic(new TopicDescription(nonBundledTopic));
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // ignore if topic already exists
            }

            var settings = new SettingsHolder();
            var namespaceConfigurations = new NamespaceConfigurations();
            var namespaceAlias          = "namespace1";

            namespaceConfigurations.Add(namespaceAlias, AzureServiceBusConnectionString.Value, NamespacePurpose.Routing);
            settings.Set(WellKnownConfigurationKeys.Topology.Addressing.Namespaces, namespaceConfigurations);

            var result = await NumberOfTopicsInBundleCheck.Run(new NamespaceManagerLifeCycleManagerInternal(new NamespaceManagerCreator(settings)), namespaceConfigurations, bundlePrefix);

            Assert.AreEqual(0, result.GetNumberOfTopicInBundle(namespaceAlias));
        }
示例#32
0
        /// <summary>
        /// Register a explicit service provider
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="providerType"></param>
        /// <param name="dependencyLifecycle"></param>
        public static void RegisterServiceFor <T>(Type providerType, DependencyLifecycle dependencyLifecycle)
        {
            var serviceType = typeof(T);

            SettingsHolder.Set <T>(() => Configure.Component(providerType, dependencyLifecycle));
            Logger.InfoFormat("Explicit provider for infrastructure service {0} has been set to {1}, lifecycle: {2}", serviceType.FullName, providerType.FullName, dependencyLifecycle);
        }
示例#33
0
        public void Run(SettingsHolder settings)
        {
            List <EnabledPersistence> definitions;

            if (!settings.TryGet("PersistenceDefinitions", out definitions))
            {
                return;
            }

            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);
        }
示例#34
0
            public Configuration(SettingsHolder settings)
            {
                this.settings = settings;

                settings.SetDefault(TransportConnectionString.Default);
                settings.Set(new QueueBindings());
            }
        public void GetConnectionUsingSettingsFromConnectionString()
        {
            var settings = new SettingsHolder();
            settings.Set(MongoPersistenceConstants.ConnectionStringKey, "mongodb://ultratinef:27017");
            var readonlySettings = (ReadOnlySettings)settings;

            var result = MongoHelpers.GetConnectionString(readonlySettings);
            result.Should().Be("mongodb://ultratinef:27017");
        }
 public void Throws_when_voron_combined_with_dtc()
 {
     using (var documentStore = new DocumentStore { Url = "http://localhost:8083" })
     using (documentStore.SetupVoronTest())
     {
         var settings = new SettingsHolder();
         settings.Set<TransportInfrastructure>(new FakeRavenDBTransportInfrastructure(TransportTransactionMode.TransactionScope));
         Assert.Throws<InvalidOperationException>(() => StorageEngineVerifier.VerifyStorageEngineSupportsDtcIfRequired(documentStore, settings));
     }
 }
        public void SetUp()
        {
            var builder = new NHibernateSagaStorage();
            var properties = SQLiteConfiguration.InMemory();

            var configuration = new Configuration().AddProperties(properties);
            var settings = new SettingsHolder();
            settings.Set("TypesToScan", new[] { typeof(SagaWithAbstractBaseClass), typeof(ContainSagaData), typeof(MyOwnAbstractBase) });
            builder.ApplyMappings(settings, configuration);
            sessionFactory = configuration.BuildSessionFactory() as SessionFactoryImpl;
        }
示例#38
0
        /// <summary>
        /// Initializes the transport infrastructure for msmq.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>the transport infrastructure for msmq.</returns>
        public override TransportInfrastructure Initialize(SettingsHolder settings, string connectionString)
        {
            settings.EnableFeature(typeof(InstanceMappingFileFeature));

            var msmqSettings = connectionString != null ? new MsmqConnectionStringBuilder(connectionString)
                .RetrieveSettings() : new MsmqSettings();

            settings.Set<MsmqSettings>(msmqSettings);

            return new MsmqTransportInfrastructure(settings);
        }
        public void Should_throw_if_class_is_derived()
        {
            var builder = new NHibernateSagaStorage();
            var properties = SQLiteConfiguration.InMemory();

            var configuration = new Configuration().AddProperties(properties);
            var settings = new SettingsHolder();
            settings.Set("TypesToScan", new[] { typeof(MyDerivedClassWithRowVersion) });
            
            Assert.Throws<MappingException>(() => builder.ApplyMappings(settings, configuration));
        }
        public void Should_generate_a_guid_only_based_name_for_machine_name_over_14_characters()
        {
            RuntimeEnvironment.MachineNameAction = () => "DEVMACHINENAME";
            const string endpointName = "When_determining_subscription_name_for_scaled_out_endpoint";
            var eventType = typeof(SomeEventWithAnInsanelyLongName);
            var settings = new SettingsHolder();
            settings.Set("ScaleOut.UseSingleBrokerQueue", false);
            var subscriptionName = NamingConventions.SubscriptionNamingConvention(settings, eventType, endpointName);

            Guid guid;
            Assert.IsTrue(Guid.TryParse(subscriptionName, out guid), "expected to have a guid, but got: " + subscriptionName);
        }
        public void DoesntThrow_when_voron_without_dtc()
        {
            using (var documentStore = new DocumentStore { Url = "http://localhost:8083" })
            using (documentStore.SetupVoronTest())
            {
                var settings = new SettingsHolder();
                settings.Set<TransportInfrastructure>(new FakeRavenDBTransportInfrastructure(TransportTransactionMode.ReceiveOnly));

                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                Assert.DoesNotThrow(() => StorageEngineVerifier.VerifyStorageEngineSupportsDtcIfRequired(documentStore, settings));
            }
        }
        public void Throws_when_voron_combined_with_dtc()
        {
            using (var documentStore = new DocumentStore { Url = "http://localhost:8083" })
            using (documentStore.SetupVoronTest())
            {

                var settings = new SettingsHolder();
                settings.Set("Transactions.SuppressDistributedTransactions", false);

                Assert.Throws<InvalidOperationException>(() => StorageEngineVerifier.VerifyStorageEngineSupportsDtcIfRequired(documentStore, settings));
            }
        }
        public void DoesntThrow_when_voron_without_dtc()
        {
            using (var documentStore = new DocumentStore { Url = "http://localhost:8083" })
            using (documentStore.SetupVoronTest())
            {
                var settings = new SettingsHolder();
                settings.Set("Transactions.SuppressDistributedTransactions", true);

                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                Assert.DoesNotThrow(() => StorageEngineVerifier.VerifyStorageEngineSupportsDtcIfRequired(documentStore, settings));
            }
        }
        public void ShouldUseExplicitValueInSettingsIfPresent()
        {
            string address;
            var settingsHolder = new SettingsHolder();

            settingsHolder.Set<AuditConfigReader.Result>(new AuditConfigReader.Result
            {
                Address = "myAuditQueue"
            });

            Assert.True(AuditConfigReader.TryGetAuditQueueAddress(settingsHolder, out address));
            Assert.AreEqual("myAuditQueue", address);
        }
        public static SessionFactoryImpl Build()
        {
            var types = Types();

            var builder = new NHibernateSagaStorage();
            var properties = SQLiteConfiguration.InMemory();

            var configuration = new Configuration().AddProperties(properties);
            var settings = new SettingsHolder();
            settings.Set("TypesToScan", types);
            builder.ApplyMappings(settings, configuration);
            return configuration.BuildSessionFactory() as SessionFactoryImpl;
        }
        public void Specific_stores_should_mask_default()
        {
            var settings = new SettingsHolder();
            settings.Set("Transactions.SuppressDistributedTransactions", true);
            settings.Set("TypesToScan", new Type[0]);
            settings.Set("NServiceBus.Routing.EndpointName", "FakeEndpoint");
            settings.Set("NServiceBus.Transport.TransportInfrastructure", new FakeRavenDBTransportInfrastructure(TransportTransactionMode.None));
            
            DocumentStoreManager.SetDocumentStore<StorageType.GatewayDeduplication>(settings, EmbeddedStore("GatewayDeduplication"));
            DocumentStoreManager.SetDocumentStore<StorageType.Outbox>(settings, EmbeddedStore("Outbox"));
            DocumentStoreManager.SetDocumentStore<StorageType.Sagas>(settings, EmbeddedStore("Sagas"));
            DocumentStoreManager.SetDocumentStore<StorageType.Subscriptions>(settings, EmbeddedStore("Subscriptions"));
            DocumentStoreManager.SetDocumentStore<StorageType.Timeouts>(settings, EmbeddedStore("Timeouts"));
            DocumentStoreManager.SetDefaultStore(settings, EmbeddedStore("Default"));

            var readOnly = settings as ReadOnlySettings;

            Assert.AreEqual("GatewayDeduplication", DocumentStoreManager.GetDocumentStore<StorageType.GatewayDeduplication>(readOnly).Identifier);
            Assert.AreEqual("Outbox", DocumentStoreManager.GetDocumentStore<StorageType.Outbox>(readOnly).Identifier);
            Assert.AreEqual("Sagas", DocumentStoreManager.GetDocumentStore<StorageType.Sagas>(readOnly).Identifier);
            Assert.AreEqual("Subscriptions", DocumentStoreManager.GetDocumentStore<StorageType.Subscriptions>(readOnly).Identifier);
            Assert.AreEqual("Timeouts", DocumentStoreManager.GetDocumentStore<StorageType.Timeouts>(readOnly).Identifier);
        }
        public void Should_generate_a_guid_based_name_with_individualizer_suffix_for_machine_name_under_14_characters()
        {
            RuntimeEnvironment.MachineNameAction = () => "DEV";
            const string endpointName = "When_determining_subscription_name_for_scaled_out_endpoint";
            var eventType = typeof(SomeEventWithAnInsanelyLongName);
            var settings = new SettingsHolder();
            settings.Set("ScaleOut.UseSingleBrokerQueue", false);
            var subscriptionName = NamingConventions.SubscriptionNamingConvention(settings, eventType, endpointName);

            Assert.True(subscriptionName.Length <= 50);
            Assert.True(subscriptionName.EndsWith("-" + RuntimeEnvironment.MachineName), "expected subscription name to end with machine name, but it didn't. Subscription name: " + subscriptionName + " machine name: " + Environment.MachineName);

            Guid guid;
            Assert.IsTrue(Guid.TryParse(subscriptionName.Substring(0, 36), out guid), "expected to have a guid, but got: " + subscriptionName);
        }
        public void Last_customize_delegate_wins()
        {
            var settings = new SettingsHolder();
            settings.Set("Transactions.SuppressDistributedTransactions", true);

            DocumentStoreManager.SetCustomizeDocumentStoreDelegate(settings, ds => ds.Identifier += "FirstDelegate");
            DocumentStoreManager.SetCustomizeDocumentStoreDelegate(settings, ds => ds.Identifier += "SecondDelegate");

            DocumentStoreManager.SetDefaultStore(settings, EmbeddedStore("Default"));
            DocumentStoreManager.SetDocumentStore<StorageType.Outbox>(settings, EmbeddedStore("Outbox"));

            var readOnly = settings as ReadOnlySettings;

            Assert.AreEqual("DefaultSecondDelegate", DocumentStoreManager.GetDocumentStore<StorageType.Sagas>(readOnly).Identifier);
            Assert.AreEqual("OutboxSecondDelegate", DocumentStoreManager.GetDocumentStore<StorageType.Outbox>(readOnly).Identifier);
        }
        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 Specific_stores_should_mask_default()
        {
            var settings = new SettingsHolder();
            settings.Set("Transactions.SuppressDistributedTransactions", true);

            DocumentStoreManager.SetDocumentStore<StorageType.GatewayDeduplication>(settings, EmbeddedStore("GatewayDeduplication"));
            DocumentStoreManager.SetDocumentStore<StorageType.Outbox>(settings, EmbeddedStore("Outbox"));
            DocumentStoreManager.SetDocumentStore<StorageType.Sagas>(settings, EmbeddedStore("Sagas"));
            DocumentStoreManager.SetDocumentStore<StorageType.Subscriptions>(settings, EmbeddedStore("Subscriptions"));
            DocumentStoreManager.SetDocumentStore<StorageType.Timeouts>(settings, EmbeddedStore("Timeouts"));
            DocumentStoreManager.SetDefaultStore(settings, EmbeddedStore("Default"));

            var readOnly = settings as ReadOnlySettings;

            Assert.AreEqual("GatewayDeduplication", DocumentStoreManager.GetDocumentStore<StorageType.GatewayDeduplication>(readOnly).Identifier);
            Assert.AreEqual("Outbox", DocumentStoreManager.GetDocumentStore<StorageType.Outbox>(readOnly).Identifier);
            Assert.AreEqual("Sagas", DocumentStoreManager.GetDocumentStore<StorageType.Sagas>(readOnly).Identifier);
            Assert.AreEqual("Subscriptions", DocumentStoreManager.GetDocumentStore<StorageType.Subscriptions>(readOnly).Identifier);
            Assert.AreEqual("Timeouts", DocumentStoreManager.GetDocumentStore<StorageType.Timeouts>(readOnly).Identifier);
        }
 public void Run(SettingsHolder settings)
 {
     // update config instance
     settings.Set("key", "value");
     // after this config.Settings will be frozen
 }
 public void Init()
 {
     settings = new SettingsHolder();
     settings.Set<TransportDefinition>(new MsmqTransport());
     featureSettings = new FeatureActivator(settings);
 }