public MessageReceiver GetMessageReceiver(string topic, string subscription)
        {
            var    connectionStr = Environment.GetEnvironmentVariable(ServiceBusConnectionString);
            string path          = EntityNameHelper.FormatSubscriptionPath(topic, subscription);

            return(new MessageReceiver(connectionStr, path));
        }
Ejemplo n.º 2
0
        IBrokeredMessageReceiver CreateBrokeredMessageReceiver(string topicPath, string subscriptionName, Action <IReceiveEndpointConfigurator> configure)
        {
            if (string.IsNullOrWhiteSpace(topicPath))
            {
                throw new ArgumentNullException(nameof(topicPath));
            }
            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            var subscriptionPath = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionName);

            return(_receivers.GetOrAdd(subscriptionPath, name =>
            {
                var topicConfigurator = new TopicConfigurator(topicPath, false);
                var settings = new SubscriptionEndpointSettings(topicConfigurator.GetTopicDescription(), subscriptionName);

                var endpointConfiguration = _hostConfiguration.CreateSubscriptionEndpointConfiguration(settings);

                var configurator = new SubscriptionBrokeredMessageReceiverConfiguration(_hostConfiguration, endpointConfiguration);

                configure(configurator);

                return configurator.Build();
            }));
        }
Ejemplo n.º 3
0
        protected override IAsyncResult OnBeginCreateReceiver(TimeSpan timeout, AsyncCallback callback, object state)
        {
            string str = EntityNameHelper.FormatSubscriptionPath(base.Path, base.ClientId);
            AmqpMessageReceiver amqpMessageReceiver = new AmqpMessageReceiver(this.messagingFactory, str, new MessagingEntityType?(MessagingEntityType.VolatileTopicSubscription), base.RetryPolicy, ReceiveMode.ReceiveAndDelete, base.Filter);

            return(new CompletedAsyncResult <AmqpMessageReceiver>(amqpMessageReceiver, callback, state));
        }
Ejemplo n.º 4
0
        public async Task <long> PurgeMessages(string connectionString, string topicPath, string subscriptionPath,
                                               bool isDlq)
        {
            var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath);

            path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path;

            long purgedCount      = 0;
            var  receiver         = new MessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete);
            var  operationTimeout = TimeSpan.FromSeconds(5);

            while (true)
            {
                var messages = await receiver.ReceiveAsync(_maxMessageCount, operationTimeout);

                if (messages == null || messages.Count == 0)
                {
                    break;
                }

                purgedCount += messages.Count;
            }

            await receiver.CloseAsync();

            return(purgedCount);
        }
Ejemplo n.º 5
0
        public async Task DeadletterMessage(string connectionString, string topicPath, string subscriptionPath,
                                            Message message)
        {
            var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath);

            var receiver = new MessageReceiver(connectionString, path, ReceiveMode.PeekLock);

            while (true)
            {
                var messages = await receiver.ReceiveAsync(_maxMessageCount);

                if (messages == null || messages.Count == 0)
                {
                    break;
                }

                var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId));
                if (foundMessage != null)
                {
                    await receiver.DeadLetterAsync(foundMessage.SystemProperties.LockToken);

                    break;
                }
            }

            await receiver.CloseAsync();
        }
