Table of Contents

Class SubscriptionClient

Namespace
Microsoft.Azure.ServiceBus
Assembly
Microsoft.Azure.ServiceBus.dll

SubscriptionClient can be used for all basic interactions with a Service Bus Subscription.

public class SubscriptionClient : ClientEntity, ISubscriptionClient, IReceiverClient, IClientEntity
Inheritance
SubscriptionClient
Implements
Inherited Members

Examples

Create a new SubscriptionClient

ISubscriptionClient subscriptionClient = new SubscriptionClient(
    namespaceConnectionString,
    topicName,
    subscriptionName,
    ReceiveMode.PeekLock,
    RetryExponential);

Register a message handler which will be invoked every time a message is received.

subscriptionClient.RegisterMessageHandler(
       async (message, token) =>
       {
           // Process the message
           Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

           // Complete the message so that it is not received again.
           // This can be done only if the subscriptionClient is opened in ReceiveMode.PeekLock mode.
           await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
       },
       async (exceptionEvent) =>
       {
           // Process the exception
           Console.WriteLine("Exception = " + exceptionEvent.Exception);
           return Task.CompletedTask;
       });

Remarks

It uses AMQP protocol for communicating with service bus. Use MessageReceiver for advanced set of functionality.

Constructors

SubscriptionClient(ServiceBusConnection, string, string, ReceiveMode, RetryPolicy)

Creates a new instance of the Subscription client on a given ServiceBusConnection

public SubscriptionClient(ServiceBusConnection serviceBusConnection, string topicPath, string subscriptionName, ReceiveMode receiveMode, RetryPolicy retryPolicy)

Parameters

serviceBusConnection ServiceBusConnection

Connection object to the service bus namespace.

topicPath string

Topic path.

subscriptionName string

Subscription name.

receiveMode ReceiveMode

Mode of receive of messages. Defaults to ReceiveMode.PeekLock.

retryPolicy RetryPolicy

Retry policy for subscription operations. Defaults to Default

SubscriptionClient(ServiceBusConnectionStringBuilder, string, ReceiveMode, RetryPolicy)

Instantiates a new SubscriptionClient to perform operations on a subscription.

public SubscriptionClient(ServiceBusConnectionStringBuilder connectionStringBuilder, string subscriptionName, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null)

Parameters

connectionStringBuilder ServiceBusConnectionStringBuilder

ServiceBusConnectionStringBuilder having namespace and topic information.

subscriptionName string
receiveMode ReceiveMode

Mode of receive of messages. Defaults to ReceiveMode.PeekLock.

retryPolicy RetryPolicy

Retry policy for subscription operations. Defaults to Default

Remarks

Creates a new connection to the subscription, which is opened during the first receive operation.

SubscriptionClient(string, string, string, ITokenProvider, TransportType, ReceiveMode, RetryPolicy)

Creates a new instance of the Subscription client using the specified endpoint, entity path, and token provider.

public SubscriptionClient(string endpoint, string topicPath, string subscriptionName, ITokenProvider tokenProvider, TransportType transportType = TransportType.Amqp, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null)

Parameters

endpoint string

Fully qualified domain name for Service Bus. Most likely, {yournamespace}.servicebus.windows.net

topicPath string

Topic path.

subscriptionName string

Subscription name.

tokenProvider ITokenProvider

Token provider which will generate security tokens for authorization.

transportType TransportType

Transport type.

receiveMode ReceiveMode

Mode of receive of messages. Defaults to ReceiveMode.PeekLock.

retryPolicy RetryPolicy

Retry policy for subscription operations. Defaults to Default

Remarks

Creates a new connection to the subscription, which is opened during the first receive operation.

SubscriptionClient(string, string, string, ReceiveMode, RetryPolicy)

Instantiates a new SubscriptionClient to perform operations on a subscription.

public SubscriptionClient(string connectionString, string topicPath, string subscriptionName, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null)

Parameters

connectionString string

Namespace connection string. Must not contain topic or subscription information.

topicPath string
subscriptionName string
receiveMode ReceiveMode

Mode of receive of messages. Defaults to ReceiveMode.PeekLock.

retryPolicy RetryPolicy

Retry policy for subscription operations. Defaults to Default

Remarks

Creates a new connection to the subscription, which is opened during the first receive operation.

Properties

OperationTimeout

Duration after which individual operations will timeout.

public override TimeSpan OperationTimeout { get; set; }

Property Value

TimeSpan

Path

Gets the formatted path of the subscription client.

public override string Path { get; }

Property Value

string
See Also

PrefetchCount

Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using Receive. Setting a non-zero value prefetches PrefetchCount number of messages. Setting the value to zero turns prefetch off. Defaults to 0.

public int PrefetchCount { get; set; }

Property Value

int

Remarks

When Prefetch is enabled, the client will quietly acquire more messages, up to the PrefetchCount limit, than what the application immediately asks for. The message pump will therefore acquire a message for immediate consumption that will be returned as soon as available, and the client will proceed to acquire further messages to fill the prefetch buffer in the background.

