How to purge messages for Service Bus Topic Subscription

Stefan Zvonar picture Stefan Zvonar · Oct 25, 2017 · Viewed 9.1k times · Source

Just wondering the best way (even if via Portal, Powershell, or C#) to purge the messages off of a Service Bus Topic's Subscription.

Imagine we have a topic with 4 subscriptions, and we only want to purge the messages from one of the subscriptions.

I have a feeling the only way may be to read the messages in a while loop, but hoping for something better.

UPDATE:

Apart from using code, you can use the Server Explorer as suggested in the answer - right click subscription and purge messages:

enter image description here

Answer

Gaurav Mantri picture Gaurav Mantri · Oct 25, 2017

You can most certainly do it via code. If you're using Service Bus SDK, you could do something like the following:

    static void PurgeMessagesFromSubscription()
    {
        var connectionString = "Endpoint=sb://account-name.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=access key";
        var topic = "topic-name";
        var subscription = "subscription-name";
        int batchSize = 100;
        var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription, ReceiveMode.ReceiveAndDelete);
        do
        {
            var messages = subscriptionClient.ReceiveBatch(batchSize);
            if (messages.Count() == 0)
            {
                break;
            }
        }
        while (true);
    }

What this code will do is fetch messages from the subscription (100 at a time) in Receive & Delete mode so that as soon as messages are fetched, they are deleted from the subscription automatically.

I believe Service Bus Explorer tool also has the capability to purge messages. You can use that as well instead of writing the code.