public void SetupSecondAzureServiceBusTestFixture()
        {
            _secondBus = CreateSecondBus();

            _secondBusHandle = _secondBus.Start();
            try
            {
                _secondBusSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondBus.Address));

                _secondInputQueueSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondInputQueueAddress));
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _secondBusHandle.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _secondBusHandle = null;
                    _secondBus = null;
                }

                throw;
            }
        }
        public void SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = _bus.Start();
            try
            {
                Await(() => _busHandle.Ready);

                _busSendEndpoint = _bus.GetSendEndpoint(_bus.Address).Result;
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = _bus.GetSendEndpoint(_inputQueueAddress).Result;
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The bus creation failed: {0}", ex);

                _busHandle.Stop();

                throw;
            }
        }
        public async Task Send <TWorkflowMessage>(IEndpointConfiguration endpointConfiguration, TWorkflowMessage workflowMessage, CancellationToken cancellationToken)
            where TWorkflowMessage : class, IWorkflowMessage
        {
            var sendEndpoint = await _busControl.GetSendEndpoint(endpointConfiguration.Address).ConfigureAwait(false);

            await sendEndpoint.Send(workflowMessage, cancellationToken).ConfigureAwait(false);
        }
Beispiel #4
0
        public async Task <IActionResult> executeplanning(RequiredAdaptation requiredAdaptation)
        {
            IEnumerable <MicroController> microControllers = await _executorService.GetPlanning(requiredAdaptation);

            //foreach (var mc in microControllers)
            // {
            //if (mc.Id == 1)
            //{
            Uri uri      = new Uri($"rabbitmq://localhost/regressiontest");
            var endPoint = await _bus.GetSendEndpoint(uri);

            await endPoint.Send(requiredAdaptation);

            //}

            //if (mc.Id == 2)
            //{
            Uri uri2      = new Uri($"rabbitmq://localhost/errerdetection");
            var endPoint2 = await _bus.GetSendEndpoint(uri2);

            await endPoint2.Send(requiredAdaptation);

            //}

            //if (mc.Id == 3)
            //{

            //}
            //}

            return(Ok(true));
        }
        public void SetupInMemoryTestFixture()
        {
            _bus = CreateBus();

            _busHandle = _bus.Start();
            try
            {
                _busSendEndpoint = Await(() => _bus.GetSendEndpoint(_bus.Address));
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = Await(() => _bus.GetSendEndpoint(_inputQueueAddress));
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _busHandle?.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus       = null;
                }

                throw;
            }
        }
        public async Task <IHttpActionResult> RegiterNew(OrderDTO orderDTO)
        {
            var order = new Order(orderDTO.CustomerName, orderDTO.CustomerPhone, orderDTO.PizzaID, Guid.NewGuid());

            _dbSet.Add(order);
            await _context.SaveChangesAsync();

            orderDTO = (OrderDTO) new OrderDTO().InjectFrom(order);
            orderDTO.StatusDescription = ((OrderStatus)order.Status).ToString();


            var endPoint = await _bus.GetSendEndpoint(_sendToUri);

            await endPoint.Send <IRegisterOrderCommand>(new
            {
                OrderID       = order.OrderID,
                CustomerName  = orderDTO.CustomerName,
                CustomerPhone = orderDTO.CustomerPhone,
                PizzaID       = orderDTO.PizzaID,
                CorrelationId = order.CorrelationId,
                Timestamp     = DateTime.UtcNow
            });

            return(Created(new Uri(_baseUri + orderDTO.OrderID), orderDTO));
        }
        public void SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = _bus.Start();
            try
            {
                _busSendEndpoint = _bus.GetSendEndpoint(_bus.Address).Result;
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = _bus.GetSendEndpoint(_inputQueueAddress).Result;
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _bus.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus       = null;
                }

                throw;
            }
        }