While messages are available in the prefetch buffer, any subsequent ReceiveAsync calls will be immediately satisfied from the buffer, and the buffer is replenished in the background as space becomes available.If there are no messages available for delivery, the receive operation will drain the buffer and then wait or block as expected.

Updates to this value take effect on the next receive call to the service.

ReceiveMode

Gets the ReceiveMode for the SubscriptionClient.

public ReceiveMode ReceiveMode { get; }

Property Value

ReceiveMode

RegisteredPlugins

Gets a list of currently registered plugins for this SubscriptionClient.

public override IList<ServiceBusPlugin> RegisteredPlugins { get; }

Property Value

IList<ServiceBusPlugin>

ServiceBusConnection

Connection object to the service bus namespace.

public override ServiceBusConnection ServiceBusConnection { get; }

Property Value

ServiceBusConnection

SubscriptionName

Gets the name of the subscription.

public string SubscriptionName { get; }

Property Value

string

TopicPath

Gets the path of the corresponding topic.

public string TopicPath { get; }

Property Value

string

Methods

AbandonAsync(string, IDictionary<string, object>)

Abandons a Message using a lock token. This will make the message available again for processing.

public Task AbandonAsync(string lockToken, IDictionary<string, object> propertiesToModify = null)

Parameters

lockToken string

The lock token of the corresponding message to abandon.

propertiesToModify IDictionary<string, object>

The properties of the message to modify while abandoning the message.

Returns

Task

Remarks

A lock token can be found in LockToken, only when ReceiveMode is set to PeekLock. Abandoning a message will increase the delivery count on the message. This operation can only be performed on messages that were received by this client.

AddRuleAsync(RuleDescription)

Adds a rule to the current subscription to filter the messages reaching from topic to the subscription.

public Task AddRuleAsync(RuleDescription description)

Parameters

description RuleDescription

The rule description that provides the rule to add.

Returns

Task

A task instance that represents the asynchronous add rule operation.

Remarks

You can add rules to the subscription that decides which messages from the topic should reach the subscription. A default TrueFilter rule named DefaultRuleName is always added while creation of the Subscription. You can add multiple rules with distinct names to the same subscription. Multiple filters combine with each other using logical OR condition. i.e., If any filter succeeds, the message is passed on to the subscription.

AddRuleAsync(string, Filter)

Adds a rule to the current subscription to filter the messages reaching from topic to the subscription.

public Task AddRuleAsync(string ruleName, Filter filter)

Parameters

ruleName string
filter Filter

The filter expression against which messages will be matched.

Returns

Task

A task instance that represents the asynchronous add rule operation.

Remarks

You can add rules to the subscription that decides which messages from the topic should reach the subscription. A default TrueFilter rule named DefaultRuleName is always added while creation of the Subscription. You can add multiple rules with distinct names to the same subscription. Multiple filters combine with each other using logical OR condition. i.e., If any filter succeeds, the message is passed on to the subscription. Max allowed length of rule name is 50 chars.

CompleteAsync(string)

Completes a Message using its lock token. This will delete the message from the subscription.

public Task CompleteAsync(string lockToken)

Parameters

lockToken string

The lock token of the corresponding message to complete.

Returns

Task

Remarks

A lock token can be found in LockToken, only when ReceiveMode is set to PeekLock. This operation can only be performed on messages that were received by this client.

DeadLetterAsync(string)

Moves a message to the deadletter sub-queue.

public Task DeadLetterAsync(string lockToken)

Parameters

lockToken string

The lock token of the corresponding message to deadletter.

Returns

Task

Remarks

A lock token can be found in LockToken, only when ReceiveMode is set to PeekLock. In order to receive a message from the deadletter sub-queue, you will need a new IMessageReceiver or ISubscriptionClient, with the corresponding path. You can use FormatDeadLetterPath(string) to help with this. This operation can only be performed on messages that were received by this client.

DeadLetterAsync(string, IDictionary<string, object>)

Moves a message to the deadletter sub-queue.

public Task DeadLetterAsync(string lockToken, IDictionary<string, object> propertiesToModify)

Parameters

lockToken string

The lock token of the corresponding message to deadletter.

propertiesToModify IDictionary<string, object>

The properties of the message to modify while moving to sub-queue.

Returns

Task

Remarks

A lock token can be found in LockToken, only when ReceiveMode is set to PeekLock. In order to receive a message from the deadletter queue, you will need a new IMessageReceiver, with the corresponding path. You can use FormatDeadLetterPath(string) to help with this. This operation can only be performed on messages that were received by this receiver.

DeadLetterAsync(string, string, string)

Moves a message to the deadletter sub-queue.

public Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null)

Parameters

lockToken string

The lock token of the corresponding message to deadletter.

deadLetterReason string

The reason for deadlettering the message.

deadLetterErrorDescription string

The error description for deadlettering the message.

Returns

Task

Remarks

