Example #1
0
        static void Main(string[] args)
        {
            Bus bus = new BusBuilder().Build();

            bus.Connect();

            bool readingInput = true;

            while (readingInput)
            {
                Console.WriteLine("Press enter to publish a message or 'X' to exit");

                var keyInfo = Console.ReadKey();

                switch (keyInfo.Key)
                {
                case ConsoleKey.Enter:
                    string messageText = "Hello, World";
                    bus.Publish(new Message(messageText));
                    Console.WriteLine("Published message: {0}", messageText);
                    break;

                case ConsoleKey.X:
                    readingInput = false;
                    break;
                }
            }

            bus.Close();
        }
        public static BusBuilder RegisterSaga(this BusBuilder busBuilder, Type sagaType, FinderList sagaFinders)
        {
            var sagaInterfaces = sagaType.GetTypeInfo().ImplementedInterfaces
                                 .Where(x => x == typeof(ISaga))
                                 .ToList();

            if (!sagaInterfaces.Any())
            {
                throw new ArgumentException("Type must implement ISaga", nameof(sagaType));
            }
            if (sagaInterfaces.Count > 1)
            {
                throw new ArgumentException("A Saga can only implement ISaga once", nameof(sagaType));
            }

            var eventTypes = sagaType.GetTypeInfo().ImplementedInterfaces
                             .Where(x => x.GetTypeInfo().IsGenericType&& x.GetGenericTypeDefinition() == typeof(IEventHandler <>))
                             .Select(x => x.GenericTypeArguments.First());

            foreach (var eventType in eventTypes)
            {
                busBuilder = busBuilder.RegisterMessage(
                    new HandlerRegistration(eventType, typeof(SagaRunnerEventHandler <,>).MakeGenericType(sagaType, eventType),
                                            new Type[] { sagaType }.Concat(sagaFinders).ToArray()
                                            )
                    );
            }

            return(busBuilder);
        }
        public BusBuilder Configure(BusBuilder builder)
        {
            builder.Match <ServiceBusBuilder>(x =>
            {
                var settings = new ServiceBusSettings(builder.Settings);

                settings.InputAddress = _uri ?? builder.Settings.InputAddress.AppendToPath("_control");

                // the endpoint factory is already created, so we can't set the endpoint here
                // we really need this to be part of another step, but i don't have a clue how yet.
                //_configurator.ConfigureEndpoint(_uri, x => x.PurgeExistingMessages());

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Configuring control bus for {0} at {1}", builder.Settings.InputAddress, settings.InputAddress);
                }

                settings.ConcurrentConsumerLimit = 1;
                settings.ConcurrentReceiverLimit = 1;
                settings.AutoStart = true;

                BusBuilder controlBusBuilder = new ControlBusBuilderImpl(settings);

                controlBusBuilder = _configurators
                                    .Aggregate(controlBusBuilder, (current, configurator) => configurator.Configure(current));

                IControlBus controlBus = controlBusBuilder.Build();

                x.UseControlBus(controlBus);
            });

            return(builder);
        }
