Пример #1
0
        public IControlBus Build()
        {
            ServiceBus bus = CreateServiceBus(_settings.EndpointCache);

            try
            {
                ConfigureBusSettings(bus);

                RunPostCreateActions(bus);

                ConfigureMessageInterceptors(bus);

                RunBusServiceConfigurators(bus);

                if (_settings.AutoStart)
                {
                    bus.Start();
                }

                return(bus);
            }
            catch
            {
                try
                {
                    bus.Dispose();
                }
                catch (Exception ex)
                {
                    _log.Error("Exception disposing of failed bus instance", ex);
                }

                throw;
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            var serviceBus =
                ServiceBus.Setup(
                    new InitializationRequest
            {
                Namespace = "YOUR NAMESPACE",
                Issuer    = "YOR ISSUER",
                IssuerKey = "YOUR KEY"
            })
                .ClearTopics()
                .Subscribe <SimpleMessage>(HandleSimpleMessage, ReceiveMode.ReceiveAndDelete);

            Console.Write("Message: ");
            var message = Console.ReadLine();

            while (!string.IsNullOrEmpty(message))
            {
                serviceBus.Publish <SimpleMessage>(new SimpleMessage
                {
                    Title = message,
                    Id    = Guid.NewGuid()
                });

                Console.Write("Message:");
                message = Console.ReadLine();
            }
        }
Пример #3
0
        /// <summary>
        /// Initialization routine
        /// </summary>
        /// <param name="action">action</param>
        /// <returns>initialization task</returns>
        private async Task Initialize(Action action)
        {
            // load the environment configuration file from UtilsInternal
            var sr                    = new FileSettingsReader(ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + environmentName + ".config");
            var certThumbprint        = sr.ReadValue(SocialPlusCertThumbprint);
            var clientID              = sr.ReadValue(EmbeddedSocialClientIdSetting);
            var storeLocation         = StoreLocation.CurrentUser;
            var vaultUrl              = sr.ReadValue(SocialPlusVaultUrlSetting);
            ICertificateHelper cert   = new CertificateHelper(certThumbprint, clientID, storeLocation);
            IKeyVaultClient    client = new AzureKeyVaultClient(cert);

            var log      = new Log(LogDestination.Console, Log.DefaultCategoryName);
            var kv       = new KV(log, clientID, vaultUrl, certThumbprint, storeLocation, client);
            var kvReader = new KVSettingsReader(sr, kv);

            IConnectionStringProvider connectionStringProvider = new ConnectionStringProvider(kvReader);
            int          queueBatchIntervalMs = int.Parse(sr.ReadValue(ServiceBusBatchIntervalMsSetting));
            QueueManager queueManager         = new QueueManager(connectionStringProvider, queueBatchIntervalMs);
            var          sbConnect            = await connectionStringProvider.GetServiceBusConnectionString(ServiceBusInstanceType.Default);

            // the ListQueues action requires an instance of a ServiceBus object
            if (action == Action.ListQueues)
            {
                this.sb = new ServiceBus(sbConnect);
            }

            // all the remaining actions operate on an instance of a ServiceBusQueue object
            if (action != Action.ListQueues)
            {
                // ParseArgs() ensures that queueName is valid here
                this.sbQueue = await ServiceBusQueue.Create(sbConnect, queueName, queueBatchIntervalMs);

                this.selectedQueue = await queueManager.GetQueue((QueueIdentifier)selectedQueueId);
            }
        }
Пример #4
0
        private static void Main()
        {
            Log.Assign(new Log4NetLog(LogManager.GetLogger(typeof(Program))));

            var bus = ServiceBus
                      .Create()
                      .AddCompressionAlgorithm(new GZipCompressionAlgorithm())
                      .AddEnryptionAlgorithm(new TripleDesEncryptionAlgorithm())
                      .Start();

            Console.WriteLine("Client bus started.  Press CTRL+C to stop.");
            Console.WriteLine();
            Console.WriteLine("Press enter to send a message with random text to the server for reversal.");
            Console.WriteLine();

            while (true)
            {
                Console.ReadLine();

                var command = new ReverseTextCommand
                {
                    Text = Guid.NewGuid().ToString().Substring(0, 5)
                };

                bus.OutgoingCorrelationId = "correlation-id";
                bus.OutgoingHeaders.Add(new TransportHeader {
                    Key = "header1", Value = "value1"
                });
                bus.OutgoingHeaders.Add(new TransportHeader {
                    Key = "header2", Value = "value2"
                });

                Console.WriteLine("Message (id: {0}) sent.  Text: {1}", bus.Send(command).MessageId, command.Text);
            }
        }
Пример #5
0
        static void Main(string[] args)
        {
            var bus = new ServiceBus();

            Console.WriteLine("Informe o Id da Barragem:");
            var idBarragem = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Informe o intervalo de envio de dados:");
            var tempoIntervaloSensoresSeg = Convert.ToInt32(Console.ReadLine());

            while (true)
            {
                var info = SensorInfo.GenerateRandom();

                var evento = new SensorInfoAlteradoEvent()
                {
                    BarragemId     = idBarragem,
                    HorarioMedicao = DateTime.Now,
                    Pressao        = info.Pressao,
                    Temperatura    = info.Temperatura,
                    Volume         = info.Volume
                };

                bus.PublicarEvento <SensorInfoAlteradoEvent>(evento);

                Console.WriteLine(info.ToString());
                System.Threading.Thread.Sleep(tempoIntervaloSensoresSeg * 1000);
            }
        }
Пример #6
0
        private static void Main(string[] args)
        {
            var brokerUri   = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
            var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Service1";

            Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");

            var serviceBus = ServiceBus.Configure()
                             .WithActiveMQEndpoints <IServiceMessage1>()
                             .Named(serviceName)
                             .UsingQueueFor <ICommand>()
                             .ConnectToBroker(brokerUri)
                             .WithCredentials("TESTUSER", "testpassword1")
                             .SerializedAsJson()
                             .AsClient()
                             .CreateClient();

            serviceBus.Events.Subscribe(c => Console.WriteLine("Received an event!"));

            Console.WriteLine("Hit <Enter> to send a command.");
            while (true)
            {
                string data = Console.ReadLine();
                serviceBus.SendAsync(new Command1 {
                    Data = data
                });
            }
        }
            public void VerifyMessageTypesMappedEntit()
            {
                IEnumerable <MessageTypeMessagingEntityMappingDetails> configuredMessageTypePathMappings = null;

                _mockMessagingEntityVerifier.Setup(mev => mev.EnsureMessagingEntitiesExist(It.IsAny <IEnumerable <MessageTypeMessagingEntityMappingDetails> >()))
                .Callback <IEnumerable <MessageTypeMessagingEntityMappingDetails> >(mtpm => configuredMessageTypePathMappings = mtpm);

                ServiceBus.Configure()
                .WithAzureServiceBusEndpoint <TestMessage>()
                .Named("Test Service Bus")
                .WithMessagingFactory(_mockMessagingFactory.Object)
                .WithMessagingEntityVerifier(_mockMessagingEntityVerifier.Object)
                .UsingQueueFor <ICommand>("commands", MessagingEntityCreationOptions.VerifyAlreadyExists)
                .UsingQueueFor <IRequest>("requests", MessagingEntityCreationOptions.VerifyAlreadyExists)
                .UsingQueueFor <IResponse>("responses", MessagingEntityCreationOptions.VerifyAlreadyExists)
                .UsingTopicFor <IEvent>("events", MessagingEntityCreationOptions.VerifyAlreadyExists)
                .UsingSubscriptionFor <IEvent>("events", "my-event-subscription", MessagingEntityCreationOptions.VerifyAlreadyExists)
                .SerializedWith(_mockMessageSerializer.Object, _mockMessageDeserializerFactory.Object)
                .FilterMessageTypeAssemblies(assembly => assembly.GetName().Name == "Obvs.AzureServiceBus.Tests")
                .AsClientAndServer()
                .CreateServiceBus();

                _mockMessagingEntityVerifier.Verify(mev => mev.EnsureMessagingEntitiesExist(It.IsAny <IEnumerable <MessageTypeMessagingEntityMappingDetails> >()), Times.Once());

                configuredMessageTypePathMappings.Should().NotBeNull();
                configuredMessageTypePathMappings.Should().BeEquivalentTo(new []
                {
                    new MessageTypeMessagingEntityMappingDetails(typeof(ICommand), "commands", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock),
                    new MessageTypeMessagingEntityMappingDetails(typeof(IRequest), "requests", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock),
                    new MessageTypeMessagingEntityMappingDetails(typeof(IResponse), "responses", MessagingEntityType.Queue, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock),
                    new MessageTypeMessagingEntityMappingDetails(typeof(IEvent), "events", MessagingEntityType.Topic, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock),
                    new MessageTypeMessagingEntityMappingDetails(typeof(IEvent), "events/subscriptions/my-event-subscription", MessagingEntityType.Subscription, MessagingEntityCreationOptions.VerifyAlreadyExists, MessageReceiveMode.PeekLock),
                });
            }
Пример #8
0
 private async Task <Domain.Order> EntryAggregate(Guid entryId)
 {
     return(await ServiceBus.Send(new Domain.OrderByIdQuery
     {
         Id = entryId
     }));
 }
Пример #9
0
        public void MakeFundIn(Guid playerId, Guid destinationWalletStructureId, decimal amount, string bonusCode = null, Guid?bonusId = null)
        {
            if (bonusId.HasValue || string.IsNullOrWhiteSpace(bonusCode) == false)
            {
                BonusCommands.ApplyForBonus(new FundInBonusApplication
                {
                    PlayerId  = playerId,
                    BonusId   = bonusId,
                    BonusCode = bonusCode,
                    Amount    = amount,
                    DestinationWalletTemplateId = destinationWalletStructureId
                });
            }

            ServiceBus.PublishMessage(new TransferFundCreated
            {
                PlayerId = playerId,
                DestinationWalletStructureId = destinationWalletStructureId,
                Amount    = amount,
                BonusCode = bonusCode,
                Type      = TransferFundType.FundIn,
                Status    = TransferFundStatus.Approved
            });

            // Here we need somehow create an event to mimic a wallet fund-in
        }
Пример #10
0
        public void ShouldOnlySubscribeToUnderlyingEndpointCommandsOnce()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<ICommand> observable1 = A.Fake<IObservable<ICommand>>();
            IObservable<ICommand> observable2 = A.Fake<IObservable<ICommand>>();

            IObserver<ICommand> observer1 = A.Fake<IObserver<ICommand>>();
            IObserver<ICommand> observer2 = A.Fake<IObserver<ICommand>>();

            A.CallTo(() => serviceEndpoint1.Commands).Returns(observable1);
            A.CallTo(() => serviceEndpoint2.Commands).Returns(observable2);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IDisposable sub1 = serviceBus.Commands.Subscribe(observer1);
            IDisposable sub2 = serviceBus.Commands.Subscribe(observer2);
            
            A.CallTo(() => serviceEndpoint1.Commands).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint2.Commands).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => observable1.Subscribe(A<IObserver<ICommand>>._)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observable2.Subscribe(A<IObserver<ICommand>>._)).MustHaveHappened(Repeated.Exactly.Once);

            sub1.Dispose();
            sub2.Dispose();
        }
        public static async Task Handler(
            [ServiceBusTrigger("agroqueue", Connection = "ServiceBusConnectionString", IsSessionsEnabled = true)] Message message,
            [SignalR(HubName = "AsyncConnection")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            var opInstance  = ServiceBus.Deserialize(message.Body);
            var ObjectIdAAD = opInstance.Value <string>("ObjectIdAAD");
            var queries     = new CommonQueries(ConfigManager.GetDbArguments);
            var userId      = await queries.GetUserIdFromAAD(ObjectIdAAD);

            var EntityName = opInstance.Value <string>("EntityName");
            var agro       = await ContainerMethods.AgroManager(ObjectIdAAD, false);

            var     entityType = opInstance["EntityType"].ToObject <Type>();
            var     repo       = agro.GetOperationByInputType(entityType);
            dynamic element    = opInstance["Element"].ToObject(entityType);

            element.Id = opInstance.Value <string>("Id");
            try {
                var saveReturn = await repo.SaveInput(element, false);

                await agro.UserActivity.SaveInput(new UserActivityInput {
                    Action     = opInstance.Value <string>("HttpMethod").Equals("post") ? UserActivityAction.CREATE : UserActivityAction.MODIFY,
                    Date       = DateTime.Now,
                    EntityName = EntityName,
                    EntityId   = saveReturn.IdRelated
                }, false);

                await signalRMessages.AddAsync(new SignalRMessage { Target = "Success", UserId = userId, Arguments = new object[] { EntityName } });
            }
            catch (Exception ex) {
                log.LogError(ex, ex.Message);
                await signalRMessages.AddAsync(new SignalRMessage { Target = "Error", UserId = userId, Arguments = new object[] { ex is Validation_Exception ? ((Validation_Exception)ex).ErrorMessages : (object)new string[] { $"{ex.Message}" } } });
            }
        }
Пример #12
0
        private static void Main(string[] args)
        {
            var container = new SimpleInjectorComponentContainer(new Container());

            ServiceBus.Register(container);

            var transportMessageFactory = container.Resolve <ITransportMessageFactory>();

            using (var bus = ServiceBus.Create(container).Start())
            {
                string userName;

                while (!string.IsNullOrEmpty(userName = Console.ReadLine()))
                {
                    var command = new RegisterMemberCommand
                    {
                        UserName = userName
                    };

                    var transportMessage = transportMessageFactory.Create(command, c => { });

                    for (var i = 0; i < 5; i++)
                    {
                        bus.Dispatch(transportMessage);                         // will be processed once since message id is the same
                    }

                    bus.Send(command);                     // will be processed since it has a new message id
                    bus.Send(command);                     // will also be processed since it too has a new message id
                }
            }
        }
Пример #13
0
        private Task StartWatcher(int i, int count)
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                                     .WithKafkaEndpoints <ITestMessage1>()
                                     .Named("Obvs.TestService")
                                     .ConnectToKafka(_kafkaAddresses)
                                     .SerializedAsJson()
                                     .AsServer()
                                     //.UsingConsoleLogging()
                                     .Create();

            double?[] times    = new double?[count];
            long[]    received = { 0 };


            var dis = serviceBus.Commands.OfType <TestCommand>().Subscribe(x =>
            {
                Interlocked.Increment(ref received[0]);
                var ms      = (Stopwatch.GetTimestamp() - x.Ticks) / ((double)Stopwatch.Frequency / 1000);
                times[x.Id] = ms;
            });

            return(Task.Run(() =>
            {
                SpinWait.SpinUntil(() => Interlocked.Read(ref received[0]) == count);

                Console.WriteLine($"******* Watcher {i}: Total {_sw.ElapsedMilliseconds}ms ({count} msgs), Min/Avg/Max (ms) = {times.Min(d=>d.Value):0}/{times.Average(d => d.Value):0}/{times.Max(d => d.Value):0}");

                dis.Dispose();
                ((IDisposable)serviceBus).Dispose();
            }));
        }