A lock token can be found in LockToken, only when ReceiveMode is set to PeekLock. In order to receive a message from the deadletter queue, you will need a new IMessageReceiver, with the corresponding path. You can use FormatDeadLetterPath(string) to help with this. This operation can only be performed on messages that were received by this receiver.

GetRulesAsync()

Get all rules associated with the subscription.

public Task<IEnumerable<RuleDescription>> GetRulesAsync()

Returns

Task<IEnumerable<RuleDescription>>

OnClosingAsync()

protected override Task OnClosingAsync()

Returns

Task

RegisterMessageHandler(Func<Message, CancellationToken, Task>, MessageHandlerOptions)

Receive messages continuously from the entity. Registers a message handler and begins a new thread to receive messages. This handler(Func<T1, T2, TResult>) is awaited on every time a new message is received by the receiver.

public void RegisterMessageHandler(Func<Message, CancellationToken, Task> handler, MessageHandlerOptions messageHandlerOptions)

Parameters

handler Func<Message, CancellationToken, Task>

A Func<T1, T2, TResult> that processes messages.

messageHandlerOptions MessageHandlerOptions

The MessageHandlerOptions options used to configure the settings of the pump.

Remarks

Enable prefetch to speed up the receive rate.

RegisterMessageHandler(Func<Message, CancellationToken, Task>, Func<ExceptionReceivedEventArgs, Task>)

Receive messages continuously from the entity. Registers a message handler and begins a new thread to receive messages. This handler(Func<T1, T2, TResult>) is awaited on every time a new message is received by the receiver.

public void RegisterMessageHandler(Func<Message, CancellationToken, Task> handler, Func<ExceptionReceivedEventArgs, Task> exceptionReceivedHandler)

Parameters

handler Func<Message, CancellationToken, Task>

A Func<T1, T2, TResult> that processes messages.

exceptionReceivedHandler Func<ExceptionReceivedEventArgs, Task>

A Func<T, TResult> that is invoked during exceptions. ExceptionReceivedEventArgs contains contextual information regarding the exception.

Remarks

Enable prefetch to speed up the receive rate. Use RegisterMessageHandler(Func<Message, CancellationToken, Task>, MessageHandlerOptions) to configure the settings of the pump.

RegisterPlugin(ServiceBusPlugin)

Registers a ServiceBusPlugin to be used for receiving messages from Service Bus.

public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin)

Parameters

serviceBusPlugin ServiceBusPlugin

The ServiceBusPlugin to register

RegisterSessionHandler(Func<IMessageSession, Message, CancellationToken, Task>, SessionHandlerOptions)

Receive session messages continuously from the queue. Registers a message handler and begins a new thread to receive session-messages. This handler(Func<T1, T2, T3, TResult>) is awaited on every time a new message is received by the subscription client.

public void RegisterSessionHandler(Func<IMessageSession, Message, CancellationToken, Task> handler, SessionHandlerOptions sessionHandlerOptions)

Parameters

handler Func<IMessageSession, Message, CancellationToken, Task>

A Func<T1, T2, T3, TResult> that processes messages. IMessageSession contains the session information, and must be used to perform Complete/Abandon/Deadletter or other such operations on the Message

sessionHandlerOptions SessionHandlerOptions

Options used to configure the settings of the session pump.

Remarks

Enable prefetch to speed up the receive rate.

RegisterSessionHandler(Func<IMessageSession, Message, CancellationToken, Task>, Func<ExceptionReceivedEventArgs, Task>)

Receive session messages continuously from the queue. Registers a message handler and begins a new thread to receive session-messages. This handler(Func<T1, T2, T3, TResult>) is awaited on every time a new message is received by the subscription client.

public void RegisterSessionHandler(Func<IMessageSession, Message, CancellationToken, Task> handler, Func<ExceptionReceivedEventArgs, Task> exceptionReceivedHandler)

Parameters

handler Func<IMessageSession, Message, CancellationToken, Task>

A Func<T1, T2, T3, TResult> that processes messages. IMessageSession contains the session information, and must be used to perform Complete/Abandon/Deadletter or other such operations on the Message

exceptionReceivedHandler Func<ExceptionReceivedEventArgs, Task>

A Func<T, TResult> that is invoked during exceptions. ExceptionReceivedEventArgs contains contextual information regarding the exception.

Remarks

Enable prefetch to speed up the receive rate. Use RegisterSessionHandler(Func<IMessageSession, Message, CancellationToken, Task>, SessionHandlerOptions) to configure the settings of the pump.

RemoveRuleAsync(string)

Removes the rule on the subscription identified by ruleName.

public Task RemoveRuleAsync(string ruleName)

Parameters

ruleName string

Returns

Task

A task instance that represents the asynchronous remove rule operation.

UnregisterPlugin(string)

Unregisters a ServiceBusPlugin.

public override void UnregisterPlugin(string serviceBusPluginName)

Parameters

serviceBusPluginName string

The name Name to be unregistered