Example #4
0
 private static BusBuilder SubscribeEvents(this BusBuilder busBuilder)
 => busBuilder.SubscribeToEvent <UsernameChanged>()
 .SubscribeToEvent <ChangeUsernameRejected>()
 .SubscribeToEvent <AvatarUploaded>()
 .SubscribeToEvent <UploadAvatarRejected>()
 .SubscribeToEvent <AvatarRemoved>()
 .SubscribeToEvent <RemoveAvatarRejected>()
 .SubscribeToEvent <PasswordChanged>()
 .SubscribeToEvent <ResetPasswordInitiated>()
 .SubscribeToEvent <NewPasswordSet>()
 .SubscribeToEvent <ChangePasswordRejected>()
 .SubscribeToEvent <ResetPasswordRejected>()
 .SubscribeToEvent <SetNewPasswordRejected>()
 .SubscribeToEvent <SignedIn>()
 .SubscribeToEvent <SignedUp>()
 .SubscribeToEvent <SignedOut>()
 .SubscribeToEvent <SignInRejected>()
 .SubscribeToEvent <SignUpRejected>()
 .SubscribeToEvent <SignOutRejected>()
 .SubscribeToEvent <MessageOnFacebookWallPosted>()
 .SubscribeToEvent <PostOnFacebookWallRejected>()
 .SubscribeToEvent <UserNotificationSettingsUpdated>()
 .SubscribeToEvent <UpdateUserNotificationSettingsRejected>()
 .SubscribeToEvent <AccountDeleted>()
 .SubscribeToEvent <DeleteAccountRejected>()
 .SubscribeToEvent <ActivateAccountInitiated>()
 .SubscribeToEvent <AccountActivated>()
 .SubscribeToEvent <ActivateAccountRejected>()
 .SubscribeToEvent <AccountLocked>()
 .SubscribeToEvent <LockAccountRejected>()
 .SubscribeToEvent <AccountUnlocked>()
 .SubscribeToEvent <UnlockAccountRejected>();
        private const int _expectedTotalCallCount = 11; // 5 interceptors * 2 + 1 handler

        protected override async Task <IBus> Given()
        {
            MethodCallCounter.Clear();

            var testFixtureType = GetType();
            var typeProvider    = new TestHarnessTypeProvider(new[] { testFixtureType.Assembly }, new[] { testFixtureType.Namespace });
            var logger          = TestHarnessLoggerFactory.Create();

            var bus = new BusBuilder().Configure()
                      .WithTransport(new InProcessTransportConfiguration())
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithTypesFrom(typeProvider)
                      .WithDependencyResolver(new DependencyResolver(typeProvider))
                      .WithDefaultTimeout(TimeSpan.FromSeconds(TimeoutSeconds))
                      .WithMaxDeliveryAttempts(1)
                      .WithGlobalInboundInterceptorTypes(typeof(SomeGlobalInterceptor))
                      .WithLogger(logger)
                      .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start();

            return(bus);
        }
Example #6
0
        public async Task StartingASaga()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <CallTracker>().AsSelf().SingleInstance();

            builder.RegisterType <TestSagaRepository>().AsSelf().AsImplementedInterfaces().SingleInstance();

            var busBuilder = new BusBuilder()
                             .RegisterSaga <TestSaga>(FinderList.Empty.AddSagaFinder <CorrelationIdSagaFinder>());

            var container = builder
                            .RegisterMicroBus(busBuilder)
                            .Build();

            var bus = container.Resolve <IMicroBus>();

            await bus.PublishAsync(new SagaStartingAEvent()
            {
                CorrelationId = id
            });

            await bus.PublishAsync(new SagaEndingEvent()
            {
                CorrelationId = id
            });

            var tracker = container.Resolve <CallTracker>();

            tracker.Count.Should().Be(2);
        }
Example #7
0
        public IServiceBus CreateServiceBus()
        {
            _log.InfoFormat("MassTransit v{0}, .NET Framework v{1}",
                            typeof(ServiceBusFactory).Assembly.GetName().Version,
                            Environment.Version);

            IEndpointCache endpointCache = CreateEndpointCache();

            _settings.EndpointCache = endpointCache;

            BusBuilder builder = _builderFactory(_settings);

            _subscriptionRouterConfigurator.SetNetwork(_settings.Network);

            // run through all configurators that have been set and let
            // them do their magic
            foreach (BusBuilderConfigurator configurator in _configurators)
            {
                builder = configurator.Configure(builder);
            }

            IServiceBus bus = builder.Build();

            return(bus);
        }
        public async Task WhenPublishTopicClientOrQueueClientIsCreatedForTopicNameOrQueueName()
        {
            // arrange
            BusBuilder.Produce <SomeMessage>(x => x.ToTopic());
            BusBuilder.Produce <OtherMessage>(x => x.ToQueue());

            var sm1 = new SomeMessage {
                Id = "1", Value = 10
            };
            var sm2 = new SomeMessage {
                Id = "2", Value = 12
            };
            var om1 = new OtherMessage {
                Id = "1"
            };
            var om2 = new OtherMessage {
                Id = "2"
            };

            // act
            await ProviderBus.Value.Publish(sm1, "some-topic").ConfigureAwait(false);

            await ProviderBus.Value.Publish(sm2, "some-topic").ConfigureAwait(false);

            await ProviderBus.Value.Publish(om1, "some-queue").ConfigureAwait(false);

            await ProviderBus.Value.Publish(om2, "some-queue").ConfigureAwait(false);

            // assert
            TopicClientMockByName.Should().ContainKey("some-topic");
            TopicClientMockByName.Should().HaveCount(1);
            QueueClientMockByName.Should().ContainKey("some-queue");
            QueueClientMockByName.Should().HaveCount(1);
        }
        public async Task WhenPublishGivenModifierConfiguredForMessageTypeThenModifierExecuted()
        {
            // arrange
            BusBuilder.Produce <SomeMessage>(x =>
            {
                x.DefaultTopic("default-topic");
                x.WithModifier((message, sbMessage) =>
                {
                    sbMessage.MessageId    = message.Id;
                    sbMessage.PartitionKey = (message.Value % 2).ToString(CultureInfo.InvariantCulture);
                });
            });

            var m1 = new SomeMessage {
                Id = "1", Value = 10
            };
            var m2 = new SomeMessage {
                Id = "2", Value = 3
            };

            // act
            await ProviderBus.Value.Publish(m1).ConfigureAwait(false);

            await ProviderBus.Value.Publish(m2).ConfigureAwait(false);

            // assert
            var topicClient = TopicClientMockByName["default-topic"];

            topicClient.Verify(x => x.SendAsync(It.Is <Message>(m => m.MessageId == "1" && m.PartitionKey == "0")), Times.Once);
            topicClient.Verify(x => x.SendAsync(It.Is <Message>(m => m.MessageId == "2" && m.PartitionKey == "1")), Times.Once);
        }