Ejemplo n.º 6
0
        public async Task Capture_Transaction_When_Receive_From_Topic_Subscription()
        {
            await using var scope = await TopicScope.CreateWithTopicAndSubscription(_adminClient);

            var sender   = new MessageSender(_environment.ServiceBusConnectionString, scope.TopicName);
            var receiver = new MessageReceiver(_environment.ServiceBusConnectionString,
                                               EntityNameHelper.FormatSubscriptionPath(scope.TopicName, scope.SubscriptionName));

            await sender.SendAsync(
                new Message(Encoding.UTF8.GetBytes("test message"))).ConfigureAwait(false);

            await receiver.ReceiveAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);

            if (!_sender.WaitForTransactions(TimeSpan.FromMinutes(2)))
            {
                throw new Exception("No transaction received in timeout");
            }

            _sender.Transactions.Should().HaveCount(1);
            var transaction = _sender.FirstTransaction;

            var subscription = $"{scope.TopicName}/Subscriptions/{scope.SubscriptionName}";

            transaction.Name.Should().Be($"{ServiceBus.SegmentName} RECEIVE from {subscription}");
            transaction.Type.Should().Be(ApiConstants.TypeMessaging);

            transaction.Links.Should().NotBeNullOrEmpty();

            transaction.Context.Message.Should().NotBeNull();
            transaction.Context.Message.Queue.Should().NotBeNull();
            transaction.Context.Message.Queue.Name.Should().Be(subscription);
        }
        static void ReceiveFromSub(string topic, string sub)
        {
            var entityPath = EntityNameHelper.FormatSubscriptionPath(topic, sub);
            var receiver   = new MessageReceiver(SBConnectionString, entityPath, ReceiveMode.ReceiveAndDelete);

            RegisterMessageHandler(receiver);
        }
        protected override IAsyncResult OnBeginCreateReceiver(TimeSpan timeout, AsyncCallback callback, object state)
        {
            string str = EntityNameHelper.FormatSubscriptionPath(base.Path, base.ClientId);
            CreateReceiverLinkSettings createReceiverLinkSetting = new CreateReceiverLinkSettings((SbmpMessagingFactory)base.MessagingFactory, str, base.Path, new MessagingEntityType?(MessagingEntityType.VolatileTopicSubscription), ReceiveMode.ReceiveAndDelete, this.ControlMessageCreator, base.RetryPolicy, false);

            return(new CompletedAsyncResult <SbmpMessageReceiver>(createReceiverLinkSetting.MessageReceiver, callback, state));
        }
        public async Task Capture_Transaction_When_ReceiveDeferred_From_Topic_Subscription()
        {
            await using var scope = await TopicScope.CreateWithTopicAndSubscription(_adminClient);

            var sender   = new MessageSender(_environment.ServiceBusConnectionString, scope.TopicName);
            var receiver = new MessageReceiver(_environment.ServiceBusConnectionString,
                                               EntityNameHelper.FormatSubscriptionPath(scope.TopicName, scope.SubscriptionName));

            await sender.SendAsync(
                new Message(Encoding.UTF8.GetBytes("test message"))).ConfigureAwait(false);

            var message = await receiver.ReceiveAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);

            await receiver.DeferAsync(message.SystemProperties.LockToken).ConfigureAwait(false);

            await receiver.ReceiveDeferredMessageAsync(message.SystemProperties.SequenceNumber).ConfigureAwait(false);

            if (!_sender.WaitForTransactions(TimeSpan.FromMinutes(2), count: 2))
            {
                throw new Exception("No transaction received in timeout");
            }

            _sender.Transactions.Should().HaveCount(2);

            var transaction = _sender.FirstTransaction;

            transaction.Name.Should().Be($"{ServiceBus.SegmentName} RECEIVE from {scope.TopicName}/Subscriptions/{scope.SubscriptionName}");
            transaction.Type.Should().Be(ApiConstants.TypeMessaging);

            var secondTransaction = _sender.Transactions[1];

            secondTransaction.Name.Should().Be($"{ServiceBus.SegmentName} RECEIVEDEFERRED from {scope.TopicName}/Subscriptions/{scope.SubscriptionName}");
            secondTransaction.Type.Should().Be(ApiConstants.TypeMessaging);
        }
Ejemplo n.º 10
0
        //https://github.com/Azure/azure-service-bus/blob/master/samples/DotNet/Microsoft.Azure.ServiceBus/ReceiveSample/readme.md

        public AzureServiceBusTopicReceiver(string connectionString, string topicName, string subscriptionName, bool peekLock = true, MessageHandlerOptions handlerOptions = null)
            : base(
                CreateClient(connectionString, topicName, subscriptionName, peekLock),
                CreateMessageReceiver(connectionString, EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName), peekLock),
                handlerOptions)
        {
        }
        protected override IMessageReceiver CreateMessageReceiver(string connectionString, string topicName, string subscriberName, ITokenProvider tokenProvider)
        {
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);

            return(new MessageReceiver(builder.Endpoint,
                                       EntityNameHelper.FormatSubscriptionPath(topicName, subscriberName), tokenProvider));
        }