Beispiel #8
0
        public async Task Send <T>(T command, string queue) where T : CommandEvent
        {
            var sendToUri = new Uri($"{"rabbitmq://localhost/"}{queue}");
            var endPoint  = await _bus.GetSendEndpoint(sendToUri);

            await endPoint.Send <T>(command);
        }
        public virtual async Task Send(ICommand command)
        {
            if (_busControl == null)
            {
                throw new InvalidOperationException("MassTransit bus must be started before sending commands.");
            }

            var commandType = command.GetType();

            ISendEndpoint endpoint;

            if (_options.UseInMemoryBus)
            {
                endpoint = await _busControl.GetSendEndpoint(
                    new Uri($"loopback://localhost/{commandType.Name}"))
                           .ConfigureAwait(false);
            }
            else
            {
                endpoint = await _busControl.GetSendEndpoint(
                    new Uri($"{_options.RabbitMQUri}/{commandType.Name}"))
                           .ConfigureAwait(false);
            }

            await endpoint.Send(command, commandType).ConfigureAwait(false);
        }
Beispiel #10
0
        public async Task CreateArticle(CreateArticle createArticle)
        {
            var sendEndpoint =
                await _busControl.GetSendEndpoint(new Uri("rabbitmq://localhost:5672/helloworld"));

            await sendEndpoint.Send(createArticle);
        }
        public void SetupSecondAzureServiceBusTestFixture()
        {
            _secondBus = CreateSecondBus();

            _secondBusHandle = _secondBus.Start();
            try
            {
                _secondBusSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondBus.Address));

                _secondInputQueueSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondInputQueueAddress));
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _secondBusHandle.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _secondBusHandle = null;
                    _secondBus       = null;
                }

                throw;
            }
        }
Beispiel #12
0
        public Task Send <T>(string channel, T message, Type messageType, CancellationToken cancellationToken = default(CancellationToken)) where T : class
        {
            var sendEndPoint = _busControl.GetSendEndpoint(new Uri($"{_configuration.GetConnectionString(MicroservicesConstants.MessageBusHost)}/{channel}")).Result;

            sendEndPoint.Send(message, messageType);

            return(Task.CompletedTask);
        }
Beispiel #13
0
        public async Task PriceOrder(string locationCode, IPriceOrderResponse pulseResponse)
        {
            await Task.Delay(3000);

            var endPoint = await _busControl.GetSendEndpoint(new Uri($"{CustomKey.RABBITMQ_BASE_ENDPOINT}/{CustomKey.RABBITMQ_PRICE_ORDER_RESPONSE_ENDPOINT}"));

            await endPoint.SendWithHeaders <IPriceOrderResponse>(pulseResponse, _consumeContext);
        }
        public async Task SendAssignDeviceMsg(string deviceId, CancellationToken token)
        {
            var endpoint = await _busControl.GetSendEndpoint(new Uri($"queue:{string.Format(QUEUE_NAME_FORMAT, deviceId)}"));

            await endpoint.Send <IDeviceStatus>(new DataCollection
            {
                DeviceId = deviceId,
                Status   = "Assigned",
                When     = DateTime.UtcNow
            });
        }
Beispiel #15
0
        /// Sends a message
        public async Task Send(CreateAccount msg)
        {
            if (msg == null)
            {
                return;
            }

            // sends a messaged to be consumed by CreateAccountConsumer
            var sendEndpoint = await bus.GetSendEndpoint(new Uri("loopback://localhost/queue_name"));

            await sendEndpoint.Send(msg);
        }
Beispiel #16
0
        private static async void DownloadPackage(IBusControl bus, string packageId)
        {
            var endpoint = await bus.GetSendEndpoint(new Uri(bus.Address, BusConstants.RepositoryManagerDownloadPackageMessageQueue));

            var updateEndpoint = await bus.GetSendEndpoint(new Uri(bus.Address, BusConstants.IndexManagerUpdateArchiveRecordMessageQueue));

            Console.WriteLine("Sending message on queue...");
            // Need to update our dummy record, to not contain the primary data link. If this is not done, we get an exception
            // when creating the Gebrauchskopie, as we find two VE with the same primary data link.
            await updateEndpoint.Send <IUpdateArchiveRecord>(new
            {
                MutationId    = 0,
                ArchiveRecord = new ArchiveRecord
                {
                    ArchiveRecordId = "9999",
                    Security        = new ArchiveRecordSecurity
                    {
                        MetadataAccessToken = new List <string> {
                            "BAR"
                        }, PrimaryDataFulltextAccessToken = new List <string> {
                            "BAR"
                        },
                        PrimaryDataDownloadAccessToken = new List <string> {
                            "BAR"
                        }
                    },
                    Metadata = new ArchiveRecordMetadata {
                        PrimaryDataLink = ""
                    }
                }
            });

            await endpoint.Send <IDownloadPackage>(new
            {
                PackageId         = packageId,
                ArchiveRecordId   = 9999, // Id not relevant for our use case
                CallerId          = "MyId",
                RetentionCategory = CacheRetentionCategory.UsageCopyPublic
            });


            Console.WriteLine("Waiting on queue to respond...");
            DownloadReceivedEvent.WaitOne();
            Console.WriteLine("Processed downloaded message");

            AssetReadyReceivedEvent.WaitOne();

            Console.WriteLine("Queue received message");
            Console.WriteLine("");
            Console.WriteLine("");
        }