Пример #14
0
 internal UserStoreWrapper(Uri evernoteUri, string consumerKey, string consumerSecret, ServiceBus servicebus)
     : base(new Uri(evernoteUri, "/edam/user"))
 {
     this.consumerKey = consumerKey;
     this.consumerSecret = consumerSecret;
     this.servicebus = servicebus;
 }
Пример #15
0
        private async Task SendCommands(int count)
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                                     .WithKafkaEndpoints <ITestMessage1>()
                                     .Named("Obvs.TestService")
                                     .WithKafkaSourceConfiguration(new KafkaSourceConfiguration())
                                     .WithKafkaProducerConfiguration(new KafkaProducerConfiguration())
                                     .ConnectToKafka(_kafkaAddresses)
                                     .SerializedAsJson()
                                     .AsClient()
                                     //.UsingConsoleLogging()
                                     .Create();

            Stopwatch sw = Stopwatch.StartNew();

            var sendTasks = Enumerable.Range(0, count)
                            .Select(i => serviceBus.SendAsync(new TestCommand {
                Id = i
            }));

            await Task.WhenAll(sendTasks);

            _sw = Stopwatch.StartNew();
            Console.WriteLine($"###$$$$### Sends: {sw.ElapsedMilliseconds}ms");

            ((IDisposable)serviceBus).Dispose();
        }