Ejemplo n.º 12
0
        private static async Task PurgeSubscriptionAsync(string subscriptionName)
        {
            try
            {
                Logger.Info($"Purging subscription '{subscriptionName}'");
                var messageReceiver = new MessageReceiver(
                    ServiceBusConnectionString,
                    EntityNameHelper.FormatSubscriptionPath(TopicName, subscriptionName),
                    ReceiveMode.ReceiveAndDelete);

                int batchSize        = 100;
                var operationTimeout = TimeSpan.FromSeconds(3);

                do
                {
                    var messages = await messageReceiver.ReceiveAsync(batchSize, operationTimeout).ConfigureAwait(false);

                    if (messages == null || messages.Count == 0) // Returns null if no message is found
                    {
                        break;
                    }
                }while (true);
                await messageReceiver.CloseAsync();
            }
            catch (Exception ex)
            {
                Logger.Error($"Error purging subscription {subscriptionName}", ex);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="IsSender">Since Sender and Receiver aren't interchangable even when the the underlying client is (queue),
 /// wee need to cache them seperately (the underlying framework will cache them anyhow; so as long as they aren't closed/disposed</param>
 /// <param name="subscriptionName"></param>
 /// <returns></returns>
 private static Tuple <string, string> _getEntityNameAndUniqueKey(ServiceBusConnectionStringBuilder builder, bool isSender = false, string subscriptionName = null)
 {
     if (!String.IsNullOrEmpty(subscriptionName))
     {
         builder.EntityPath = EntityNameHelper.FormatSubscriptionPath(builder.EntityPath, subscriptionName);
     }
     return(new Tuple <string, string>(builder.EntityPath, $"{builder.Endpoint}/{builder.EntityPath}{isSender}".ToLowerInvariant()));
 }
 public ServiceBusTriggerBinding(string parameterName, Type parameterType, ITriggerDataArgumentBinding <Message> argumentBinding, ServiceBusAccount account,
                                 ServiceBusOptions options, MessagingProvider messagingProvider, string topicName, string subscriptionName)
     : this(parameterName, parameterType, argumentBinding, account, options, messagingProvider)
 {
     _topicName        = topicName;
     _subscriptionName = subscriptionName;
     _entityPath       = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);
 }
Ejemplo n.º 15
0
 public ServiceBusTriggerBinding(string parameterName, Type parameterType, ITriggerDataArgumentBinding <Message> argumentBinding, ServiceBusAccount account,
                                 ServiceBusConfiguration config, string topicName, string subscriptionName)
     : this(parameterName, parameterType, argumentBinding, account, config)
 {
     _topicName        = topicName;
     _subscriptionName = subscriptionName;
     _entityPath       = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);
 }
Ejemplo n.º 16
0
        public Task <IListener> CreateAsync(CancellationToken cancellationToken)
        {
            string entityPath = EntityNameHelper.FormatSubscriptionPath(_topicName, _subscriptionName);

            ServiceBusTriggerExecutor triggerExecutor = new ServiceBusTriggerExecutor(_executor);
            var listener = new ServiceBusListener(entityPath, triggerExecutor, _config, _account);

            return(Task.FromResult <IListener>(listener));
        }
 public AzureMessageReceiver(IActorRuntime runtime, string connectionString, string topicName, ActorId actorId, string subscriptionName)
 {
     this.ActorRuntime         = runtime;
     this.LocalActorId         = actorId;
     this.LocalActorName       = (actorId == null) ? "Client" : actorId.Name;
     this.SubscriptionReceiver = new MessageReceiver(connectionString,
                                                     EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName),
                                                     ReceiveMode.ReceiveAndDelete);
 }
        protected override ClientContext CreateClientContext(MessagingFactoryContext connectionContext, Uri inputAddress)
        {
            var entityPath      = EntityNameHelper.FormatSubscriptionPath(_settings.TopicDescription.Path, _settings.SubscriptionDescription.SubscriptionName);
            var messageReceiver = connectionContext.MessagingFactory.CreateMessageReceiver(entityPath);

            messageReceiver.PrefetchCount = _settings.PrefetchCount;

            return(new SubscriptionClientContext(messageReceiver, inputAddress, _settings));
        }