Beispiel #17
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("How many jobs:");
            var response = Console.ReadLine();

            int.TryParse(response, out var n);
            n = n > 0 ? n : new Random().Next(100, 5000);

            _logger.LogDebug("Starting bus");
            await _busControl.StartAsync(cancellationToken).ConfigureAwait(false);

            _logger.LogDebug("Bus started");

            _logger.LogInformation("Testing with {Count} jobs", n);
            var endpoint = await _busControl.GetSendEndpoint(new Uri("loopback://localhost/create_jobs")).ConfigureAwait(false);

            await endpoint.Send(new CreateJobsCommand
            {
                CorrelationId = NewId.Next().ToString(),
                // ideally we wouldn't do this
                // instead we would retrieve jobs from a store inside the consumer
                // aim to keep message sizes small
                Jobs = Enumerable.Range(0, n).Select(_ => NewId.NextGuid().ToString()).ToArray(),
            }).ConfigureAwait(false);
        }
Beispiel #18
0
        public async Task Send <T>(T message, string reciever) where T : class, ICommand
        {
            var sendToUri = new Uri($"{_bus.Address.Scheme}://{_bus.Address.Host}/{reciever}");
            var endPoint  = await _bus.GetSendEndpoint(sendToUri);

            await endPoint.Send(message);
        }
Beispiel #19
0
        private static void AppendPackage(IBusControl bus, string packageId)
        {
            var endpoint = bus.GetSendEndpoint(new Uri(bus.Address, BusConstants.RepositoryManagerArchiveRecordAppendPackageMessageQueue)).Result;

            Console.WriteLine("Sending message on queue...");
            var t = endpoint.Send <IArchiveRecordAppendPackage>(new
            {
                MutationId    = 1,
                ArchiveRecord = new ArchiveRecord
                {
                    ArchiveRecordId = "9999",
                    Security        = new ArchiveRecordSecurity
                    {
                        MetadataAccessToken = new List <string> {
                            "BAR"
                        }, PrimaryDataFulltextAccessToken = new List <string> {
                            "BAR"
                        },
                        PrimaryDataDownloadAccessToken = new List <string> {
                            "BAR"
                        }
                    },
                    Metadata = new ArchiveRecordMetadata {
                        PrimaryDataLink = packageId
                    }
                }
            });
        }
Beispiel #20
0
        public async Task PublishMessageAsync(dynamic e)
        {
            var address  = "rabbitmq://localhost/messages";
            var endpoint = await _bus.GetSendEndpoint(new Uri(address));

            await endpoint.Send(e);
        }
Beispiel #21
0
        public async Task Send <T>(T message, string endpoint) where T : class
        {
            endpoint = GetEndpointAddressByName(endpoint) ?? endpoint;
            var se = await _control.GetSendEndpoint(new System.Uri(endpoint));

            await se.Send(message);
        }
Beispiel #22
0
        private static async Task SendMessage <MessageType>(IBusControl bus, MessageType msg, string host = null, int port = 0, string queue = null)
            where MessageType : class
        {
            if (host == null || queue == null)
            {
                await bus.Publish <MessageType>(msg);
            }
            else
            {
                // Send message to the specific host and queue
                Uri uri;

                if (port != 0)
                {
                    uri = new Uri($"rabbitmq://{host}:{port}/{queue}");
                }
                else
                {
                    uri = new Uri($"rabbitmq://{host}/{queue}");
                }

                var ep = await bus.GetSendEndpoint(uri);

                await ep.Send <MessageType>(msg);
            }
        }
        public async Task <ActionResult> DeliverProduct([FromBody] DeliveryModel deliveryModel)
        {
            try
            {
                //deliver product
                var identity = (System.Security.Claims.ClaimsIdentity)HttpContext.User.Identity;
                var userId   = identity.Claims.FirstOrDefault(c => c.Type == "userId").Value;
                DeliveryDb.deliveryList.Add(new DeliveryModel(DeliveryDb.deliveryList.Count + 1, deliveryModel.orderId, userId, deliveryModel.DeliveredBy, deliveryModel.DeliveryStatus));

                //change status in order
                Uri uri      = new Uri($"rabbitmq://{_config.GetValue<string>("RabbitMQHostName")}/delStatus");
                var endPoint = await _bus.GetSendEndpoint(uri);

                var order = new Common.OrderDetails();
                order.OrderId = deliveryModel.orderId;
                order.UserId  = deliveryModel.userId;
                order.IsDeliverySuccessful = deliveryModel.DeliveryStatus;
                await endPoint.Send(order);

                _log.LogInformation("Order has been delivered.");
                return(Ok("Order Delivered"));
            }
            catch (Exception ex)
            {
                _log.LogInformation("Order can't be delivered.");
                return(Ok("Order can't be delivered."));
            }
        }