Пример #16
0
        public void Start()
        {
            Log.Assign(new Log4NetLog(LogManager.GetLogger(typeof(Host))));

            _container = new WindsorContainer();

            var container = new WindsorComponentContainer(_container);

            container.RegisterSuffixed("Shuttle.ProcessManagement");

            ServiceBus.Register(container);

            var subscriptionManager = container.Resolve <ISubscriptionManager>();

            subscriptionManager.Subscribe <OrderProcessRegisteredEvent>();
            subscriptionManager.Subscribe <OrderProcessCancelledEvent>();
            subscriptionManager.Subscribe <OrderProcessAcceptedEvent>();
            subscriptionManager.Subscribe <OrderProcessCompletedEvent>();
            subscriptionManager.Subscribe <OrderProcessArchivedEvent>();
            subscriptionManager.Subscribe <OrderCreatedEvent>();
            subscriptionManager.Subscribe <CancelOrderProcessRejectedEvent>();
            subscriptionManager.Subscribe <ArchiveOrderProcessRejectedEvent>();
            subscriptionManager.Subscribe <InvoiceCreatedEvent>();
            subscriptionManager.Subscribe <EMailSentEvent>();

            _bus = ServiceBus.Create(container).Start();
        }
Пример #17
0
        public MonitoredNode(string nodeId, Uri incoming, IDocumentStore store)
        {
            Policies.Local.Add <ErrorHandlingPolicy>();

            AlterSettings <MonitoringSettings>(x => x.Incoming = "memory://jobs".ToUri());

            Channel(x => x.Incoming).ReadIncoming();

            NodeName = "Monitoring";
            NodeId   = nodeId;

            _nodeId = nodeId;

            ServiceBus.EnableInMemoryTransport(incoming);


            Services.ReplaceService(store);

            Services.AddService <ILogListener, ScheduledJobListener>();


            ScheduledJob.DefaultJobChannel(x => x.Incoming);
            ScheduledJob.RunJob <AlwaysGoodJob>().ScheduledBy <TenMinuteIncrements>();
            ScheduledJob.RunJob <FailsFirstTwoTimes>().ScheduledBy <SevenMinuteIncrements>();
            ScheduledJob.RunJob <FailsSometimes>().ScheduledBy <FiveMinuteIncrements>();
            ScheduledJob.RunJob <TimesOutSometimes>().ScheduledBy <ThreeMinuteIncrements>().Timeout(10.Seconds());
        }
Пример #18
0
        static void Main(string[] args)
        {
            using (var bus = ServiceBus.Create().Start())
            {
                string userName;

                while (!string.IsNullOrEmpty(userName = Console.ReadLine()))
                {
                    var command = new RegisterMemberCommand
                    {
                        UserName = userName
                    };

                    var transportMessage = bus.CreateTransportMessage(command, null);

                    for (var i = 0; i < 5; i++)
                    {
                        bus.Dispatch(transportMessage);                         // will be processed once since message id is the same
                    }

                    bus.Send(command);                     // will be processed since it has a new message id
                    bus.Send(command);                     // will also be processed since it also has a new message id
                }
            }
        }
Пример #19
0
        public void Should_be_able_to_handle_expired_message()
        {
            var handlerInvoker = new FakeMessageHandlerInvoker();
            var fakeQueue      = new FakeQueue(2);
            var configuration  = new ServiceBusConfiguration
            {
                Inbox = new InboxQueueConfiguration
                {
                    WorkQueue   = fakeQueue,
                    ErrorQueue  = fakeQueue,
                    ThreadCount = 1
                },
                MessageHandlerInvoker = handlerInvoker
            };

            using (var bus = new ServiceBus(configuration))
            {
                bus.Start();

                var timeout = DateTime.Now.AddMilliseconds(5000);

                while (fakeQueue.MessageCount < 2 && DateTime.Now < timeout)
                {
                    Thread.Sleep(5);
                }
            }

            Assert.AreEqual(1, handlerInvoker.GetInvokeCount("SimpleCommand"), "FakeHandlerInvoker was not invoked exactly once.");
            Assert.AreEqual(2, fakeQueue.MessageCount, "FakeQueue was not invoked exactly twice.");
        }
Пример #20
0
        protected void TestInboxError(string queueSchemeAndHost, bool useJournal, bool isTransactional)
        {
            var configuration = GetTestInboxConfiguration(queueSchemeAndHost, useJournal, 1, isTransactional);

            using (var bus = new ServiceBus(configuration))
            {
                var message = bus.CreateTransportMessage(new NoHandlerCommand());

                configuration.Inbox.WorkQueue.Enqueue(message.MessageId, configuration.Serializer.Serialize(message));

                var working = true;

                bus.Events.ThreadWaiting += (sender, args) => { working = false; };

                bus.Start();

                while (working)
                {
                    Thread.Sleep(5);
                }
            }

            Assert.NotNull(configuration.Inbox.ErrorQueue.Dequeue());

            AttemptDropQueues(queueSchemeAndHost, useJournal);
        }
Пример #21
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // delay startup to let broker start first
            var delay = TimeSpan.FromSeconds(10);

            Console.WriteLine($"Starting in {delay}");
            await Task.Delay(delay, cancellationToken);

            // get env variables
            _brokerUri   = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
            _serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "MyService";

            Console.WriteLine($"Starting {_serviceName}, connecting to broker {_brokerUri}");

            // create singleton ServiceBus
            var serviceBus = ServiceBus.Configure()
                             .WithActiveMQEndpoints <IServiceMessage1>() // you can use different transports for each service
                             .Named(_serviceName)                        // used to prefix AMQ topic names
                             .UsingQueueFor <ICommand>()                 // optional, default is topic
                             .ConnectToBroker(_brokerUri)
                             .WithCredentials("admin", "admin")
                             .SerializedAsJson()    // you can use different serialization formats for each service
                             .AsServer()            // will subscribe to commands and requests, and publish events and responses
                             .UsingConsoleLogging() // optional logging extensions available
                             .Create();

            // subscribe to commands and publish events

            _subscription = serviceBus.Commands.OfType <Command1>().Subscribe(async cmd =>
            {
                await serviceBus.PublishAsync(new Event1 {
                    Data = cmd.Data
                });
            });
        }
Пример #22
0
        protected void TestInboxDeferred(string queueSchemeAndHost)
        {
            var configuration = GetTestInboxConfiguration(queueSchemeAndHost, false, 1, false);
            var messageId     = Guid.Empty;
            var messageType   = typeof(ReceivePipelineCommand).FullName;

            using (var bus = new ServiceBus(configuration))
            {
                var id      = messageId;
                var type    = messageType;
                var waiting = true;

                bus.Events.AfterTransportMessageDeserialization +=
                    (sender, eventArgs) =>
                {
                    Assert.True(id.Equals(eventArgs.TransportMessage.MessageId));
                    Assert.True(type.Equals(eventArgs.TransportMessage.MessageType, StringComparison.OrdinalIgnoreCase));
                    waiting = false;
                };

                bus.Events.ThreadWaiting += (sender, args) => { waiting = false; };

                bus.Start();

                messageId = bus.SendDeferred(DateTime.Now.AddMilliseconds(500), new ReceivePipelineCommand(), configuration.Inbox.WorkQueue).MessageId;

                while (waiting)
                {
                    Thread.Sleep(5);
                }
            }
        }
Пример #23
0
        public Guid SubmitDeposit(Guid playerId, decimal depositAmount = 200, string bonusCode = null, Guid?bonusId = null)
        {
            var depositId = Guid.NewGuid();

            ServiceBus.PublishMessage(new DepositSubmitted
            {
                DepositId = depositId,
                PlayerId  = playerId,
                Amount    = depositAmount
            });

            if (bonusId.HasValue || string.IsNullOrWhiteSpace(bonusCode) == false)
            {
                BonusCommands.ApplyForBonus(new DepositBonusApplication
                {
                    PlayerId  = playerId,
                    BonusId   = bonusId,
                    BonusCode = bonusCode,
                    Amount    = depositAmount,
                    DepositId = depositId
                });
            }

            return(depositId);
        }
Пример #24
0
        public void Start()
        {
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);

            Log.Assign(new Log4NetLog(LogManager.GetLogger(typeof(Host))));

            _container = new WindsorContainer();

            var container = new WindsorComponentContainer(_container);

            container.RegisterSuffixed("Shuttle.Abacus");

            EventStore.Register(container);
            ServiceBus.Register(container);

            container.Register <ArgumentHandler>();
            container.Register <FormulaHandler>();
            container.Register <MatrixHandler>();
            container.Register <TestHandler>();

            _eventProcessor = container.Resolve <IEventProcessor>();

            _eventProcessor.AddProjection(new Projection("Argument").AddEventHandler(container.Resolve <ArgumentHandler>()));
            _eventProcessor.AddProjection(new Projection("Formula").AddEventHandler(container.Resolve <FormulaHandler>()));
            _eventProcessor.AddProjection(new Projection("Matrix").AddEventHandler(container.Resolve <MatrixHandler>()));
            _eventProcessor.AddProjection(new Projection("Test").AddEventHandler(container.Resolve <TestHandler>()));

            container.Resolve <IDatabaseContextFactory>().ConfigureWith("Abacus");

            _bus = ServiceBus.Create(container).Start();
            _eventProcessor.Start();
        }
Пример #25
0
        public void Start()
        {
            Log.Assign(new Log4NetLog(LogManager.GetLogger(typeof(Host))));

            _container = new WindsorContainer();

            _container.RegisterDataAccessCore();
            _container.RegisterDataAccess("Shuttle.ProcessManagement");

            var subscriptionManager = SubscriptionManager.Default();

            subscriptionManager.Subscribe <OrderProcessRegisteredEvent>();
            subscriptionManager.Subscribe <OrderProcessCancelledEvent>();
            subscriptionManager.Subscribe <OrderProcessAcceptedEvent>();
            subscriptionManager.Subscribe <OrderProcessCompletedEvent>();
            subscriptionManager.Subscribe <OrderProcessArchivedEvent>();
            subscriptionManager.Subscribe <OrderCreatedEvent>();
            subscriptionManager.Subscribe <CancelOrderProcessRejectedEvent>();
            subscriptionManager.Subscribe <ArchiveOrderProcessRejectedEvent>();
            subscriptionManager.Subscribe <InvoiceCreatedEvent>();
            subscriptionManager.Subscribe <EMailSentEvent>();

            _bus = ServiceBus.Create(
                c =>
            {
                c
                .MessageHandlerFactory(new CastleMessageHandlerFactory(_container))
                .SubscriptionManager(subscriptionManager);
            }).Start();
        }
        public virtual void Start()
        {
            // init logging
            Log.Assign(new ConsoleLog(typeof(ShuttleESBHost))
            {
                LogLevel = LogLevel.Trace
            });

            // init depedency injection container
            InitializeContainer();

            // init message handler factory
            var messageHandlerFactory = InitializeMessageHandlerFactory();

            // init subscription manager
            var subscriptionManager = InitializeSubscriptionManager();

            // init message serializer
            var messageSerializer = InitializeMessageSerializer();

            // init compression algorithm
            var compressionAlgorithm = InitializeCompressionAlgorithm();

            // init encryption algorithm
            var encryptionAlgorithm = InitializeEncryptionAlgorithm();

            // start service bus
            Bus = ServiceBus
                  .Create(c =>
            {
                if (subscriptionManager != null)
                {
                    c.SubscriptionManager(subscriptionManager);
                }

                if (messageHandlerFactory != null)
                {
                    c.MessageHandlerFactory(messageHandlerFactory);
                }

                if (messageSerializer != null)
                {
                    c.MessageSerializer(messageSerializer);
                }

                if (compressionAlgorithm != null)
                {
                    c.AddCompressionAlgorithm(compressionAlgorithm);
                }

                if (encryptionAlgorithm != null)
                {
                    c.AddEnryptionAlgorithm(encryptionAlgorithm);
                }
            });

            Contract.Assume(Bus != null);

            Bus.Start();
        }
Пример #27
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCors();

            var container = new WindsorContainer();

            var componentContainer = new WindsorComponentContainer(container);

            componentContainer.RegisterInstance <IAccessConfiguration>(AccessSection.Configuration());

            componentContainer.RegisterSuffixed("Shuttle.Sentinel");
            componentContainer.RegisterSuffixed("Shuttle.Access.Sql");

            componentContainer.Register <IInspectionQueue, DefaultInspectionQueue>();
            componentContainer.Register <IHttpContextAccessor, HttpContextAccessor>();
            componentContainer.Register <IDatabaseContextCache, ContextDatabaseContextCache>();

            ServiceBus.Register(componentContainer);
            EventStore.Register(componentContainer);

            componentContainer.Resolve <IDataStoreDatabaseContextFactory>().ConfigureWith("Sentinel");
            componentContainer.Resolve <IDatabaseContextFactory>().ConfigureWith("Sentinel");
            var inspectionQueue = componentContainer.Resolve <IInspectionQueue>();

            _bus = ServiceBus.Create(componentContainer).Start();

            return(WindsorRegistrationHelper.CreateServiceProvider(container, services));
        }
Пример #28
0
        private static async Task StartService(string host, int port)
        {
            //服务信息
            var serviceInfo = new ServiceInformation()
            {
                Host        = host,
                Port        = port,
                Description = "我的小服务, 老火了",
                Key         = "Foo.Services",
                Name        = "我的小服务",
                ServiceType = ServiceType.Grpc,
            };

            //启动服务
            Server service = new Server
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports    = { new ServerPort(serviceInfo.Host, port, ServerCredentials.Insecure) }
            };

            service.Start();

            using (IZookeeperClient zon = await ServiceBus.Register(serviceInfo))
            {
                Console.WriteLine("Greeter server listening on port " + port);
                Console.WriteLine("Press any key to stop the server...");
                Console.ReadKey();
                service.ShutdownAsync().Wait();
            }
        }
Пример #29
0
        public async Task ServiceBus_PublishIntegrationEventsAsyncPersistsChangesToContext()
        {
            var @event  = new FakeIntegrationEvent("Fake Value");
            var options = SetupContext();

            using (var context = new InfrastructureContext(options))
            {
                var mockSerializer = new Mock <IMessageSerializer>();
                var sut            = new ServiceBus(
                    Mock.Of <IMessageSerializer>(),
                    Mock.Of <IHttpContextAccessor>(),
                    Mock.Of <IQueueClient>(),
                    Mock.Of <ITopicClient>(),
                    Mock.Of <ILogger>(),
                    context);


                await sut.PublishEventsAsync(@event);
            }

            using (var context = new InfrastructureContext(options))
            {
                var eventEntity = await context.IntegrationEvents.FindAsync(@event.MessageId);

                Assert.NotNull(eventEntity);
                Assert.Equal(@event.MessageId, eventEntity.Id);
            }
        }
Пример #30
0
        public override async Task <SpeechletResponse> HandleIntentAsync(IntentRequest intentRequest, Session session)
        {
            if (intentRequest.DialogState == IntentRequest.DialogStateEnum.STARTED || intentRequest.DialogState == IntentRequest.DialogStateEnum.IN_PROGRESS)
            {
                return(new SpeechletResponse
                {
                    Directives = new List <Directive>
                    {
                        new DialogDelegateDirective()
                        {
                            UpdatedIntent = intentRequest?.Intent
                        }
                    }
                });
            }

            var result   = String.Empty;
            var intent   = intentRequest?.Intent;
            var command  = intent.Name;
            var argument = String.Empty;

            switch (intent.Name)
            {
            case GitIntents.Status:
                return(BuildSpeechletResponse("Okay", "The file changes dot txt has been modified.", true));

            case GitIntents.Add:
                result = "All changes have been staged.";
                break;

            case GitIntents.Commit:
                intent.Slots.TryGetValue(GitSlots.CommitMessage, out Slot slot);
                argument = slot?.Value;
                result   = "I committed your changes.";
                break;

            case GitIntents.Pull:

                result = "Upstream branches have been pulled.";
                break;

            case GitIntents.Push:
                intent.Slots.TryGetValue(GitSlots.RemoteBranch, out Slot branchSlot);
                intent.Slots.TryGetValue(GitSlots.RemoteRepository, out Slot repositorySlot);
                argument = repositorySlot?.Value + " " + branchSlot?.Value;
                result   = $"I successfully pushed your changes to {repositorySlot?.Value} {branchSlot?.Value}.";
                break;
            }

            var commandDto = new Command
            {
                CommandText = command.ToLower(),
                Argument    = argument
            };

            var serviceBus = new ServiceBus(ServiceBusQueues.GitQueue);
            await serviceBus.SendMessage(JsonConvert.SerializeObject(commandDto));

            return(BuildSpeechletResponse("Okay", result, true));
        }
Пример #31
0
        public void Start()
        {
            Log.Assign(new Log4NetLog(LogManager.GetLogger(typeof(Host))));

            _container = new WindsorContainer();

            _container.RegisterDataAccessCore();
            _container.RegisterDataAccess("Shuttle.ProcessManagement");

            _container.Register(Component.For <IEventStore>().ImplementedBy <EventStore>());
            _container.Register(Component.For <IKeyStore>().ImplementedBy <KeyStore>());
            _container.Register(Component.For <ISerializer>().ImplementedBy <DefaultSerializer>());
            _container.Register(Component.For <IEventStoreQueryFactory>().ImplementedBy <EventStoreQueryFactory>());
            _container.Register(Component.For <IKeyStoreQueryFactory>().ImplementedBy <KeyStoreQueryFactory>());

            var subscriptionManager = SubscriptionManager.Default();

            subscriptionManager.Subscribe <OrderCreatedEvent>();
            subscriptionManager.Subscribe <InvoiceCreatedEvent>();
            subscriptionManager.Subscribe <EMailSentEvent>();

            var processConfiguration = ProcessSection.Configuration();

            ((DefaultProcessActivator)processConfiguration.ProcessActivator).RegisterMappings();

            _bus = ServiceBus.Create(
                c =>
            {
                c.MessageHandlerFactory(new CastleMessageHandlerFactory(_container));
                c.SubscriptionManager(subscriptionManager);
                c.AddModule(new ProcessModule(_container.Resolve <IDatabaseContextFactory>(), _container.Resolve <IEventStore>(), _container.Resolve <IKeyStore>(), processConfiguration));
            }).Start();
        }
Пример #32
0
        static void Main(string[] args)
        {
            var bus = ServiceBus.Run(c => c
                                     .SetServiceLocator(AppDomainUnityServiceLocator.Current)
                                     .MsmqTransport()
                                     .SetInputQueue("PSB.App2.Input")
                                     .SetErrorQueue("PSB.App2.Error")
                                     .AddEndpoint("Shared.ClientMessages", "PSB.App1.Input")
                                     .Dispatcher(d => d
                                                 .AddHandlers(typeof(Program).Assembly)
                                                 )
                                     );

            Console.WriteLine("Server started. Press enter to send message");

            while (true)
            {
                Console.ReadKey();

                var message = new SayHelloToClientMessage()
                {
                    Message = "Hello Client!"
                };
                bus.Send(message);
            }
        }
Пример #33
0
        private void InitializeServiceBus()
        {
            var serviceBus = new ServiceBus();

            serviceBus.Subscribe<MarketStateChangeRequest>(
                changeRequest => StockMarket.MarketState = changeRequest.NewState);

            ServiceBus = serviceBus;
        }
Пример #34
0
 static void Main(string[] args)
 {
     var bus = new ServiceBus("test_queue");
     bus.Start();
     string textMessage;
     while (!String.IsNullOrWhiteSpace((textMessage = Console.ReadLine())))
     {
         var message = new TestMessage { Id = Guid.NewGuid(), Timestamp = DateTime.Now, Message = textMessage };
         bus.Publish(message);
     }
 }
Пример #35
0
 static void Main(string[] args)
 {
     using (var bus = new ServiceBus("test_queue"))
     {
         bus.RegisterReplyGenerator<TestMessage>(m => new TestReply(m.Id));
         bus.MessageHandlers.Add<TestMessage>(m => Console.WriteLine("{0} : {1}", m.Timestamp, m.Message));
         bus.Start();
         while (!Console.KeyAvailable)
         {
             Thread.Sleep(1);
         }
     }
 }
Пример #36
0
        static void Main()
        {
            var bus = new ServiceBus { LocalEndpoint = "minibuss_publisher1" };

            bus.HandleSubscriptionsFor<SomethingHappenedEvent>();

            bus.Start();

            Task.Factory.StartNew(() => PublishingThread(bus), TaskCreationOptions.LongRunning);

            Console.WriteLine("Working, press ENTER to exit");
            Console.ReadLine();
        }
Пример #37
0
        /// <summary>
        /// create this factory. all parameters are mandatory.
        /// </summary>
        /// <param name="evernoteUri">evernote base url, like http://sandbox.evernote.com/</param>
        /// <param name="consumerKey">your personal consumer key that you got from Evernote</param>
        /// <param name="consumerSecret">your secret key that you got from Evernote</param>
        public StoreFactory(Uri evernoteUri, string consumerKey, string consumerSecret)
        {
            ParamCheck.NotNull("evernoteUri", evernoteUri);
            ParamCheck.NullNorEmpty("consumerKey", consumerKey);
            ParamCheck.NullNorEmpty("consumerSecret", consumerSecret);

            this.evernoteUri = evernoteUri;
            this.consumerKey = consumerKey;
            this.consumerSecret = consumerSecret;
            this.servicebus = new ServiceBus();

            //we are interested in auth event
            this.servicebus.AddSubscriber<AuthenticationEvent>(authenticationEventHandler);
        }
    	protected override void Before_each()
        {
            _builder = MockRepository.GenerateMock<IObjectBuilder>();
        	_builder.Stub(x => x.GetInstance<XmlMessageSerializer>()).Return(new XmlMessageSerializer());
			_endpointResolver = EndpointFactoryConfigurator.New(x =>
			{
				x.SetObjectBuilder(_builder);
				x.RegisterTransport<LoopbackEndpoint>();
			});

            _mockEndpoint = _endpointResolver.GetEndpoint(queueUri);

            _subscription = new Subscription(typeof (PingMessage), queueUri);
        	_serviceBus = new ServiceBus(_mockEndpoint, _builder, _endpointResolver);
        }
Пример #39
0
        private static void StartSubscriber(string queueName)
        {
            using (var bus = new ServiceBus(queueName))
            {
                bus.Start();
                bus.SubscribeTo<TestMessage>(publisherEndpoint, TestMessageHandler);

                while (!_tokenSource.Token.IsCancellationRequested)
                {
                    Thread.Sleep(1);
                }

                bus.Unsubscribe<TestMessage>(publisherEndpoint);
            }
        }