Ejemplo n.º 19
0
        private async Task Cleanup()
        {
            await CleanUpEntity(FirstQueueName);
            await CleanUpEntity(SecondQueueName);
            await CleanUpEntity(BinderQueueName);
            await CleanUpEntity(FirstQueueName, _secondaryConnectionString);

            await CleanUpEntity(EntityNameHelper.FormatSubscriptionPath(TopicName, TopicSubscriptionName1));
            await CleanUpEntity(EntityNameHelper.FormatSubscriptionPath(TopicName, TopicSubscriptionName2));
        }
Ejemplo n.º 20
0
        public IMessageReceiver Create(string queueName, ReceiveMode receiveMode, bool isDeadLetterQueue = false)
        {
            string path = EntityNameHelper.FormatSubscriptionPath(_connectionDetails.TopicName, queueName);

            if (isDeadLetterQueue)
            {
                path = EntityNameHelper.FormatDeadLetterPath(path);
            }
            return(new MessageReceiver(_connectionDetails.ServiceBusConnectionString, path, receiveMode, RetryPolicy.NoRetry, 0));
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo parameter = context.Parameter;
            var           attribute = TypeUtility.GetResolvedAttribute <ServiceBusTriggerAttribute>(parameter);

            if (attribute == null)
            {
                return(Task.FromResult <ITriggerBinding>(null));
            }

            string queueName        = null;
            string topicName        = null;
            string subscriptionName = null;
            string entityPath       = null;

            if (attribute.QueueName != null)
            {
                queueName  = Resolve(attribute.QueueName);
                entityPath = queueName;
            }
            else
            {
                topicName        = Resolve(attribute.TopicName);
                subscriptionName = Resolve(attribute.SubscriptionName);
                entityPath       = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);
            }

            ITriggerDataArgumentBinding <Message> argumentBinding = InnerProvider.TryCreate(parameter);

            if (argumentBinding == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind ServiceBusTrigger to type '{0}'.", parameter.ParameterType));
            }

            attribute.Connection = Resolve(attribute.Connection);
            ServiceBusAccount account = new ServiceBusAccount(_options, _configuration, attribute);

            ITriggerBinding binding;

            if (queueName != null)
            {
                binding = new ServiceBusTriggerBinding(parameter.Name, parameter.ParameterType, argumentBinding, account, _options, _messagingProvider, queueName);
            }
            else
            {
                binding = new ServiceBusTriggerBinding(parameter.Name, parameter.ParameterType, argumentBinding, account, _options, _messagingProvider, topicName, subscriptionName);
            }

            return(Task.FromResult <ITriggerBinding>(binding));
        }
Ejemplo n.º 22
0
            public static void SBSub1Trigger(
                [ServiceBusTrigger(_topicName, _subscriptionName, IsSessionsEnabled = true)] Message message, int deliveryCount,
                IMessageSession messageSession,
                ILogger log,
                string lockToken)
            {
                Assert.Equal(EntityNameHelper.FormatSubscriptionPath(_topicName, _subscriptionName), messageSession.Path);
                Assert.Equal(1, deliveryCount);

                ServiceBusSessionsTestHelper.ProcessMessage(message, log, _waitHandle1, _waitHandle2);
            }
Ejemplo n.º 23
0
        public async Task ClearDeadLetters(string topicName, string subscriptionName)
        {
            var messageReceiver = new MessageReceiver(ServiceBusConnectionString, EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName), ReceiveMode.PeekLock);
            var message         = await messageReceiver.ReceiveAsync();

            while ((message = await messageReceiver.ReceiveAsync()) != null)
            {
                await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
            }
            await messageReceiver.CloseAsync();
        }