Example #10
0
        public async Task ItShouldGoBangQuickly()
        {
            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });
            var logger       = TestHarnessLoggerFactory.Create(Guid.NewGuid(), GetType().FullName);

            using (
                var bus = new BusBuilder().Configure()
                          .WithDefaults(typeProvider)
                          .WithTransport(new AzureServiceBusTransportConfiguration()
                                         .WithConnectionString(
                                             @"Endpoint=sb://shouldnotexist.example.com/;SharedAccessKeyName=IntegrationTestHarness;SharedAccessKey=borkborkbork=")
                                         )
                          .WithNames("IntegrationTestHarness", Environment.MachineName)
                          .WithDefaultTimeout(TimeSpan.FromSeconds(TimeoutSeconds >> 1))
                          .WithLogger(logger)
                          .Build())
            {
                try
                {
                    await bus.Start();

                    Assert.Fail();
                }
                catch (Exception e)
                {
                    e.ShouldBeTypeOf <BusException>();
                }
            }
        }
Example #11
0
        private static void SetUpBus(IUnityContainer container)
        {
            //TODO: Set up your own connection string in app.config
            var connectionString = ConfigurationManager.AppSettings["AzureConnectionString"];

            // You'll want a logger. There's a ConsoleLogger and a NullLogger if you really don't care. You can roll your
            // own by implementing the ILogger interface if you want to hook it to an existing logging implementation.
            container.RegisterType <ILogger, ConsoleLogger>();

            // This is how you tell Nimbus where to find all your message types and handlers.
            var typeProvider = new AssemblyScanningTypeProvider(Assembly.GetExecutingAssembly());

            var bus = new BusBuilder().Configure()
                      .WithTransport(new WindowsServiceBusTransportConfiguration()
                                     .WithConnectionString(connectionString))
                      .WithNames("PingPong.Unity", Environment.MachineName)
                      .WithTypesFrom(typeProvider)
                      .WithDefaultTimeout(TimeSpan.FromSeconds(5))
                      .WithUnityDependencyResolver(typeProvider, container)
                      .Build();

            bus.Start().Wait();

            container.RegisterInstance <IBus>(bus);
        }
        public async Task SagaWithTwoStarters()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <TestSagaRepository>().AsImplementedInterfaces().SingleInstance();

            var busBuilder = new BusBuilder()
                             .RegisterSaga <TestSaga>();

            var container = builder
                            .RegisterMicroBus(busBuilder)
                            .Build();

            var bus = container.Resolve <IMicroBus>();

            await bus.PublishAsync(new SagaStartingBEvent()
            {
                CorrelationId = id
            });

            await bus.PublishAsync(new SagaStartingAEvent()
            {
                CorrelationId = id
            });

            await bus.PublishAsync(new SagaEndingEvent()
            {
                CorrelationId = id
            });
        }
Example #13
0
        public void RegisterASingleCommandHandlerShouldReturnOneRegistration()
        {
            var register = new BusBuilder()
                           .RegisterCommandHandler <CommandB, CommandBHandler>();

            register.MessageHandlerRegistrations.Count.Should().Be(1);
        }