Пример #40
0
        static void Main(string[] args)
        {
            using (var bus = new ServiceBus("my_test_queue"))
            {
                bus.MessageHandlers.Add<TestReply>(r => Console.WriteLine("Got reply to: {0}, Sent on second: {1}", r.ReplyTo, r.SecondSent));
                bus.TargetEndpoints.SetFor<TestMessage>(new BusEndpoint(".", "test_queue"));
                bus.Start();

                var textMessage = Console.ReadLine();
                while (!String.IsNullOrWhiteSpace(textMessage))
                {
                    bus.Send(new SpecialTestMessage { Id = Guid.NewGuid(), Timestamp = DateTime.Now, Message = textMessage, SpecialnessFactor = 3 });
                    textMessage = Console.ReadLine();
                }
            }
        }
Пример #41
0
        static void Main()
        {
            var bus = new ServiceBus { LocalEndpoint = "minibuss_receiver1" };

            bus.RegisterMessageHandler<HelloCommand>(command =>
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(command.Message + " Guid: " + command.Guid + ", Number: " + command.Number);

                bus.Reply(command, new HelloResponse { Guid = Guid.NewGuid(), Message = "Hello back!" });
            });

            bus.Start();

            Console.WriteLine("Waiting for commands, press ENTER to exit");
            Console.ReadLine();
        }
Пример #42
0
        private void InitService()
        {
            ServiceBus bus = new ServiceBus();
            EventStore eventStore = new EventStore(bus);
            var repository = new Repository<InventoryItem>(eventStore);
            var commands = new CommandHandler<InventoryItem>(repository);

            bus.RegisterHandler<CreateInventoryItem>(commands.Create);
            bus.RegisterHandler<DeleteInventoryItem>(commands.Delete);

            var detail = new InventoryItemCreatedHandle();
            bus.RegisterHandler<InventoryItemCreated>(detail.Create);
            bus.RegisterHandler<ItemsDeletedFromInventory>(detail.Delete);
            bus.RegisterHandler<InventoryItemRenamed>(detail.Update);


            ServiceLocator.Bus = bus;
        }
Пример #43
0
        private static void StartListener(int listenerId)
        {
            var token = _tokenSource.Token;

            if(token.IsCancellationRequested)
                return;

            using (var bus = new ServiceBus("test_queue"))
            {
                bus.MessageHandlers.Add<TestMessage>(m => Console.WriteLine(String.Format("Listener {0} received \"{1}\"", listenerId, m.Message)));
                bus.Start();

                while (!token.IsCancellationRequested)
                {
                    Thread.Sleep(1);
                }
            }
        }
Пример #44
0
        static void Main()
        {
            var bus = new ServiceBus { LocalEndpoint = "minibuss_sender1" };

            bus.RegisterMessageEndpoint<HelloCommand>("minibuss_receiver1@localhost");

            bus.RegisterMessageHandler<HelloResponse>(reply =>
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Reply from receiver: " + reply.Message);
                    });

            bus.Start();    //start bus if expecting replies

            Task.Factory.StartNew(() => SendThread(bus), TaskCreationOptions.LongRunning);

            Console.WriteLine("Working, press ENTER to exit");
            Console.ReadLine();
        }
        public void SimpleTest()
        {
            var unity = new UnityContainer();
            var tracker = new Tracker();
            unity.RegisterInstance(tracker);

            var config = new Configuration(unity)
                .SetInputQueue("PSB.App1.Input1")
                .SetErrorQueue("PSB.App1.Error")
                .AddEndpoint("Paralect.ServiceBus.Test.Messages", "PSB.App2.Input1");

            var bus = new ServiceBus(config);
            bus.Run();

            var config2 = new Configuration(unity)
                .SetInputQueue("PSB.App2.Input1")
                .SetErrorQueue("PSB.App2.Error")
                .AddEndpoint("Paralect.ServiceBus.Test.Messages", "PSB.App1.Input1")
                .AddHandlers(Assembly.GetExecutingAssembly())
                .AddInterceptor(typeof(FirstInterceptor))
                .AddInterceptor(typeof(SecondInterceptor));

            var bus2 = new ServiceBus(config2);
            bus2.Run();

            var msg = new SimpleMessage3
            {
                Id = Guid.NewGuid(),
                Text = "From dddbfdfdgfgusd! Muaha!"
            };

            bus.Send(msg);

            Thread.Sleep(3000);

            Assert.AreEqual(1, tracker.Handlers.Count);
            Assert.AreEqual(2, tracker.Interceptors.Count);
            Assert.AreEqual(typeof(SimpleMessage3), tracker.Handlers[0]);
            Assert.AreEqual(typeof(FirstInterceptor), tracker.Interceptors[0]);
            Assert.AreEqual(typeof(SecondInterceptor), tracker.Interceptors[1]);
        }
Пример #46
0
        public void Test()
        {
            Parallel.For(0, 15, (i, state) =>
            {
                var unity = new UnityContainer();
                var tracker = new Tracker();
                unity.RegisterInstance(tracker);

                var config = new Configuration(unity)
                    .SetName("PS " + i)
                    .SetInputQueue("PSB.App1.Input")
                    .SetErrorQueue("PSB.App1.Error")
                    .AddEndpoint("Paralect.ServiceBus.Test.Messages", "PSB.App2.Input");

                using (var bus = new ServiceBus(config))
                {
                    bus.Run();
                    Thread.Sleep(10);
                }
            });
        }
Пример #47
0
        public void ShouldSendCommandsToCorrectEndpoints()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient3 = A.Fake<IServiceEndpointClient>();

            ICommand command1 = A.Fake<ICommand>();
            ICommand command2 = A.Fake<ICommand>();
            ICommand command3 = A.Fake<ICommand>();

            A.CallTo(() => serviceEndpointClient1.CanHandle(A<ICommand>._)).Returns(true);
            A.CallTo(() => serviceEndpointClient2.CanHandle(A<ICommand>._)).Returns(false);
            A.CallTo(() => serviceEndpointClient3.CanHandle(A<ICommand>._)).Returns(true);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2, serviceEndpointClient3 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            serviceBus.SendAsync(command1);

            A.CallTo(() => serviceEndpointClient1.SendAsync(command1)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.SendAsync(command1)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpointClient3.SendAsync(command1)).MustHaveHappened(Repeated.Exactly.Once);

            serviceBus.SendAsync(new[]{command2, command3});

            A.CallTo(() => serviceEndpointClient1.SendAsync(command2)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.SendAsync(command2)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpointClient3.SendAsync(command2)).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => serviceEndpointClient1.SendAsync(command3)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.SendAsync(command3)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpointClient3.SendAsync(command3)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #48
0
        public void ShouldSendRequestsToCorrectEndpoints()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient3 = A.Fake<IServiceEndpointClient>();

            IRequest request = A.Fake<IRequest>();

            A.CallTo(() => serviceEndpointClient1.CanHandle(request)).Returns(true);
            A.CallTo(() => serviceEndpointClient2.CanHandle(request)).Returns(false);
            A.CallTo(() => serviceEndpointClient3.CanHandle(request)).Returns(true);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2, serviceEndpointClient3 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IDisposable sub1 = serviceBus.GetResponses(request).Subscribe(A.Fake<IObserver<IResponse>>());

            A.CallTo(() => serviceEndpointClient1.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.GetResponses(request)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpointClient3.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Once);

            IDisposable sub2 = serviceBus.GetResponses<IResponse>(request).Subscribe(A.Fake<IObserver<IResponse>>());

            A.CallTo(() => serviceEndpointClient1.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Twice);
            A.CallTo(() => serviceEndpointClient2.GetResponses(request)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpointClient3.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Twice);

            sub1.Dispose();
            sub2.Dispose();
        }
