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); } }
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); }
public async Task CreateTopicAndSubscription() { #if !SNIPPET string topicName = Guid.NewGuid().ToString("D").Substring(0, 8); string subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); string connectionString = TestEnvironment.ServiceBusConnectionString; var client = new ServiceBusAdministrationClient(connectionString); #endif try { #region Snippet:CreateTopicAndSubscription #if SNIPPET string connectionString = "<connection_string>"; string topicName = "<topic_name>"; var client = new ServiceBusManagementClient(connectionString); #endif var topicOptions = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromDays(7), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 2048, RequiresDuplicateDetection = true, UserMetadata = "some metadata" }; topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions); #if SNIPPET string subscriptionName = "<subscription_name>"; #endif var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromDays(7), DefaultMessageTimeToLive = TimeSpan.FromDays(2), EnableBatchedOperations = true, UserMetadata = "some metadata" }; SubscriptionProperties createdSubscription = await client.CreateSubscriptionAsync(subscriptionOptions); #endregion Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic) { MaxMessageSizeInKilobytes = topicOptions.MaxMessageSizeInKilobytes }); Assert.AreEqual(subscriptionOptions, new CreateSubscriptionOptions(createdSubscription)); } finally { await client.DeleteTopicAsync(topicName); } }
public async Task GetUpdateDeleteTopicAndSubscription() { string topicName = Guid.NewGuid().ToString("D").Substring(0, 8); string subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); string connectionString = TestEnvironment.ServiceBusConnectionString; var client = new ServiceBusManagementClient(connectionString); var topicOptions = new CreateTopicOptions(topicName); var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName); await client.CreateTopicAsync(topicOptions); await client.CreateSubscriptionAsync(subscriptionOptions); #region Snippet:GetTopic TopicProperties topic = await client.GetTopicAsync(topicName); #endregion #region Snippet:GetSubscription SubscriptionProperties subscription = await client.GetSubscriptionAsync(topicName, subscriptionName); #endregion #region Snippet:UpdateTopic topic.UserMetadata = "some metadata"; TopicProperties updatedTopic = await client.UpdateTopicAsync(topic); #endregion Assert.AreEqual("some metadata", updatedTopic.UserMetadata); #region Snippet:UpdateSubscription subscription.UserMetadata = "some metadata"; SubscriptionProperties updatedSubscription = await client.UpdateSubscriptionAsync(subscription); #endregion Assert.AreEqual("some metadata", updatedSubscription.UserMetadata); // need to delete the subscription before the topic, as deleting // the topic would automatically delete the subscription #region Snippet:DeleteSubscription await client.DeleteSubscriptionAsync(topicName, subscriptionName); #endregion Assert.That( async() => await client.GetSubscriptionAsync(topicName, subscriptionName), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound)); #region Snippet:DeleteTopic await client.DeleteTopicAsync(topicName); #endregion Assert.That( async() => await client.GetTopicAsync(topicName), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound)); }
public static Task Create(ServiceBusAdministrationClient client, CommandOption topicName, CommandOption <int> size, CommandOption partitioning) { var topicNameToUse = topicName.HasValue() ? topicName.Value() : DefaultTopicName; var options = new CreateTopicOptions(topicNameToUse) { EnableBatchedOperations = true, EnablePartitioning = partitioning.HasValue(), MaxSizeInMegabytes = (size.HasValue() ? size.ParsedValue : 5) * 1024 }; return(client.CreateTopicAsync(options)); }
public async Task CreateQueues(string[] queues, CancellationToken cancellationToken = default) { await namespacePermissions.CanManage(cancellationToken).ConfigureAwait(false); var topic = new CreateTopicOptions(transportSettings.TopicName) { EnableBatchedOperations = true, EnablePartitioning = transportSettings.EnablePartitioning, MaxSizeInMegabytes = maxSizeInMb }; try { await administrativeClient.CreateTopicAsync(topic, cancellationToken).ConfigureAwait(false); } catch (ServiceBusException sbe) when(sbe.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists) { Logger.Info($"Topic {topic.Name} already exists"); } catch (ServiceBusException sbe) when(sbe.IsTransient) // An operation is in progress. { Logger.Info($"Topic creation for {topic.Name} is already in progress"); } foreach (var address in queues) { var queue = new CreateQueueOptions(address) { EnableBatchedOperations = true, LockDuration = TimeSpan.FromMinutes(5), MaxDeliveryCount = int.MaxValue, MaxSizeInMegabytes = maxSizeInMb, EnablePartitioning = transportSettings.EnablePartitioning }; try { await administrativeClient.CreateQueueAsync(queue, cancellationToken).ConfigureAwait(false); } catch (ServiceBusException sbe) when(sbe.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists) { Logger.Debug($"Queue {queue.Name} already exists"); } catch (ServiceBusException sbe) when(sbe.IsTransient) // An operation is in progress. { Logger.Info($"Queue creation for {queue.Name} is already in progress"); } } }
/// <summary> /// Agrega el db context yu registra todo lo necesair para poder despachar Integration Events /// </summary> /// <param name="services"></param> /// <param name="serviceBusCnnString"></param> /// <param name="config"></param> /// <param name="modelsAssemblies">Los assenblies adonde estan ls modelss de lso cuales e pueden disprar eventyops</param> public static void AddServiceBusIntegrationEventSender(this IServiceCollection services, IntegrationEventTopicConfiguration config, params Assembly[] modelsAssemblies) { if (string.IsNullOrEmpty(config.ConnectionString) == false) { List <Type> events = new List <Type>(); foreach (Assembly modelAssembly in modelsAssemblies) { events.AddRange(GetRootEntities(modelAssembly)); } var adm = new Azure.Messaging.ServiceBus.Administration.ServiceBusAdministrationClient(config.ConnectionString); ServiceBusClient client = new ServiceBusClient(config.ConnectionString); foreach (Type root in events) { var exits = adm.TopicExistsAsync(GetTopicName(root)).GetAwaiter().GetResult(); if (!exits) { var options = new CreateTopicOptions(GetTopicName(root)); options.DefaultMessageTimeToLive = new TimeSpan(0, 0, config.TimeToLiveSeconds); options.EnablePartitioning = config.EnablePatitioning; if (config.MaxSizeInMegabytes != null) { options.MaxSizeInMegabytes = config.MaxSizeInMegabytes.Value; } if (config.AutoDeleteSeconds != null) { options.AutoDeleteOnIdle = new TimeSpan(0, 0, config.AutoDeleteSeconds.Value); } if (config.DuplicateDetectionSeconds != null) { options.RequiresDuplicateDetection = true; options.DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 0, config.DuplicateDetectionSeconds.Value); } adm.CreateTopicAsync(options).GetAwaiter().GetResult(); } var sender = client.CreateSender(GetTopicName(root)); services.AddSingleton(sender); } } services.AddScoped <IIntegrationEventSender, ServiceBusTopicSender>(); }
public static async Task <TopicProperties> CreateTopicAsync(string topicName, string connectionString) { var client = new ServiceBusAdministrationClient(connectionString); var topicOptions = new CreateTopicOptions(topicName) { DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 2048, UserMetadata = "some metadata" }; topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); return(await client.CreateTopicAsync(topicOptions)); }
public void CanCreateTopicPropertiesFromOptions() { var options = new CreateTopicOptions("topic") { MaxSizeInMegabytes = 1024, RequiresDuplicateDetection = true, DefaultMessageTimeToLive = TimeSpan.FromSeconds(120), AutoDeleteOnIdle = TimeSpan.FromMinutes(10), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromSeconds(100), EnableBatchedOperations = true, AuthorizationRules = { new SharedAccessAuthorizationRule("key", new AccessRights[] { AccessRights.Listen }) }, Status = EntityStatus.Disabled, EnablePartitioning = true, UserMetadata = "metadata" }; var properties = new TopicProperties(options); Assert.AreEqual(options, new CreateTopicOptions(properties)); }
public async Task AuthenticateWithSharedKeyCredential() { var queueName = Recording.Random.NewGuid().ToString("D").Substring(0, 8); var topicName = Recording.Random.NewGuid().ToString("D").Substring(0, 8); var client = CreateSharedKeyTokenClient(); var queueOptions = new CreateQueueOptions(queueName); QueueProperties createdQueue = await client.CreateQueueAsync(queueOptions); Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue)); var topicOptions = new CreateTopicOptions(topicName); TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions); Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic)); await client.DeleteQueueAsync(queueName); await client.DeleteTopicAsync(topicName); }
public async Task AuthenticateWithAAD() { var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ServiceBusManagementClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential); var queueOptions = new CreateQueueOptions(queueName); QueueProperties createdQueue = await client.CreateQueueAsync(queueOptions); Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue)); var topicOptions = new CreateTopicOptions(topicName); TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions); Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic)); await client.DeleteQueueAsync(queueName); await client.DeleteTopicAsync(topicName); }
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 BasicTopicCrudOperations() { var topicName = nameof(BasicTopicCrudOperations).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8); var client = CreateClient(); var options = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 1024, RequiresDuplicateDetection = true, UserMetadata = nameof(BasicTopicCrudOperations) }; options.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); Response <TopicProperties> createdTopicResponse = await client.CreateTopicAsync(options); Response rawResponse = createdTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties createdTopic = createdTopicResponse.Value; if (Mode == RecordedTestMode.Playback) { // Auth rules use a randomly generated key, but we don't want to store // these in our test recordings, so we skip the auth rule comparison // when in playback mode. Assert.AreEqual(options, new CreateTopicOptions(createdTopic) { AuthorizationRules = options.AuthorizationRules.Clone() }); Assert.AreEqual(createdTopic, new TopicProperties(options) { AuthorizationRules = createdTopic.AuthorizationRules.Clone() }); } else { Assert.AreEqual(options, new CreateTopicOptions(createdTopic)); Assert.AreEqual(createdTopic, new TopicProperties(options)); } Response <TopicProperties> getTopicResponse = await client.GetTopicAsync(options.Name); rawResponse = getTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties getTopic = getTopicResponse.Value; Assert.AreEqual(createdTopic, getTopic); getTopic.EnableBatchedOperations = false; getTopic.DefaultMessageTimeToLive = TimeSpan.FromDays(3); getTopic.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2); getTopic.EnableBatchedOperations = false; getTopic.MaxSizeInMegabytes = 1024; Response <TopicProperties> updatedTopicResponse = await client.UpdateTopicAsync(getTopic); rawResponse = updatedTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties updatedTopic = updatedTopicResponse.Value; Assert.AreEqual(getTopic, updatedTopic); bool exists = await client.TopicExistsAsync(topicName); Assert.True(exists); List <TopicProperties> topicList = new List <TopicProperties>(); await foreach (TopicProperties topic in client.GetTopicsAsync()) { topicList.Add(topic); } topicList = topicList.Where(e => e.Name.StartsWith(nameof(BasicTopicCrudOperations).ToLower())).ToList(); Assert.True(topicList.Count == 1, $"Expected 1 topic but {topicList.Count} topics returned"); Assert.AreEqual(topicList.First().Name, topicName); Response response = await client.DeleteTopicAsync(updatedTopic.Name); Assert.NotNull(response.ClientRequestId); Assert.IsTrue(response.ContentStream.CanRead); Assert.AreEqual(0, response.ContentStream.Position); Assert.That( async() => await client.GetTopicAsync(options.Name), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound)); exists = await client.TopicExistsAsync(topicName); Assert.False(exists); }
public async Task BasicTopicCrudOperations() { var topicName = nameof(BasicTopicCrudOperations).ToLower() + Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString); var options = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 2048, RequiresDuplicateDetection = true, UserMetadata = nameof(BasicTopicCrudOperations) }; options.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); TopicProperties createdTopic = await client.CreateTopicAsync(options); Assert.AreEqual(options, new CreateTopicOptions(createdTopic)); TopicProperties getTopic = await client.GetTopicAsync(options.Name); Assert.AreEqual(createdTopic, getTopic); getTopic.EnableBatchedOperations = false; getTopic.DefaultMessageTimeToLive = TimeSpan.FromDays(3); getTopic.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2); getTopic.EnableBatchedOperations = false; getTopic.MaxSizeInMegabytes = 1024; TopicProperties updatedTopic = await client.UpdateTopicAsync(getTopic); Assert.AreEqual(getTopic, updatedTopic); bool exists = await client.TopicExistsAsync(topicName); Assert.True(exists); List <TopicProperties> topicList = new List <TopicProperties>(); await foreach (TopicProperties topic in client.GetTopicsAsync()) { topicList.Add(topic); } topicList = topicList.Where(e => e.Name.StartsWith(nameof(BasicTopicCrudOperations).ToLower())).ToList(); Assert.True(topicList.Count == 1, $"Expected 1 topic but {topicList.Count} topics returned"); Assert.AreEqual(topicList.First().Name, topicName); await client.DeleteTopicAsync(updatedTopic.Name); Assert.That( async() => await client.GetTopicAsync(options.Name), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusException.FailureReason.MessagingEntityNotFound)); exists = await client.TopicExistsAsync(topicName); Assert.False(exists); }