﻿# Azure Service Bus Pub/Sub Native Integration

<!-- Version variant: asbs_5; default: [/samples/azure-service-bus-netstandard/native-integration-pub-sub/index.md](/samples/azure-service-bus-netstandard/native-integration-pub-sub/index.md) -->


This sample shows how to subscribe to events published by an NServiceBus endpoint using the Azure Service Bus API.

## Prerequisites

An environment variable named `AzureServiceBus_ConnectionString` with the connection string for the Azure Service Bus namespace.

## Code walk-through

The sample contains three executable projects:

* `Publisher`: an NServiceBus endpoint that publishes `EventOne` and `EventTwo` events.
* `NativeSubscriberA`: an executable subscribing to the `EventOne` event published by the `Publisher`.
* `NativeSubscriberB`: an executable subscribing to both events published by the `Publisher`.

## Running the sample

1. Start first the `NativeSubscriberA` and `NativeSubscriberB` projects. This will create all the necessary publish/subscribe infrastructure in Azure Service Bus, including the event topics.
2. In the `Publisher` window, press any key to publish an event.
    * The endpoint in the `NativeSubscriberA` window will receive `EventOne`.
    * The endpoint in the `NativeSubscriberB` window will receive both `EventOne` and `EventTwo`.

## Setting up namespace entities

Each subscriber requires topic subscription(s) to receive the events published by the `Publisher`. The subscriptions are created on the `EventOne` or `EventTwo` topic, which follow the the default topic naming convention used by NServiceBus endpoints.

<!-- snippet: SubscriptionCreation -->

```cs
await client.CreateSubscriptionAsync(new CreateSubscriptionOptions(topicPath, subscriptionName)
{
    LockDuration = TimeSpan.FromMinutes(5),
    EnableDeadLetteringOnFilterEvaluationExceptions = false,
    MaxDeliveryCount = int.MaxValue,
    EnableBatchedOperations = true,
    ForwardTo = forwardTo,
}, new CreateRuleOptions(ruleName, sqlFilter));
```

<!-- endsnippet -->

### Subscription filters

Subscriptions created by `NativeSubscriberA` and `NativeSubscriberB`. `NativeSubscriberA` subscribes to the `EventOne` events by adding a subscription with the default [`TrueFilter`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.truefilter?view=azure-dotnet) and forwarding to its input queue:

<!-- snippet: EventOneSubscription -->

```cs
await TopologyManager.CreateSubscription(
    ConnectionString,
    queueName,
    ruleName:"$default",
    sqlFilter: new TrueRuleFilter(),
    topicPath: "EventOne",
    forwardTo: queueName
    );
```

<!-- endsnippet -->

The other subscriber creates two subscriptions following the same subscription pattern under both the `EventOne` and `EventTwo` topics.

