private static async Task Setup(this ServiceBusAdministrationClient admin, string topic) { if (!(await admin.TopicExistsAsync(topic)).Value) { await admin.CreateTopicAsync(new CreateTopicOptions(topic)); } }
private async Task CreateTopicIfNotExistsAsync(string name, CancellationToken cancellationToken) { // if entity creation is not enabled, just return if (!TransportOptions.EnableEntityCreation) { Logger.LogTrace("Entity creation is diabled. Topic creation skipped"); return; } // If the topic does not exist, create it Logger.LogDebug("Checking if topic '{TopicName}' exists", name); if (!await managementClient.TopicExistsAsync(name: name, cancellationToken: cancellationToken)) { Logger.LogTrace("Topic '{TopicName}' does not exist, preparing creation.", name); var options = new CreateTopicOptions(name: name) { // set the defaults for a topic here Status = EntityStatus.Active, EnablePartitioning = false, RequiresDuplicateDetection = BusOptions.EnableDeduplication, DuplicateDetectionHistoryTimeWindow = BusOptions.DuplicateDetectionDuration, }; // Allow for the defaults to be overriden TransportOptions.SetupTopicOptions?.Invoke(options); Logger.LogInformation("Creating topic '{TopicName}'", name); _ = await managementClient.CreateTopicAsync(options : options, cancellationToken : cancellationToken); } }
public static async Task SetupTopicAsync(this ServiceBusAdministrationClient client, string topicName) { if (!await client.TopicExistsAsync(topicName)) { await client.CreateTopicAsync(topicName); } }
private static async Task <ServiceBusAdministrationClient> Cleanup(string connectionString, string inputQueue, string topicName, string rushSubscription, string currencySubscription) { var client = new ServiceBusAdministrationClient(connectionString); if (await client.SubscriptionExistsAsync(topicName, rushSubscription)) { await client.DeleteSubscriptionAsync(topicName, rushSubscription); } if (await client.SubscriptionExistsAsync(topicName, currencySubscription)) { await client.DeleteSubscriptionAsync(topicName, currencySubscription); } if (await client.TopicExistsAsync(topicName)) { await client.DeleteTopicAsync(topicName); } var topicDescription = new CreateTopicOptions(topicName); await client.CreateTopicAsync(topicDescription); if (await client.QueueExistsAsync(inputQueue)) { await client.DeleteQueueAsync(inputQueue); } var queueDescription = new CreateQueueOptions(inputQueue); await client.CreateQueueAsync(queueDescription); return(client); }
private async Task EnsureTopicExistsAsync(string topicName, CancellationToken cancellationToken) { if (!await _administrationClient.TopicExistsAsync(topicName, cancellationToken)) { await _administrationClient.CreateTopicAsync(topicName, cancellationToken); } }
private static async Task SendTextMessageToTopic() { const string topicName = "sbt-text-message"; var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential); if (!await managementClient.TopicExistsAsync(topicName)) { await managementClient.CreateTopicAsync(topicName); } await using var client = new ServiceBusClient(Config.Namespace, Config.Credential); var sender = client.CreateSender(topicName); var message = new ServiceBusMessage(Encoding.UTF8.GetBytes("This is a simple test message")); Console.WriteLine("Press any key to send a message. Press Enter to exit."); while (Console.ReadKey(true).Key != ConsoleKey.Enter) { await sender.SendMessageAsync(message); Console.WriteLine($"Message Sent for {nameof(SendTextMessageToTopic)}"); } Console.ReadLine(); await managementClient.DeleteQueueAsync(topicName); }
/// <summary> /// Check if a Topic exists /// </summary> /// <param name="topic">The name of the Topic.</param> /// <returns>True if the Topic exists.</returns> public bool TopicExists(string topic) { s_logger.LogDebug("Checking if topic {Topic} exists...", topic); bool result; try { result = _administrationClient.TopicExistsAsync(topic).GetAwaiter().GetResult(); } catch (Exception e) { s_logger.LogError(e, "Failed to check if topic {Topic} exists.", topic); throw; } if (result) { s_logger.LogDebug("Topic {Topic} exists.", topic); } else { s_logger.LogWarning("Topic {Topic} does not exist.", topic); } return(result); }
public async Task CreateTopicAsync() { var connString = _configuration.GetValue <string>("Azure:ServiceBus:SourceSynchronizer:ConnString"); var sbAdminClient = new ServiceBusAdministrationClient(connString); if (!await sbAdminClient.TopicExistsAsync(_topicName)) { await sbAdminClient.CreateTopicAsync(_topicName); } }
async Task EnsureInitializationAsync() { if (!await adminClient.TopicExistsAsync(this.TopicName)) { await adminClient.CreateTopicAsync(new CreateTopicOptions(this.TopicName)); /*Explore more options*/ } if (!await adminClient.SubscriptionExistsAsync(this.TopicName, this.SubscriptionName)) { await adminClient.CreateSubscriptionAsync(this.TopicName, this.SubscriptionName); } }
private ServiceBusSender GetServiceBusTopicSender(string topicName) { var busAdmin = new ServiceBusAdministrationClient(Connections.ServiceBusConnectionString); if (!busAdmin.TopicExistsAsync(topicName).Result.Value) { busAdmin.CreateTopicAsync(topicName).Wait(); } ServiceBusClient client = new ServiceBusClient(Connections.ServiceBusConnectionString); return(client.CreateSender(topicName)); }
private void CreateTopicAndSubscriptions(string topicName, string[] subscriptions) { var busAdmin = new ServiceBusAdministrationClient(Connections.ServiceBusConnectionString); if (!busAdmin.TopicExistsAsync(topicName).Result.Value) { busAdmin.CreateTopicAsync(topicName).Wait(); } foreach (var subscription in subscriptions) { if (!busAdmin.SubscriptionExistsAsync(topicName, subscription).Result.Value) { busAdmin.CreateSubscriptionAsync(topicName, subscription).Wait(); } } }
public async Task SetupAsync(IHost host) { using var scope = host.Services.CreateScope(); var referenceFactory = scope.ServiceProvider.GetRequiredService <IQueueReferenceFactory>(); var policy = referenceFactory.Create <TM>(); var azureConfig = scope.ServiceProvider.GetRequiredService <AzureServiceBusConfiguration>(); var adminClient = new ServiceBusAdministrationClient(azureConfig.ConnectionString); if (!(await adminClient.TopicExistsAsync(policy.TopicName))) { await adminClient.CreateTopicAsync(policy.TopicName); } if (!(await adminClient.SubscriptionExistsAsync(policy.TopicName, policy.SubscriptionName))) { await adminClient.CreateSubscriptionAsync(policy.TopicName, policy.SubscriptionName); } }
public ServiceBusQueue(string connectionString, string topicName, string subscription, ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PeekLock, bool createQueueIfItDoesNotExist = true) : base(connectionString) { this.connectionString = connectionString; this.queueName = topicName; this.topicName = topicName; this.subscription = subscription; this.receiveMode = receiveMode; this.SubQueue = SubQueue.None; busAdmin = new ServiceBusAdministrationClient(this.connectionString); if (createQueueIfItDoesNotExist && !busAdmin.TopicExistsAsync(topicName).Result.Value) { busAdmin.CreateTopicAsync(topicName).Wait(); } if (createQueueIfItDoesNotExist && !string.IsNullOrEmpty(subscription) && !busAdmin.SubscriptionExistsAsync(topicName, subscription).Result.Value) { busAdmin.CreateSubscriptionAsync(topicName, subscription).Wait(); } }
public async Task EnsureTopic(string topicName, CancellationToken cancellationToken = default) { try { if (!await _administrationClient.TopicExistsAsync(topicName, cancellationToken)) { var options = new CreateTopicOptions(topicName) { Status = EntityStatus.Active, MaxSizeInMegabytes = 1024, DefaultMessageTimeToLive = TimeSpan.FromDays(10000) }; await _administrationClient.CreateTopicAsync(options, cancellationToken); } } catch (Exception ex) { _logger.LogError(ex, "Service Bus ensure topic operation failure"); throw new ServiceBusPublisherOperationException("Service Bus ensure topic operation failure", ex); } }
public async Task SetupAsync(IHost host) { using var scope = host.Services.CreateScope(); var referenceFactory = scope.ServiceProvider.GetRequiredService <IQueueReferenceFactory>(); var policy = referenceFactory.Create <TM>(); var azureConfig = scope.ServiceProvider.GetRequiredService <AzureServiceBusConfiguration>(); var adminClient = new ServiceBusAdministrationClient(azureConfig.ConnectionString); try { if (!await adminClient.TopicExistsAsync(policy.TopicName)) { await adminClient.CreateTopicAsync(new CreateTopicOptions(policy.TopicName) { RequiresDuplicateDetection = true }); } } catch (Exception ex) { Console.WriteLine(ex.Message); } try { if (!await adminClient.SubscriptionExistsAsync(policy.TopicName, policy.SubscriptionName)) { await adminClient.CreateSubscriptionAsync(policy.TopicName, policy.SubscriptionName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task StartAsync(CancellationToken cancellationToken) { if (Subscription == null) { if (!await _administrationClient.QueueExistsAsync(QueueOrTopic, cancellationToken)) { await _administrationClient.CreateQueueAsync(QueueOrTopic, cancellationToken); } } else { if (!await _administrationClient.TopicExistsAsync(QueueOrTopic, cancellationToken)) { await _administrationClient.CreateTopicAsync(QueueOrTopic, cancellationToken); } if (!await _administrationClient.SubscriptionExistsAsync(QueueOrTopic, Subscription, cancellationToken)) { await _administrationClient.CreateSubscriptionAsync(QueueOrTopic, Subscription, cancellationToken); } } await _processor.StartProcessingAsync(cancellationToken); }
public async Task StartAsync(CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _client = await _clientFactory.GetReceiverClient <TTopic, IEventSubscription <TTopic> >(_subscription, new ServiceBusProcessorOptions { AutoCompleteMessages = false, MaxAutoLockRenewalDuration = Settings.MessageLockTimeout, MaxConcurrentCalls = Settings.MaxConcurrentCalls, PrefetchCount = Settings.PrefetchCount, ReceiveMode = ServiceBusReceiveMode.PeekLock }).ConfigureAwait(false); var topicName = AutoMessageMapper.GetQueueName <TTopic>(); if (!await _managementClient.TopicExistsAsync(topicName, cancellationToken).ConfigureAwait(false)) { try { var serviceBusCreationOptions = GetServiceBusCreationOptions(); await _managementClient.CreateTopicAsync(new CreateTopicOptions(topicName) { EnablePartitioning = serviceBusCreationOptions.EnablePartitioning, EnableBatchedOperations = serviceBusCreationOptions.EnableBatchedOperations, SupportOrdering = serviceBusCreationOptions.SupportOrdering }, cancellationToken).ConfigureAwait(false); } catch (ServiceBusException e) { _log.Error(e, "Failed to create topic {TopicName}", topicName); throw; } } if (!await _managementClient.SubscriptionExistsAsync(topicName, _subscription.Name, cancellationToken).ConfigureAwait(false)) { try { var serviceBusCreationOptions = GetServiceBusCreationOptions(); await _managementClient.CreateSubscriptionAsync(new CreateSubscriptionOptions(topicName, _subscription.Name) { EnableBatchedOperations = serviceBusCreationOptions.EnableBatchedOperations }, cancellationToken).ConfigureAwait(false); } catch (ServiceBusException e) { _log.Error(e, "Failed to create subscription {TopicName} {SubscriptionName}", topicName, _subscription.Name); throw; } } _deadLetterLimit = Settings.DeadLetterDeliveryLimit; _client.ProcessMessageAsync += ClientOnProcessMessageAsync; _client.ProcessErrorAsync += ClientOnProcessErrorAsync; await _client.StartProcessingAsync(cancellationToken); #pragma warning disable 4014 // ReSharper disable once MethodSupportsCancellation Task.Run(async() => { _cancellationToken.WaitHandle.WaitOne(); //Cancellation requested try { _log.Information($"Closing ServiceBus channel receiver for {typeof(TTopic).Name}"); await _client.CloseAsync(CancellationToken.None); } catch (Exception) { //Swallow } }); #pragma warning restore 4014 }
public async Task <bool> IsTopic(string name) { var administrationClient = new ServiceBusAdministrationClient(ConnectionString); return(await administrationClient.TopicExistsAsync(name).ConfigureAwait(false)); }