Пример #49
0
        public void ShouldSetRequestIdsOnRequestsWhenUsingDefaultRequestCorrelationProvider()
        {
            const string requestId = "MyOwnRequestId";

            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<IResponse> observable1 = A.Fake<IObservable<IResponse>>();
            IObservable<IResponse> observable2 = A.Fake<IObservable<IResponse>>();

            IObserver<IResponse> observer1 = A.Fake<IObserver<IResponse>>();
            IObserver<IResponse> observer2 = A.Fake<IObserver<IResponse>>();

            IRequest request1 = A.Fake<IRequest>();
            IRequest request2 = A.Fake<IRequest>();

            request2.RequestId = requestId;

            A.CallTo(() => serviceEndpointClient1.CanHandle(request1)).Returns(true);
            A.CallTo(() => serviceEndpointClient2.CanHandle(request2)).Returns(true);

            A.CallTo(() => serviceEndpointClient1.GetResponses(request1)).Returns(observable1);
            A.CallTo(() => serviceEndpointClient2.GetResponses(request2)).Returns(observable2);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IObservable<IResponse> responses1 = serviceBus.GetResponses(request1);
            IObservable<IResponse> responses2 = serviceBus.GetResponses(request2);

            IDisposable sub1 = responses1.Subscribe(observer1);
            IDisposable sub2 = responses2.Subscribe(observer2);

            Assert.That(!string.IsNullOrEmpty(request1.RequestId), "RequestId not set on request");
            Assert.That(!string.IsNullOrEmpty(request1.RequesterId), "RequesterId not set on request");

            Assert.That(request2.RequestId, Is.EqualTo(requestId), "Custom RequestId was overriden");
            Assert.That(!string.IsNullOrEmpty(request2.RequesterId), "RequesterId not set on request");
            Assert.That(request1.RequesterId, Is.EqualTo(request2.RequesterId), "RequesterId should the same on both requests");

            sub1.Dispose();
            sub2.Dispose();
        }
Пример #50
0
        public void ShouldPublishEventsToCorrectEndpoints()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint3 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IEvent ev = A.Fake<IEvent>();

            A.CallTo(() => serviceEndpoint1.CanHandle(ev)).Returns(true);
            A.CallTo(() => serviceEndpoint2.CanHandle(ev)).Returns(false);
            A.CallTo(() => serviceEndpoint3.CanHandle(ev)).Returns(true);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2, serviceEndpoint3 });

            serviceBus.PublishAsync(ev);

            A.CallTo(() => serviceEndpoint1.PublishAsync(ev)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint2.PublishAsync(ev)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpoint3.PublishAsync(ev)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #51
0
 internal NoteStoreWrapper(Uri evernoteUri, string authToken, string shardId, ServiceBus servicebus)
     : base(new Uri(evernoteUri, "/edam/note/" + shardId))
 {
     this.authToken = authToken;
     servicebus.AddSubscriber<AuthenticationEvent>(this.authenticationHandler);
 }
Пример #52
0
        public void ShouldDisposeEndpointsWhenDisposed()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            ((IDisposable)serviceBus).Dispose();

            A.CallTo(() => serviceEndpoint1.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint2.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient1.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #53
0
        public void ShouldDisposeUnderlyingRequestSubscriptionOnlyWhenAllSubscriptionsDisposed()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<IRequest> observable1 = A.Fake<IObservable<IRequest>>();
            IObservable<IRequest> observable2 = A.Fake<IObservable<IRequest>>();

            IObserver<IRequest> observer1 = A.Fake<IObserver<IRequest>>();
            IObserver<IRequest> observer2 = A.Fake<IObserver<IRequest>>();

            A.CallTo(() => serviceEndpoint1.Requests).Returns(observable1);
            A.CallTo(() => serviceEndpoint2.Requests).Returns(observable2);

            IObserver<IRequest> requestSource1 = null;
            IObserver<IRequest> requestSource2 = null;

            A.CallTo(() => observable1.Subscribe(A<IObserver<IRequest>>._)).Invokes(call => requestSource1 = call.GetArgument<IObserver<IRequest>>(0));
            A.CallTo(() => observable2.Subscribe(A<IObserver<IRequest>>._)).Invokes(call => requestSource2 = call.GetArgument<IObserver<IRequest>>(0));

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IDisposable requestSub1 = serviceBus.Requests.Subscribe(observer1);
            IDisposable requestSub2 = serviceBus.Requests.Subscribe(observer2);

            Assert.That(requestSource1, Is.Not.Null);
            Assert.That(requestSource2, Is.Not.Null);

            IRequest request = A.Fake<IRequest>();

            requestSource1.OnNext(request);
            A.CallTo(() => observer1.OnNext(request)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(request)).MustHaveHappened(Repeated.Exactly.Once);

            // dispose of first subscriptions
            requestSub1.Dispose();

            // second subscription should still be active
            requestSource1.OnNext(request);
            A.CallTo(() => observer1.OnNext(request)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(request)).MustHaveHappened(Repeated.Exactly.Twice);

            // dispose of second subscriptions
            requestSub2.Dispose();

            // no subscriptions should be active
            requestSource1.OnNext(request);
            A.CallTo(() => observer1.OnNext(request)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(request)).MustHaveHappened(Repeated.Exactly.Twice);
        }
Пример #54
0
        public void ShouldHandleUnderlyingRequestSubscriptionErrorsOnTheExceptionChannel()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<IRequest> observable1 = A.Fake<IObservable<IRequest>>();
            IObservable<IRequest> observable2 = A.Fake<IObservable<IRequest>>();

            IObserver<IRequest> observer1 = A.Fake<IObserver<IRequest>>();
            IObserver<IRequest> observer2 = A.Fake<IObserver<IRequest>>();
            IObserver<Exception> observer3 = A.Fake<IObserver<Exception>>();

            A.CallTo(() => serviceEndpoint1.Requests).Returns(observable1);
            A.CallTo(() => serviceEndpoint2.Requests).Returns(observable2);

            IObserver<IRequest> requestSource1 = null;
            IObserver<IRequest> requestSource2 = null;

            A.CallTo(() => observable1.Subscribe(A<IObserver<IRequest>>._)).Invokes(call => requestSource1 = call.GetArgument<IObserver<IRequest>>(0));
            A.CallTo(() => observable2.Subscribe(A<IObserver<IRequest>>._)).Invokes(call => requestSource2 = call.GetArgument<IObserver<IRequest>>(0));

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IDisposable eventSub1 = serviceBus.Requests.Subscribe(observer1);
            IDisposable eventSub2 = serviceBus.Requests.Subscribe(observer2);
            IDisposable exceptionSub = serviceBus.Exceptions.Subscribe(observer3);

            Assert.That(requestSource1, Is.Not.Null);
            Assert.That(requestSource2, Is.Not.Null);

            IRequest request1 = A.Fake<IRequest>();
            IRequest request2 = A.Fake<IRequest>();

            requestSource1.OnNext(request1);
            A.CallTo(() => observer1.OnNext(request1)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(request1)).MustHaveHappened(Repeated.Exactly.Once);

            Exception exception = new Exception();
            requestSource1.OnError(exception);
            requestSource1.OnError(new Exception());
            requestSource1.OnError(new Exception());
            requestSource1.OnError(new Exception());
            A.CallTo(() => observer1.OnError(exception)).MustNotHaveHappened();
            A.CallTo(() => observer2.OnError(exception)).MustNotHaveHappened();

            requestSource2.OnNext(request2);
            A.CallTo(() => observer1.OnNext(request2)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(request2)).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => observer3.OnNext(A<Exception>._)).WhenArgumentsMatch(call => call.Get<Exception>(0).InnerException == exception).MustHaveHappened(Repeated.Exactly.Once);

            eventSub1.Dispose();
            eventSub2.Dispose();
            exceptionSub.Dispose();
        }