Example #14
0
        static void SendAutoDistributeDemo()
        {
            // demonstrate distributing messages evenly across queues
            // each call to Send chooses the next queue to send the message to

            IBus bus = new BusBuilder()
                       .WithLogging(new FileLogger())
                       .InstallMsmqIfNeeded()
                       .DefineErrorQueue("MiniBus.errors")
                       .DefineWriteQueue("MiniBus.messages1")
                       .DefineWriteQueue("MiniBus.messages2")
                       .DefineWriteQueue("MiniBus.messages3")
                       .CreateLocalQueuesAutomatically()
                       .AutoDistributeOnSend()
                       .JsonSerialization()
                       .CreateBus();

            var p = new Person {
                Name = "Bob", Age = 20
            };

            bus.Send(p); // MiniBus.messages1
            bus.Send(p); // MiniBus.messages2
            bus.Send(p); // MiniBus.messages3
            bus.Send(p); // MiniBus.messages1

            Console.WriteLine("\nPress a key to exit");
            Console.ReadLine();
            bus.Dispose();
        }
Example #15
0
        static void Main(string[] args)
        {
            Bus bus = new BusBuilder().Configure(ctx => ctx.WithDefaultSerializationStrategy(new JsonSerializationStrategy())).Build();

            bus.Connect();

            bool readingInput = true;

            while (readingInput)
            {
                Console.WriteLine("Press enter to publish a message or 'X' to exit");

                var keyInfo = Console.ReadKey();

                switch (keyInfo.Key)
                {
                case ConsoleKey.Enter:
                    bus.Publish(new StatusMessage("This is a test."));
                    break;

                case ConsoleKey.X:
                    readingInput = false;
                    break;
                }
            }

            bus.Close();
        }
Example #16
0
        private async Task ClearMeABus()
        {
            // Filter types we care about to only our own test's namespace. It's a performance optimisation because creating and
            // deleting queues and topics is slow.
            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { "Some.Namespace.That.Does.Not.Exist" });

            var logger = TestHarnessLoggerFactory.Create();

            var busBuilder = new BusBuilder().Configure()
                             .WithNames("IntegrationTestHarness", Environment.MachineName)
                             .WithConnectionString(CommonResources.ServiceBusConnectionString)
                             .WithTypesFrom(typeProvider)
                             .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                             .WithLogger(logger)
                             .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
            ;

            using (var bus = busBuilder.Build())
            {
                await bus.Start();
            }
        }
Example #17
0
        public async Task <Bus> CreateAndStart()
        {
            var logger = TestHarnessLoggerFactory.Create();
            //var logger = new NullLogger();

            // Filter types we care about to only our own test's namespace. It's a performance optimisation because creating and
            // deleting queues and topics is slow.
            var typeProvider = new TestHarnessTypeProvider(new[] { _testFixtureType.Assembly }, new[] { _testFixtureType.Namespace });

            var bus = new BusBuilder().Configure()
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(typeProvider)
                      .WithGlobalInboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IInboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithGlobalOutboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IOutboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithDependencyResolver(new DependencyResolver(typeProvider))
                      .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                      .WithHeartbeatInterval(TimeSpan.MaxValue)
                      .WithLogger(logger)
                      .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start(MessagePumpTypes.All);

            return(bus);
        }
        protected override async Task <Bus> Given()
        {
            _largeMessageBodyTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString());

            _fakeHandler        = new FakeHandler(NumMessagesToSend);
            _dependencyResolver = new FakeDependencyResolver(_fakeHandler);
            _timeout            = TimeSpan.FromSeconds(300); //FIXME set to 30 seconds
            _typeProvider       = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });

            _logger = TestHarnessLoggerFactory.Create();
            //_logger = new NullLogger();

            var largeMessageBodyStorage = new FileSystemStorageBuilder().Configure()
                                          .WithStorageDirectory(_largeMessageBodyTempPath)
                                          .WithLogger(_logger)
                                          .Build();

            var bus = new BusBuilder().Configure()
                      .WithNames("ThroughputTestSuite", Environment.MachineName)
                      .WithLogger(_logger)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(_typeProvider)
                      .WithDependencyResolver(_dependencyResolver)
                      .WithLargeMessageStorage(c => c.WithLargeMessageBodyStore(largeMessageBodyStorage)
                                               .WithMaxSmallMessageSize(4096))
                      .WithDebugOptions(dc => dc.RemoveAllExistingNamespaceElementsOnStartup(
                                            "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start();

            return(bus);
        }
Example #19
0
        private async Task ClearMeABus(IConfigurationScenario <TransportConfiguration> scenario)
        {
            using (var instance = scenario.CreateInstance())
            {
                // We want a namespace that doesn't exist here so that all the queues and topics are removed.
                var typeProvider           = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { "Some.Namespace.That.Does.Not.Exist" });
                var transportConfiguration = instance.Configuration;

                var busBuilder = new BusBuilder().Configure()
                                 .WithTransport(transportConfiguration)
                                 .WithRouter(new DestinationPerMessageTypeRouter())
                                 .WithSerializer(new JsonSerializer())
                                 .WithDeliveryRetryStrategy(new ImmediateRetryDeliveryStrategy())
                                 .WithDependencyResolver(new DependencyResolver(typeProvider))
                                 .WithNames("MyTestSuite", Environment.MachineName)
                                 .WithTypesFrom(typeProvider)
                                 .WithDefaultTimeout(TimeSpan.FromSeconds(TimeoutSeconds))
                                 .WithHeartbeatInterval(TimeSpan.MaxValue)
                                 .WithLogger(_logger)
                                 .WithDebugOptions(
                    dc =>
                    dc.RemoveAllExistingNamespaceElementsOnStartup(
                        "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                ;

                using (var bus = busBuilder.Build())
                {
                    await bus.Start();

                    await bus.Stop();
                }
            }
        }
Example #20
0
        private async Task <Bus> BuildMeABus(IConfigurationScenario <TransportConfiguration> scenario)
        {
            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });

            using (var instance = scenario.CreateInstance())
            {
                var transportConfiguration = instance.Configuration;

                var configuration = new BusBuilder().Configure()
                                    .WithTransport(transportConfiguration)
                                    .WithRouter(new DestinationPerMessageTypeRouter())
                                    .WithSerializer(new JsonSerializer())
                                    .WithDeliveryRetryStrategy(new ImmediateRetryDeliveryStrategy())
                                    .WithDependencyResolver(new DependencyResolver(typeProvider))
                                    .WithNames("MyTestSuite", Environment.MachineName)
                                    .WithTypesFrom(typeProvider)
                                    .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                                    .WithHeartbeatInterval(TimeSpan.MaxValue)
                                    .WithLogger(_logger)
                ;

                var bus = configuration.Build();
                await bus.Start();

                await bus.Stop();

                return(bus);
            }
        }
        protected override async Task <Bus> Given()
        {
            //var logger = TestHarnessLoggerFactory.Create();
            var logger = new NullLogger();

            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });

            var bus = new BusBuilder().Configure()
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithTransport(new InProcessTransportConfiguration())
                      .WithTypesFrom(typeProvider)
                      .WithGlobalInboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IInboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithGlobalOutboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IOutboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithDependencyResolver(new DependencyResolver(typeProvider))
                      .WithDefaultTimeout(TimeSpan.FromSeconds(TimeoutSeconds))
                      .WithLogger(logger)
                      .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();

            MethodCallCounter = MethodCallCounter.CreateInstance(bus.InstanceId);

            await bus.Start(MessagePumpTypes.All);

            return(bus);
        }
Example #22
0
        public void ConfigureContainer(ContainerBuilder builder)
        {
            var bus = new BusBuilder()
                      .RegisterHandlers(typeof(Startup).Assembly);

            builder.RegisterMicroBus(bus);
        }
Example #23
0
        static async Task <IBus> JupiterService()
        {
            var bus = new BusBuilder()
                      .UseAzureStorageQueue(
                "UseDevelopmentStorage=true",
                configuration =>
            {
                configuration.PublishAndSendOptions.AddAvailableQueues("saturn");
                configuration.PublishAndSendOptions
                .MapCommandToQueue <AppleCommand>("saturn");
            })
                      //.UseAzureServiceBus(
                      //    ConnectionString,
                      //    configuration =>
                      //    {
                      //        configuration.SetManagementSettings(SubscriptionId, TenantId, ClientId, ClientSecret, ResourceGroupName, NamespaceName);
                      //        configuration.PublishAndSendOptions
                      //                     .AttemptCreateTopicWith(new Microsoft.Azure.Management.ServiceBus.Models.SBTopic { EnablePartitioning = true })
                      //                     .MapCommandToQueue<AppleCommand>("saturn");
                      //    })
                      .DefineCommandScanRuleWith(t => t.Namespace == "RockyBus.DemoMessages" && t.Name.EndsWith("Command"))
                      .DefineEventScanRuleWith(t => t.Namespace == "RockyBus.DemoMessages" && t.Name.EndsWith("Event"))
                      .Build();
            await bus.Start();

            await bus.Publish(new CatEvent { Text = "Meow" });

            await bus.Send(new AppleCommand { Text = "jupiter to saturn" });

            return(bus);
        }
Example #24
0
        protected override async Task <Bus> Given()
        {
            _largeMessageBodyTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString());

            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });
            var logger       = TestHarnessLoggerFactory.Create();

            logger.Debug("Starting disk storage large message test at {0}", _largeMessageBodyTempPath);

            var largeMessageBodyStorage = new FileSystemStorageBuilder().Configure()
                                          .WithStorageDirectory(_largeMessageBodyTempPath)
                                          .WithLogger(logger)
                                          .Build();

            var bus = new BusBuilder().Configure()
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(typeProvider)
                      .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                      .WithLogger(logger)
                      .WithLargeMessageStorage(c => c.WithLargeMessageBodyStore(largeMessageBodyStorage)
                                               .WithMaxSmallMessageSize(64 * 1024)
                                               .WithMaxLargeMessageSize(10 * 1048576))
                      .WithDebugOptions(dc => dc.RemoveAllExistingNamespaceElementsOnStartup(
                                            "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start();

            logger.Debug("Bus started");
            return(bus);
        }
Example #25
0
        protected override async Task <Bus> Given()
        {
            _logger = TestHarnessLoggerFactory.Create();

            var typeProvider = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });

            var bus = new BusBuilder().Configure()
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(typeProvider)
                      .WithGlobalInboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IInboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithGlobalOutboundInterceptorTypes(typeProvider.InterceptorTypes.Where(t => typeof(IOutboundInterceptor).IsAssignableFrom(t)).ToArray())
                      .WithDependencyResolver(new DependencyResolver(typeProvider))
                      .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                      .WithDefaultMessageLockDuration(_messageLockDuration)
                      .WithLogger(_logger)
                      .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start();

            return(bus);
        }
Example #26
0
        static void SendDemo()
        {
            // demonstrate sending message to defined write queue

            IBus bus = new BusBuilder()
                       .WithLogging(new FileLogger())
                       .InstallMsmqIfNeeded()
                       .DefineErrorQueue("MiniBus.errors")
                       .DefineWriteQueue("MiniBus.messages1")
                       .CreateLocalQueuesAutomatically()
                       .EnlistInAmbientTransactions()
                       .JsonSerialization()
                       .CreateBus();


            // transaction scope isn't required unless modifying another transactional resource at the same time
            using (var scope = new TransactionScope())
            {
                for (int i = 1; i <= 10; i++)
                {
                    var p = new Person {
                        Name = "Bob", Age = i
                    };

                    // insert/update a database to see atomic commit

                    bus.Send(p);
                }
                scope.Complete();
            }

            Console.WriteLine("\nPress a key to exit");
            Console.ReadLine();
            bus.Dispose();
        }