Beispiel #24
0
        /// <summary>
        /// Sends registration message to the other application
        /// </summary>
        private static void SendMessage()
        {
            string address = "rabbitmq://localhost";
            string queue   = "uppgift4.domains.queueGrade";
            Uri    rootUri = new Uri(address);

            IBusControl busControl = Bus.Factory.CreateUsingRabbitMq(r =>
            {
                r.Host(rootUri, settings =>
                {
                    settings.Username("guest");
                    settings.Password("guest");
                });
            });

            Task <ISendEndpoint> sendEndpointTask = busControl.GetSendEndpoint(new Uri(string.Concat(address, "/", queue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;

            while (true)
            {
                var message = CreateMessage();

                Task sendTask = sendEndpoint.Send <IStudentRegistration>(new
                {
                    Ideal      = message[0],
                    CourseCode = message[1],
                    Term       = message[2],
                    ExamNumber = message[3],
                    Grade      = message[4]
                });
                WaitForMessage();
            }
        }
        public static async Task Send <T>(this IBusControl busControl, T message, string queue) where T : class
        {
            if (Uri.TryCreate(busControl.Address, queue, out Uri endpointUri))
            {
                ISendEndpoint sendEndpoint;
                string        key = endpointUri.ToString();

                if (Endpoints.ContainsKey(key))
                {
                    sendEndpoint = Endpoints[key];
                }
                else
                {
                    lock (SyncLock)
                    {
                        if (Endpoints.ContainsKey(key))
                        {
                            sendEndpoint = Endpoints[key];
                        }
                        else
                        {
                            sendEndpoint = busControl.GetSendEndpoint(endpointUri).Result;
                            Endpoints.Add(key, sendEndpoint);
                        }
                    }
                }

                await sendEndpoint.Send(message);
            }
            else
            {
                throw new ConfigurationException($"We cannot initialize a new Uri from these sources: Address:{busControl.Address} Queue:{queue}");
            }
        }
Beispiel #26
0
        private static void ScheduleMessagesWithQuartzInMemory()
        {
            string rabbitMqAddress = "rabbitmq://localhost:5672/accounting";
            string rabbitMqQueue   = "mycompany.queues.news.scheduled";
            Uri    rabbitMqRootUri = new Uri(rabbitMqAddress);

            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                rabbit.Host(rabbitMqRootUri, settings =>
                {
                    settings.Password("accountant");
                    settings.Username("accountant");
                });

                rabbit.UseInMemoryScheduler();
            });
            Uri sendUri = new Uri(string.Concat(rabbitMqAddress, "/", rabbitMqQueue));
            Task <ISendEndpoint> sendEndpointTask = rabbitBusControl.GetSendEndpoint(sendUri);
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;

            Task <ScheduledMessage <IWorldNews> > scheduledMessageTask = sendEndpoint.ScheduleSend <IWorldNews>
                                                                             (new Uri("rabbitmq://localhost:5672/quartz"), TimeSpan.FromSeconds(30), new { Message = "The world is going down." });
            ScheduledMessage <IWorldNews> scheduledMessage = scheduledMessageTask.Result;

            Console.ReadKey();
        }
Beispiel #27
0
        /// <summary>
        /// Послать сообщение в очередь
        /// </summary>
        /// <typeparam name="T">тип сообщения</typeparam>
        /// <param name="message">сообщение</param>
        /// <returns>Task</returns>
        public async Task Send <T>(T message) where T : class, IWithQueueName
        {
            CheckForNull(message);

            var queueName = GetQueueNameOrThrow(message);

            InitBusAndThrowOnError();

            var sendEndpoint = await _bus.GetSendEndpoint(ComposeUri(queueName));

            if (sendEndpoint == null)
            {
                throw new Exception($"Не удалось найти очередь {queueName}");
            }
            await sendEndpoint.Send(message, pc => pc.SetAwaitAck(false));
        }
        public async Task <IActionResult> RegisterOrder(OrderViewModel model)
        {
            MemoryStream memory = new MemoryStream();

            using (var uploadedFile = model.File.OpenReadStream())
            {
                await uploadedFile.CopyToAsync(memory);
            }

            model.ImageData  = memory.ToArray();
            model.PictureUrl = model.File.FileName;
            model.OrderId    = Guid.NewGuid();
            var sendToUri = new Uri($"{RabbitMqMassTransitConstants.RabbitMqUri }/" +

                                    $"{RabbitMqMassTransitConstants.RegisterOrderCommandQueue}");

            var endPoint = await _busControl.GetSendEndpoint(sendToUri);

            await endPoint.Send <IRegisterOrderCommand>(
                new
            {
                model.OrderId,
                model.UserEmail,
                model.ImageData,
                model.PictureUrl
            });

            ViewData["OrderId"] = model.OrderId;
            return(View("Thanks"));
        }
Beispiel #29
0
        private void CreateOrder(CreateOrderModel createOrderModel)
        {
            var sendToUri = new Uri($"{MqConstants.RabbitMqUri}{MqConstants.OrderQueue}");
            var endPoint  = _bus.GetSendEndpoint(sendToUri).Result;

            endPoint.Send <ICreateOrderCommand>(createOrderModel).Wait();
        }
        public static async Task SendNewAccountMessage(IBusControl publishEndpoint, Contracts.IAccount newAccount)
        {
            var destinationAddress = new Uri("rabbitmq://localhost/consumer_queue");
            var destination        = await publishEndpoint.GetSendEndpoint(destinationAddress);

            await destination.Send <Contracts.IAccount>(newAccount);
        }
Beispiel #31
0
        private static void RunMessageBus()
        {
            string rabbitMqAddress = "rabbitmq://localhost:5672/payment";
            string rabbitMqQueue   = "superdigital.payments.orderpayments";
            Uri    rabbitMqRootUri = new Uri(rabbitMqAddress);

            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                rabbit.Host(rabbitMqRootUri, settings =>
                {
                    settings.Password("guest");
                    settings.Username("guest");
                });
            });

            Task <ISendEndpoint> sendEndpointTask = rabbitBusControl.GetSendEndpoint(new Uri(string.Concat(rabbitMqAddress, "/", rabbitMqQueue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;


            for (int i = 0; i < 100; i++)
            {
                Task sendTask = sendEndpoint.Send <ICreatePayment>(new
                {
                    CreditAccount = 5587,
                    DebitAccount  = 6698,
                    Value         = i + 580,
                    PaymentType   = "Salary"
                });

                sendTask.Wait();
                Console.WriteLine("Mensagem {0} enviada", i);
            }
            Console.ReadKey();
        }
        public void SetupSecondAzureServiceBusTestFixture()
        {
            _secondBus = CreateSecondBus();

            _secondBusHandle = _secondBus.Start();
            try
            {
                _secondBusSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondBus.Address));

                _secondInputQueueSendEndpoint = Await(() => _secondBus.GetSendEndpoint(_secondInputQueueAddress));
            }
            catch (Exception ex)
            {
                Console.WriteLine("The bus creation failed: {0}", ex);

                _secondBusHandle.Stop();

                throw;
            }
        }