Пример #55
0
        public void ShouldOnlySubscribeToUnderlyingEndpointResponsesOnce()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<IResponse> observable1 = A.Fake<IObservable<IResponse>>();
            IObservable<IResponse> observable2 = A.Fake<IObservable<IResponse>>();

            IObserver<IResponse> observer1 = A.Fake<IObserver<IResponse>>();
            IObserver<IResponse> observer2 = A.Fake<IObserver<IResponse>>();

            IRequest request = A.Fake<IRequest>();

            A.CallTo(() => serviceEndpointClient1.CanHandle(request)).Returns(true);
            A.CallTo(() => serviceEndpointClient2.CanHandle(request)).Returns(true);

            A.CallTo(() => serviceEndpointClient1.GetResponses(request)).Returns(observable1);
            A.CallTo(() => serviceEndpointClient2.GetResponses(request)).Returns(observable2);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IObservable<IResponse> responses = serviceBus.GetResponses(request);

            IDisposable sub1 = responses.Subscribe(observer1);
            IDisposable sub2 = responses.Subscribe(observer2);

            A.CallTo(() => serviceEndpointClient1.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.GetResponses(request)).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => observable1.Subscribe(A<IObserver<IResponse>>._)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observable2.Subscribe(A<IObserver<IResponse>>._)).MustHaveHappened(Repeated.Exactly.Once);

            sub1.Dispose();
            sub2.Dispose();
        }
Пример #56
0
        private void SubscribeToImageMessages()
        {
            Log("Subscribing to ImageMessage messages");

            _serviceBus = ServiceBus
                .Setup(ServiceBusUtilities.GetServiceBusCredentials())
                .Subscribe<ImageMessage>(this.SaveImageToBlobStorage);

            Log("Subscribed to ImageMessage messages");
        }
Пример #57
0
        public void ShouldAttemptToSendResponseToAllEndpointsWhenExceptionsAreThrown()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint3 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IRequest request = A.Fake<IRequest>();
            IResponse response = A.Fake<IResponse>();

            A.CallTo(() => serviceEndpoint1.CanHandle(A<IResponse>._)).Returns(true);
            A.CallTo(() => serviceEndpoint2.CanHandle(A<IResponse>._)).Returns(true);
            A.CallTo(() => serviceEndpoint3.CanHandle(A<IResponse>._)).Returns(true);

            Exception originalException = new Exception("Something went wrong");
            A.CallTo(() => serviceEndpoint2.ReplyAsync(request, response)).Throws(originalException);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2, serviceEndpoint3 });

            AggregateException aggregateException = null;

            try
            {
                serviceBus.ReplyAsync(request, response);
            }
            catch (AggregateException ex)
            {
                aggregateException = ex;
                Console.WriteLine(ex);
            }

            Assert.That(aggregateException != null, "No aggregate exception was thrown");
            Assert.That(aggregateException.InnerExceptions.Any(e => e.InnerException == originalException), "Aggregate exception did not contain original exception");

            A.CallTo(() => serviceEndpoint1.ReplyAsync(request, response)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint2.ReplyAsync(request, response)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint3.ReplyAsync(request, response)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #58
0
        public void ShouldAttemptToSendCommandToAllEndpointsWhenExceptionsAreThrown()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient3 = A.Fake<IServiceEndpointClient>();

            ICommand command = A.Fake<ICommand>();
            ICommand command2 = A.Fake<ICommand>();

            A.CallTo(() => serviceEndpointClient1.CanHandle(A<ICommand>._)).Returns(true);
            A.CallTo(() => serviceEndpointClient2.CanHandle(A<ICommand>._)).Returns(true);
            A.CallTo(() => serviceEndpointClient3.CanHandle(A<ICommand>._)).Returns(true);

            Exception originalException = new Exception("Something went wrong");
            A.CallTo(() => serviceEndpointClient1.SendAsync(A<ICommand>._)).Returns(Task.FromResult(true));
            A.CallTo(() => serviceEndpointClient2.SendAsync(A<ICommand>._)).Throws(originalException);
            A.CallTo(() => serviceEndpointClient3.SendAsync(A<ICommand>._)).Returns(Task.FromResult(true));

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2, serviceEndpointClient3 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            AggregateException aggregateException = null;
            try
            {
                serviceBus.SendAsync(new[] {command, command2});
            }
            catch (AggregateException ex)
            {
                aggregateException = ex;
                Console.WriteLine(ex);
            }

            Assert.That(aggregateException != null, "No aggregate exception was thrown");
            Assert.That(aggregateException.InnerExceptions.Any(e => e.InnerException == originalException), "Aggregate exception did not contain original exception");

            A.CallTo(() => serviceEndpointClient1.SendAsync(command)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient2.SendAsync(command)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpointClient3.SendAsync(command)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #59
0
        public void ShouldSendResponsesToCorrectEndpoints()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint3 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IRequest request = A.Fake<IRequest>();
            IResponse response = A.Fake<IResponse>();

            A.CallTo(() => serviceEndpoint1.CanHandle(response)).Returns(true);
            A.CallTo(() => serviceEndpoint2.CanHandle(response)).Returns(false);
            A.CallTo(() => serviceEndpoint3.CanHandle(response)).Returns(true);

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2, serviceEndpoint3 });

            serviceBus.ReplyAsync(request, response);

            A.CallTo(() => serviceEndpoint1.ReplyAsync(request, response)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => serviceEndpoint2.ReplyAsync(request, response)).MustNotHaveHappened();
            A.CallTo(() => serviceEndpoint3.ReplyAsync(request, response)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #60
0
        public void ShouldReturnEventsFromUnderlyingEndpoints()
        {
            IServiceEndpoint serviceEndpoint1 = A.Fake<IServiceEndpoint>();
            IServiceEndpoint serviceEndpoint2 = A.Fake<IServiceEndpoint>();
            IServiceEndpointClient serviceEndpointClient1 = A.Fake<IServiceEndpointClient>();
            IServiceEndpointClient serviceEndpointClient2 = A.Fake<IServiceEndpointClient>();

            IObservable<IEvent> observable1 = A.Fake<IObservable<IEvent>>();
            IObservable<IEvent> observable2 = A.Fake<IObservable<IEvent>>();

            IObserver<IEvent> observer1 = A.Fake<IObserver<IEvent>>();
            IObserver<IEvent> observer2 = A.Fake<IObserver<IEvent>>();

            A.CallTo(() => serviceEndpointClient1.Events).Returns(observable1);
            A.CallTo(() => serviceEndpointClient2.Events).Returns(observable2);

            IObserver<IEvent> internalObserver1 = null;
            IObserver<IEvent> internalObserver2 = null;

            A.CallTo(() => observable1.Subscribe(A<IObserver<IEvent>>._)).Invokes(call => internalObserver1 = call.GetArgument<IObserver<IEvent>>(0));
            A.CallTo(() => observable2.Subscribe(A<IObserver<IEvent>>._)).Invokes(call => internalObserver2 = call.GetArgument<IObserver<IEvent>>(0));

            IServiceBus serviceBus = new ServiceBus(new[] { serviceEndpointClient1, serviceEndpointClient2 }, new[] { serviceEndpoint1, serviceEndpoint2 });

            IDisposable sub1 = serviceBus.Events.Subscribe(observer1);
            IDisposable sub2 = serviceBus.Events.Subscribe(observer2);

            Assert.That(internalObserver1, Is.Not.Null);
            Assert.That(internalObserver2, Is.Not.Null);

            IEvent event1 = A.Fake<IEvent>();
            IEvent event2 = A.Fake<IEvent>();
            internalObserver1.OnNext(event1);
            internalObserver2.OnNext(event2);

            A.CallTo(() => observer1.OnNext(event1)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(event1)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer1.OnNext(event2)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => observer2.OnNext(event2)).MustHaveHappened(Repeated.Exactly.Once);

            sub1.Dispose();
            sub2.Dispose();
        }