17

Is there a way to get the current message count for an Azure topic subscription?

I see that the SubscriptionDescription class has a MessageCount property, but this class appears to only be used to create a subscription. I don't see a way to retrieve a SubscriptionDescription object for an existing subscription.

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
egelvin
  • 523
  • 4
  • 10

3 Answers3

24

I found what I was looking for:

var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
var subscriptionDesc = namespaceManager.GetSubscription(topicPath, subscriptionName);
long messageCount = subscriptionDesc.MessageCount;
egelvin
  • 523
  • 4
  • 10
  • I think that helps if you're looking for a Subscription Count, but not a Topic count. (Though depending on your configuration that could be the same.) I'm looking for an API that gives an Active Message Count for an entire Topic, including all Subscriptions. – Lucas Jul 07 '15 at 09:09
  • @Lucas, did you get that API count, you were looking for? Please share if found. – Ashokan Sivapragasam Aug 04 '20 at 12:07
  • I believe this is for the old windowsazure library. the new library uses the classes mentioned in https://stackoverflow.com/a/53541781/34315 – gabe Nov 12 '20 at 01:21
9

The accepted answer is for when using the .NET Framework library with the namespace Microsoft.ServiceBus.Messaging (nuget package).

For the .NET Standard library with the namespace Microsoft.Azure.ServiceBus (nuget package) the following code does the trick:

var managementClient = new ManagementClient(connectionString);
var runTimeInfo = await managementClient.GetSubscriptionRuntimeInfoAsync(topicPath, subscriptionName); 
var messageCount = runTimeInfo.MessageCountDetails.ActiveMessageCount;

See Microsoft.ServiceBus.Messaging vs Microsoft.Azure.ServiceBus for more details about the differences between the two libraries.

With the retirement of .NET Standard there is a new namespace for .NET 5+ apps, Azure.Messaging.ServiceBus (nuget package). The code required to do the same with this package is:

var client = new Azure.Messaging.ServiceBus.Administration.ServiceBusAdministrationClient("connetionString");
var runtimeProps = (await client.GetQueueRuntimePropertiesAsync("queueName")).Value;
var messageCount = runtimeProps.ActiveMessageCount;
Simon Ness
  • 2,272
  • 22
  • 28
4

Microsoft.Azure.ServiceBus library is deprecated now in favor of Azure.Messaging.ServiceBus. So now this can be achieved with Azure.Messaging.ServiceBus.Administration.ServiceBusAdministrationClient:

var client = new Azure.Messaging.ServiceBus.Administration.ServiceBusAdministrationClient("connetionString");
var runtimeProps = (await client.GetQueueRuntimePropertiesAsync("queueName")).Value;
var messageCount = runtimeProps.ActiveMessageCount;
AndrewG
  • 186
  • 4