Example #27
0
        static void ReceiveDemo()
        {
            // demonstrate receiving - Receive processes whatever messages happen to be on the queue at the time of the call

            Console.WriteLine("\nPress a key to read message/s");
            Console.ReadLine();

            IBus bus = new BusBuilder()
                       .WithLogging(new FileLogger())
                       .InstallMsmqIfNeeded()
                       .DefineErrorQueue("MiniBus.errors")
                       .DefineReadQueue("MiniBus.messages1")
                       .CreateLocalQueuesAutomatically()
                       .EnlistInAmbientTransactions()
                       .JsonSerialization()
                       .NumberOfRetries(3)
                       .CreateBus();

            // pass true to have a message fail and moved to the error queue
            bus.RegisterHandler(new PersonHandler(false));

            bus.Receive <Person>();

            Console.WriteLine("\nPress a key to exit");
            Console.ReadLine();
            bus.Dispose();
        }
        protected override async Task <IBus> Given()
        {
            MethodCallCounter.Clear();

            var testFixtureType = GetType();
            var outboundAuditingInterceptorType = typeof(OutboundAuditingInterceptor);
            var auditEventType = typeof(AuditEvent);
            var typeProvider   = new TestHarnessTypeProvider(new[] { testFixtureType.Assembly, outboundAuditingInterceptorType.Assembly },
                                                             new[] { testFixtureType.Namespace, outboundAuditingInterceptorType.Namespace, auditEventType.Namespace });
            var logger = TestHarnessLoggerFactory.Create();

            var dependencyResolver = new DependencyResolver(typeProvider);

            var bus = new BusBuilder().Configure()
                      .WithNames("MyTestSuite", Environment.MachineName)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(typeProvider)
                      .WithDependencyResolver(dependencyResolver)
                      .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                      .WithMaxDeliveryAttempts(1)
                      .WithHeartbeatInterval(TimeSpan.MaxValue)
                      .WithGlobalOutboundInterceptorTypes(typeof(OutboundAuditingInterceptor))
                      .WithLogger(logger)
                      .WithDebugOptions(
                dc =>
                dc.RemoveAllExistingNamespaceElementsOnStartup(
                    "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();

            await bus.Start();

            return(bus);
        }
		public BusBuilder Configure(BusBuilder builder)
		{
			builder.Match<ServiceBusBuilder>(x =>
				{
					var settings = new ServiceBusSettings(builder.Settings);

					settings.InputAddress = _uri ?? builder.Settings.InputAddress.AppendToPath("_control");

					// the endpoint factory is already created, so we can't set the endpoint here
					// we really need this to be part of another step, but i don't have a clue how yet.
					//_configurator.ConfigureEndpoint(_uri, x => x.PurgeExistingMessages());

					if (_log.IsDebugEnabled)
						_log.DebugFormat("Configuring control bus for {0} at {1}", builder.Settings.InputAddress, settings.InputAddress);

					settings.ConcurrentConsumerLimit = 1;
					settings.ConcurrentReceiverLimit = 1;
					settings.AutoStart = true;

					BusBuilder controlBusBuilder = new ControlBusBuilderImpl(settings);

					controlBusBuilder = _configurators
						.Aggregate(controlBusBuilder, (current, configurator) => configurator.Configure(current));

					IControlBus controlBus = controlBusBuilder.Build();

					x.UseControlBus(controlBus);
				});

			return builder;
		}
        private static Bus CreateBus(IWindsorContainer container, ITypeProvider typeProvider)
        {
            var configRetriever = container.Resolve <IGetEnvironmentConfiguration>();

            try
            {
                // Get the Azure Service Bus connection string, app name, and unique name for this running instance
                string connectionString = configRetriever.GetSetting(AzureServiceBusConnectionStringKey);
                string appName          = configRetriever.AppName;
                string uniqueName       = configRetriever.UniqueInstanceId;

                Bus bus = new BusBuilder().Configure()
                          .WithConnectionString(connectionString)
                          .WithNames(appName, uniqueName)
                          .WithJsonSerializer()
                          .WithWindsorDefaults(container)
                          .WithTypesFrom(typeProvider)
                          .Build();
                return(bus);
            }
            finally
            {
                container.Release(configRetriever);
            }
        }
        private ICancelableMicroMediator GetMediator(BusBuilder busBuilder)
        {
            var container = new ContainerBuilder()
                            .RegisterMicroBus(busBuilder)
                            .Build();

            return(container.Resolve <ICancelableMicroMediator>());
        }
		public BusBuilder Configure(BusBuilder builder)
		{
			builder.AddBusServiceConfigurator(this);

			return builder;
		}
		public BusBuilder Configure(BusBuilder builder)
		{
			builder.Match<ServiceBusBuilder>(x => x.AddBusServiceConfigurator(_configurator));

			return builder;
		}
		public BusBuilder Configure(BusBuilder builder)
		{
			builder.Match<ServiceBusBuilder>(x => x.AddPostCreateAction(_postCreateAction));

			return builder;
		}
		public BusBuilder Configure(BusBuilder builder)
		{
			builder.AddPostCreateAction(_postCreateAction);

			return builder;
		}