Beispiel #33
0
        public BusTestScenario(TimeSpan timeout, IBusControl busControl)
        {
            _timeout = timeout;
            _busControl = busControl;

            Received = new ReceivedMessageList(timeout);
            _skipped = new ReceivedMessageList(timeout);
            _published = new PublishedMessageList(timeout);

            _tokenSource = new CancellationTokenSource(timeout);
            CancellationToken = _tokenSource.Token;

            _subjectSendEndpoint = _busControl.GetSendEndpoint(new Uri("loopback://localhost/input_queue")).Result;

            var testSendObserver = new TestSendObserver(timeout);
            Sent = testSendObserver.Messages;
            _subjectSendEndpoint.ConnectSendObserver(testSendObserver);

            var consumeObserver = new TestConsumeObserver(timeout);
            Received = consumeObserver.Messages;
            busControl.ConnectConsumeObserver(consumeObserver);

            _busHandle = _busControl.Start();
        }
        public async Task SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = await _bus.StartAsync();
            try
            {
                _busSendEndpoint = await _bus.GetSendEndpoint(_bus.Address);
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = await _bus.GetSendEndpoint(_inputQueueAddress);
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        await _bus.StopAsync(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus = null;
                }

                throw;
            }
        }
        public void SetupInMemoryTestFixture()
        {
            _bus = CreateBus();

            _busHandle = _bus.Start();
            try
            {
                _busSendEndpoint = Await(() => _bus.GetSendEndpoint(_bus.Address));
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = Await(() => _bus.GetSendEndpoint(_inputQueueAddress));
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _busHandle?.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus = null;
                }

                throw;
            }
        }
        public void SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = _bus.Start();
            try
            {
                Await(() => _busHandle.Ready);

                _busSendEndpoint = _bus.GetSendEndpoint(_bus.Address).Result;
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = _bus.GetSendEndpoint(_inputQueueAddress).Result;
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The bus creation failed: {0}", ex);

                _busHandle.Stop();

                throw;
            }
        }