Ejemplo n.º 24
0
        /// <inheritdoc />
        protected override async Task RebuildReceiver()
        {
            using (await ReceiverLock.WriterLockAsync())
            {
                if (Receiver != null && !Receiver.IsClosedOrClosing)
                {
                    await Receiver.CloseAsync().ConfigureAwait(false);
                }

                Receiver = new MessageReceiver(ConnectionString, EntityNameHelper.FormatSubscriptionPath(AzureTopic.Name, SubscriptionName), ReceiveMode.PeekLock, new RetryExponential(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(500), 3), BatchSize);
            }
        }
Ejemplo n.º 25
0
 public SubscriptionWrapper(
     SubscriptionOptions options,
     ServiceBusOptions parentOptions,
     IServiceProvider provider)
     : base(
         options,
         parentOptions,
         provider,
         EntityNameHelper.FormatSubscriptionPath(options.TopicName, options.SubscriptionName))
 {
     _options = options;
 }
        public GatewayMessageReceiver(GatewaySettings settings, ITextMessageProcessors processors, ILogger logger)
        {
            _logger     = logger;
            _processors = processors;

            var subscription = EntityNameHelper.FormatSubscriptionPath(settings.ListenToTopic, settings.ServiceName);

            _receiver = new MessageReceiver(settings.ServieBusConnectionString, subscription);
            _receiver.RegisterMessageHandler(NewMessagReceivedHandler, ExceptionReceivedHandler);

            _logger.Information($"Conneted SmsReciever to {settings.ServiceName}");
        }
        public AzureServiceBusMessageSubscriber(
            string connectionString,
            string topicName,
            string subscriptionName)
        {
            var entityPath = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);

            _messageReceiver = new MessageReceiver(
                connectionString,
                entityPath,
                ReceiveMode.PeekLock);
        }
Ejemplo n.º 28
0
        private async Task ReceiveMessages(string subscription)
        {
            var entityPath = EntityNameHelper.FormatSubscriptionPath(TopicName, subscription);
            var receiver   = new MessageReceiver(ServiceBusConnectionString, entityPath, ReceiveMode.PeekLock, RetryPolicy.Default, 100);

            // In reality you would not break out of the loop like in this example but would keep looping. The receiver keeps the connection open
            // to the broker for the specified amount of seconds and the broker returns messages as soon as they arrive. The client then initiates
            // a new connection. So in reality you would not want to break out of the loop.
            // Also note that the code shows how to batch receive, which you would do for performance reasons. For convenience you can also always
            // use the regular receive pump which we show in our Quick Start and in other github samples.
            while (true)
            {
                try
                {
                    IList <Message> messages = await receiver.ReceiveAsync(10, TimeSpan.FromSeconds(2));

                    // Note the extension class which is serializing an deserializing messages and testing messages is null or 0.
                    // If you think you did not receive all messages, just press M and receive again via the menu.
                    if (messages.Any())
                    {
                        foreach (var message in messages)
                        {
                            lock (Console.Out)
                            {
                                Item item = message.As <Item>();
                                IDictionary <string, object> myUserProperties = message.UserProperties;
                                Console.WriteLine($"StoreId={myUserProperties["StoreId"]}");

                                if (message.Label != null)
                                {
                                    Console.WriteLine($"Label={message.Label}");
                                }

                                Console.WriteLine(
                                    $"Item data: Price={item.getPrice()}, Color={item.getColor()}, Category={item.getItemCategory()}");
                            }

                            await receiver.CompleteAsync(message.SystemProperties.LockToken);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            await receiver.CloseAsync();
        }
Ejemplo n.º 29
0
        private async Task <AzureMessage> PeekDlqMessageBySequenceNumber(string connectionString, string topicPath,
                                                                         string subscriptionPath, long sequenceNumber)
        {
            var path           = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath);
            var deadletterPath = EntityNameHelper.FormatDeadLetterPath(path);

            var receiver     = new MessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock);
            var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber);

            await receiver.CloseAsync();

            return(azureMessage);
        }
        private void StartReceiving()
        {
            var entityPath = EntityNameHelper.FormatSubscriptionPath(Name, MyUsername);
            var receiver   = new MessageReceiver(WorkshopConfig.SBConnectionString, entityPath, ReceiveMode.ReceiveAndDelete);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = true
            };

            receiver.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }