public async Task CreateTopicAsync(string topicName, ManagementClient managementClient) { try { TopicDescription topic = null; if (!await managementClient.TopicExistsAsync(topicName)) { topic = await managementClient.CreateTopicAsync(topicName).ConfigureAwait(false); } else { topic = await managementClient.GetTopicAsync(topicName); } if (!await managementClient.SubscriptionExistsAsync(topic.Path, "Subscription1")) { await managementClient.CreateSubscriptionAsync(topic.Path, "Subscription1"); } if (!await managementClient.SubscriptionExistsAsync(topic.Path, "Subscription2")) { await managementClient.CreateSubscriptionAsync(topic.Path, "Subscription2"); } if (!await managementClient.SubscriptionExistsAsync(topic.Path, "Subscription3")) { await managementClient.CreateSubscriptionAsync(topic.Path, "Subscription3"); } } catch (ServiceBusException ex) { Console.WriteLine($"Encountered exception while creating Topic -\n{ex}"); throw; } }
public async Task CreatetopicprioritySubscription(string topicname) { var client = new ManagementClient(sbconnection); bool topicExists = await client.TopicExistsAsync(topicname).ConfigureAwait(false); string[] subscriptionarray = new string[] { "highprioritysubscription", "lowprioritysubscription" }; if (topicExists) { foreach (var item in subscriptionarray) { if (item == "highprioritysubscription") { SubscriptionDescription subName = new SubscriptionDescription(topicname, item); subName.Status = 0; RuleDescription subscriptionRule = new RuleDescription(); subscriptionRule.Filter = new SqlFilter("Priority >= 10"); var result01 = await client.CreateSubscriptionAsync(subName, subscriptionRule).ConfigureAwait(false); } else { SubscriptionDescription subName = new SubscriptionDescription(topicname, item); subName.Status = 0; RuleDescription subscriptionRule = new RuleDescription(); subscriptionRule.Filter = new SqlFilter("Priority < 10"); var result01 = await client.CreateSubscriptionAsync(subName, subscriptionRule).ConfigureAwait(false); } } } }
/// <summary>Adds the subscriber.</summary> /// <param name="routingKey">The routing key.</param> public void AddSubscriber(string routingKey) { ManagementClient client = new ManagementClient(_connectionString); if (!client.SubscriptionExistsAsync(_topicName, _topicSubscription).Result) { SubscriptionDescription subscriptionDescription = new SubscriptionDescription(_topicName, _topicSubscription) { LockDuration = TimeSpan.FromMinutes(5) }; if (!string.IsNullOrWhiteSpace(routingKey)) { RuleDescription ruleDescription = new RuleDescription { Filter = new Microsoft.Azure.ServiceBus.SqlFilter(routingKey) }; client.CreateSubscriptionAsync(subscriptionDescription, ruleDescription); } else { client.CreateSubscriptionAsync(subscriptionDescription); } } }
public async Task <SubscriptionDescriptionDto> CreateSubscriptionAsync(string topicName, string subsName) { var subs = await _managementClient .CreateSubscriptionAsync(topicName, subsName); _logger.LogInformation($"Creating Subscription {subsName} for Topic {topicName}"); return(new SubscriptionDescriptionDto(subs)); }
public async Task <SubscriptionDescription> CreateSubscriptionAsync(string topicPath, string subscriptionName) { Console.WriteLine($"Creating Subscription { topicPath }/{ subscriptionName }"); await CreateTopicAsync(topicPath); if (!await _managementClient.SubscriptionExistsAsync(topicPath, subscriptionName)) { return(await _managementClient.CreateSubscriptionAsync(topicPath, subscriptionName)); } return(await _managementClient.GetSubscriptionAsync(topicPath, subscriptionName)); }
static async Task CreateSubscriptions() { Console.WriteLine("Creating subscriptions.."); //filter by job that ends with leader if (!await _managementClient.SubscriptionExistsAsync(_topic, "SubLeader")) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topic, "SubLeader") { AutoDeleteOnIdle = TimeSpan.FromMinutes(30) }, new RuleDescription("FilterByLeader", new SqlFilter("job LIKE '%Leader'"))); } //filter by salary that is greater than 2500 if (!await _managementClient.SubscriptionExistsAsync(_topic, "SubHighSalary")) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topic, "SubHighSalary") { AutoDeleteOnIdle = TimeSpan.FromMinutes(30) }, new RuleDescription("FilterBySalary", new SqlFilter("salary > 2500"))); } //filter by job that has title = Software Developer if (!await _managementClient.SubscriptionExistsAsync(_topic, "SubDevJob")) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topic, "SubDevJob") { AutoDeleteOnIdle = TimeSpan.FromMinutes(30) }, new RuleDescription("FilterByDevJob", new CorrelationFilter("Software Developer"))); } //filter by job that has title = Software Tester if (!await _managementClient.SubscriptionExistsAsync(_topic, "SubTesterJob")) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topic, "SubTesterJob") { AutoDeleteOnIdle = TimeSpan.FromMinutes(30) }, new RuleDescription("FilterByTesterJob", new CorrelationFilter { Label = "Software Tester" })); } //Wire-Tap await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topic, $"wire-{Guid.NewGuid().ToString()}") { AutoDeleteOnIdle = TimeSpan.FromMinutes(30), }); Console.WriteLine("Done.\n"); }
static void Init() { try { _managementClient = new ManagementClient(_connectionString); if (!_managementClient.TopicExistsAsync(_topicName).Result) { _managementClient.CreateTopicAsync(new TopicDescription(_topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), EnablePartitioning = true, RequiresDuplicateDetection = true, DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2), EnableBatchedOperations = true }); } _topicClient = new TopicClient(_connectionString, _topicName); string subscriberByDevJob = Guid.NewGuid().ToString(); RuleDescription ruleDescriptionByDevJob = new RuleDescription("DevJobRule", new SqlFilter("Job = 'Developer'")); if (!_managementClient.SubscriptionExistsAsync(_topicName, subscriberByDevJob).Result) { _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, subscriberByDevJob) { AutoDeleteOnIdle = TimeSpan.FromMinutes(40), EnableBatchedOperations = true }, ruleDescriptionByDevJob).Wait(); } string subscriberByIDCountry = Guid.NewGuid().ToString(); RuleDescription ruleDescriptionByIDCountry = new RuleDescription("IDCountryRule", new SqlFilter("Country = 'ID'")); if (!_managementClient.SubscriptionExistsAsync(_topicName, subscriberByIDCountry).Result) { _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, subscriberByIDCountry) { AutoDeleteOnIdle = TimeSpan.FromMinutes(40), EnableBatchedOperations = true }, ruleDescriptionByIDCountry).Wait(); } _subscriberByDeveloperJob = new SubscriptionClient(_connectionString, _topicName, subscriberByDevJob); _subscriberByIDCountry = new SubscriptionClient(_connectionString, _topicName, subscriberByIDCountry); } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task MessagingEntityAlreadyExistsExceptionTest() { var queueName = Guid.NewGuid().ToString("D").Substring(0, 8); var topicName = Guid.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); try { await client.CreateQueueAsync(queueName); await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>( async() => { await client.CreateQueueAsync(queueName); }); await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>( async() => { await client.CreateTopicAsync(topicName); }); await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>( async() => { await client.CreateSubscriptionAsync(topicName, subscriptionName); }); // Cleanup await client.DeleteQueueAsync(queueName); await client.DeleteTopicAsync(topicName); } catch { await Task.WhenAll(SafeDeleteTopic(client, topicName), SafeDeleteQueue(client, queueName)); throw; } finally { await client.CloseAsync(); } }
public async Task StartAsync() { _client = await _clientFactory.GetSubscriptionClient <TTopic, IEventSubscription <TTopic> >(_subscription).ConfigureAwait(false); if (!await _managementClient.TopicExistsAsync(_client.TopicPath).ConfigureAwait(false)) { await _managementClient.CreateTopicAsync(new TopicDescription(_client.TopicPath) { EnableBatchedOperations = _configuration.CreationOptions.EnableBatchedOperations, EnablePartitioning = _configuration.CreationOptions.EnablePartitioning, SupportOrdering = _configuration.CreationOptions.SupportOrdering }).ConfigureAwait(false); } if (!await _managementClient.SubscriptionExistsAsync(_client.TopicPath, _client.SubscriptionName).ConfigureAwait(false)) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_client.TopicPath, _client.SubscriptionName) { EnableBatchedOperations = _configuration.CreationOptions.EnableBatchedOperations }).ConfigureAwait(false); } _deadLetterLimit = Settings.DeadLetterDeliveryLimit; _client.PrefetchCount = Settings.PrefetchCount; var options = new MessageHandlerOptions(OnExceptionReceivedAsync) { AutoComplete = false, MaxAutoRenewDuration = Settings.MessageLockTimeout, MaxConcurrentCalls = Settings.MaxConcurrentCalls }; _client.RegisterMessageHandler(OnMessageAsync, options); }
public async Task CreateSubscriptionAsync( string managementConnectionString, string subscriptionName, string topicPath, TimeSpan autoDeleteOnIdleTimeout, CancellationToken cancellationToken = default ) { try { var managementClient = new ManagementClient(managementConnectionString); await managementClient.CreateSubscriptionAsync( new SubscriptionDescription(topicPath, subscriptionName) { AutoDeleteOnIdle = autoDeleteOnIdleTimeout }, cancellationToken ).ConfigureAwait(false); _logger.NewSubscriptionCreated(subscriptionName); } catch (ServiceBusException e) { throw new ServiceBusSubscriptionCreationException(e); } }
public void CreateSubscription(string topicName, string subscriptionName, int maxDeliveryCount = 2000) { s_logger.LogInformation("Creating subscription {ChannelName} for topic {Topic}...", subscriptionName, topicName); if (!TopicExists(topicName)) { CreateTopic(topicName); } var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName) { MaxDeliveryCount = maxDeliveryCount }; try { _managementClient.CreateSubscriptionAsync(subscriptionDescription).Wait(); } catch (Exception e) { s_logger.LogError(e, "Failed to create subscription {ChannelName} for topic {Topic}.", subscriptionName, topicName); throw; } s_logger.LogInformation("Subscription {ChannelName} for topic {Topic} created.", subscriptionName, topicName); }
public async Task CreateTopicAsync() { string entityPath = "runtime-creation"; var connstr = $"Endpoint=sb://localrequestbus-dev.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=fVoIfvx0cI0oY7Zkni4dknP6FbZbjh3DiUh7Ci4rrfI=;"; var client = new ManagementClient(connstr); if (!await client.TopicExistsAsync(entityPath)) { await client.CreateTopicAsync(entityPath); await client.CreateSubscriptionAsync(entityPath, "application"); await client.CreateSubscriptionAsync(entityPath, "admin"); } }
public async Task EnsureSubscriptionIsSetup(string subscriptionName) { try { // The hash lookup works only when this class is registered in DI as a singleton if (subscriptionsThatHaveBeenSetup.Contains(subscriptionName)) { return; } subscriptionsThatHaveBeenSetup.Add(subscriptionName); if (!await managementClient.SubscriptionExistsAsync(topicName, subscriptionName)) { await managementClient.CreateSubscriptionAsync(new SubscriptionDescription(topicName, subscriptionName), MakeRule(subscriptionName)); } else { // The default rule is to accept everything, so delete it and replace it with the subscriptionName filter await managementClient.DeleteRuleAsync(topicName, subscriptionName, "$Default"); await managementClient.CreateRuleAsync(topicName, subscriptionName, MakeRule(subscriptionName)); } } catch (Exception e) { logger.LogError(e, $"Error setting up subscription for subscriptionName: {subscriptionName}"); } }
static void Init() { try { _managementClient = new ManagementClient(_connectionString); if (!_managementClient.TopicExistsAsync(_topicName).Result) { _managementClient.CreateTopicAsync(new TopicDescription(_topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1) }).Wait(); } _senderTopicClient = new TopicClient(_connectionString, _topicName); if (!_managementClient.SubscriptionExistsAsync(_topicName, _subscriptionName).Result) { _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, _subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(45), EnableDeadLetteringOnMessageExpiration = true }).Wait(); } string deadLetterPath = EntityNameHelper.FormatDeadLetterPath(_subscriptionName); _subscriptionClient = new SubscriptionClient(_connectionString, _topicName, _subscriptionName); _deadLetterSubscriptionClient = new SubscriptionClient(_connectionString, _topicName, deadLetterPath); } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task <object> CreateSbtopic(string topicname, string subscriptionName) { var client = new ManagementClient(sbconnection); bool topicExists = await client.TopicExistsAsync(topicname).ConfigureAwait(false); if (!topicExists) { TopicDescription topicName = new TopicDescription(topicname); topicName.MaxSizeInMB = 1024; topicName.DefaultMessageTimeToLive = new TimeSpan(2, 0, 0, 0); dynamic result = await client.CreateTopicAsync(topicname).ConfigureAwait(false); if (result.Path != null) { SubscriptionDescription subName = new SubscriptionDescription(result.Path, subscriptionName); subName.Status = 0; var result01 = await client.CreateSubscriptionAsync(subName).ConfigureAwait(false); return(result); } return(result); } else { return("Topic already exsits!!"); } }
public static async Task SubscribeAsync(string serviceBusConnectionString, string subscriptionName, int maxConcurrentCalls = 1) { // Create subscription on first call var client = new ManagementClient(serviceBusConnectionString); if (!await client.SubscriptionExistsAsync(TopicName, subscriptionName).ConfigureAwait(false)) { await client.CreateSubscriptionAsync(new SubscriptionDescription(TopicName, subscriptionName)).ConfigureAwait(false); } // Create subscription client subscriptionClient = new SubscriptionClient(serviceBusConnectionString, TopicName, subscriptionName); // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc. var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = maxConcurrentCalls, // Indicates whether the message pump should automatically complete the messages after returning from user callback. // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync(). AutoComplete = true }; // Register the function that processes messages. subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); }
private static async Task ProvisionSamplesAsync(string connectionString) { var management = new ManagementClient(connectionString); if (false == await management.TopicExistsAsync(TopicName)) { await management.CreateTopicAsync(new TopicDescription(TopicName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(10) }); } if (false == await management.SubscriptionExistsAsync(TopicName, SubscriptionName)) { await management.CreateSubscriptionAsync(new SubscriptionDescription(TopicName, SubscriptionName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(20), DefaultMessageTimeToLive = TimeSpan.FromMinutes(1), MaxDeliveryCount = 2 }); } if (false == await management.QueueExistsAsync(QueueName)) { await management.CreateQueueAsync(new QueueDescription(QueueName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(20), DefaultMessageTimeToLive = TimeSpan.FromMinutes(1), MaxDeliveryCount = 2 }); } }
static void Init() { try { _managementClient = new ManagementClient(_connectionString); if (!_managementClient.TopicExistsAsync(_topicName).Result) { _managementClient.CreateTopicAsync(new TopicDescription(_topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), EnablePartitioning = true, RequiresDuplicateDetection = true, DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2), EnableBatchedOperations = true }); } _topicClient = new TopicClient(_connectionString, _topicName); string subscriptionName = Guid.NewGuid().ToString(); if (!_managementClient.SubscriptionExistsAsync(_topicName, subscriptionName).Result) { _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(45), EnableBatchedOperations = true }).Wait(); } _subscriptionClient = new SubscriptionClient(_connectionString, _topicName, subscriptionName); } catch (Exception ex) { Console.WriteLine(ex); } }
static void Main(string[] args) { Console.WriteLine("Enter name:"); var userName = Console.ReadLine(); // Create a management client to manage artifacts var manager = new ManagementClient(ConnectionString); // Create a topic if it does not exist if (!manager.TopicExistsAsync(TopicPath).Result) { manager.CreateTopicAsync(TopicPath).Wait(); } // Create a subscription for the user var description = new SubscriptionDescription(TopicPath, userName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(5) }; manager.CreateSubscriptionAsync(description).Wait(); // Create clients var topicClient = new TopicClient(ConnectionString, TopicPath); var subscriptionClient = new SubscriptionClient(ConnectionString, TopicPath, userName); // Create a message pump for receiving messages subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, ExceptionReceivedHandler); // Send a message to say you are here var helloMessage = new Message(Encoding.UTF8.GetBytes("Has entered the room...")); helloMessage.Label = userName; topicClient.SendAsync(helloMessage).Wait(); while (true) { string text = Console.ReadLine(); if (text.Equals("exit")) { break; } // Send a chat message var chatMessage = new Message(Encoding.UTF8.GetBytes(text)); chatMessage.Label = userName; topicClient.SendAsync(chatMessage).Wait(); } // Send a message to say you are leaving var goodbyeMessage = new Message(Encoding.UTF8.GetBytes("Has left the building...")); goodbyeMessage.Label = userName; topicClient.SendAsync(goodbyeMessage).Wait(); // Close the clients topicClient.CloseAsync().Wait(); subscriptionClient.CloseAsync().Wait(); }
static async Task Main(string[] args) { Console.WriteLine("Wire Tap Console"); Console.WriteLine("Press enter to activate wire tap"); Console.ReadLine(); var subscriptionName = $"wiretap-{ Guid.NewGuid() }"; var managementClient = new ManagementClient(ServiceBusConnectionString); await managementClient.CreateSubscriptionAsync (new SubscriptionDescription(OrdersTopicPath, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(5) }); var subscriptionClinet = new SubscriptionClient (ServiceBusConnectionString, OrdersTopicPath, subscriptionName); var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 1, AutoComplete = true }; subscriptionClinet.RegisterMessageHandler(InspectMessageAsync, messageHandlerOptions); Console.WriteLine($"Receiving on { subscriptionName }"); Console.WriteLine("Press enter to quit..."); Console.ReadLine(); await subscriptionClinet.CloseAsync(); }
private async Task <SubscriptionDescription> GetOrCreateSubscription(string endpointName, CancellationToken cancellationToken) { var manageClient = new ManagementClient(connectionString); SubscriptionDescription subscriptionDescription; if (!await manageClient.SubscriptionExistsAsync(TopicPath, endpointName, cancellationToken)) { subscriptionDescription = new SubscriptionDescription(TopicPath, endpointName) { ForwardTo = endpointName, UserMetadata = endpointName, EnableBatchedOperations = true, MaxDeliveryCount = Int32.MaxValue, EnableDeadLetteringOnFilterEvaluationExceptions = false, LockDuration = TimeSpan.FromMinutes(5) }; var defaultRule = new RuleDescription("$default") { Filter = new SqlFilter("1=0") }; await manageClient.CreateSubscriptionAsync( subscriptionDescription, defaultRule, cancellationToken); } else { subscriptionDescription = await manageClient.GetSubscriptionAsync(TopicPath, endpointName, cancellationToken); } return(subscriptionDescription); }
public async Task CreateSubscriptionAsync(string topicPath, string subscriptionName) { Console.Write("Creating subscription {0}/subscriptions/{1}...", topicPath, subscriptionName); var description = await m_ManagementClient.CreateSubscriptionAsync(topicPath, subscriptionName); Console.WriteLine("Done!"); }
public async Task <object> CreatetopicCorrelationFilterSubscription(string topicname) { var client = new ManagementClient(sbconnection); bool topicExists = await client.TopicExistsAsync(topicname).ConfigureAwait(false); if (topicExists) { SubscriptionDescription subName = new SubscriptionDescription(topicname, "CorrelationFilterSubscription"); subName.Status = 0; RuleDescription subscriptionRule = new RuleDescription(); subscriptionRule.Filter = new CorrelationFilter { Label = "Correlationfiltersample", ReplyTo = "x", ContentType = "Finanical", }; var result01 = await client.CreateSubscriptionAsync(subName, subscriptionRule).ConfigureAwait(false); return(result01); } else { return("Unable to create CorrelationFilter Subscription!!"); } }
private static async Task Init() { try { _managementClient = new ManagementClient(_connectionString); if (!await _managementClient.TopicExistsAsync(_topicName)) { await _managementClient.CreateTopicAsync(new TopicDescription(_topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2), RequiresDuplicateDetection = true }); } _topicClient = new TopicClient(_connectionString, _topicName); string subscriberName = Guid.NewGuid().ToString(); await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, subscriberName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(45) }); _subscriptionClient = new SubscriptionClient(_connectionString, _topicName, subscriberName); } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task CreateSubscriptionAsync(string tPath, string subscriptionName) { Console.WriteLine($"Creating a subscription {subscriptionName} for {tPath}"); var subscription = await m_ManagementClient.CreateSubscriptionAsync(tPath, subscriptionName); Console.WriteLine("Done"); }
private static async Task CreateTopicIfNotExist(ManagementClient mc, string name, ILogger log) { if (!await mc.TopicExistsAsync(name)) { await mc.CreateTopicAsync(name); log.LogInformation($"Created topic {name}"); } else { log.LogInformation($"Skipped topic {name}"); } if (!await mc.SubscriptionExistsAsync(name, "bridge")) { var sd = new SubscriptionDescription(name, "bridge") { ForwardTo = "bridge" }; var rl = new RuleDescription("bridge") { Filter = new SqlFilter("xbridge is null"), Action = new SqlRuleAction($"set xbridge=1; set sys.to='{name}'") }; await mc.CreateSubscriptionAsync(sd, rl); log.LogInformation($"Created bridge subscription on {name}"); } else { log.LogInformation($"Skipped bridge subscription on {name}"); } }
public async Task CreateSubscriptionAsync(string subscriptionName, string topicName, TimeSpan?deleteOnIdleAfter = null, TimeSpan?timeToLive = null, TimeSpan?lockDuration = null, int?maxDeliveryCount = null, bool useDeadLetterOnExpiration = false) { if (string.IsNullOrWhiteSpace(topicName)) { throw new ArgumentException($"'{nameof(topicName)}' cannot be null or empty.", nameof(topicName)); } if (string.IsNullOrWhiteSpace(subscriptionName)) { throw new ArgumentException($"'{nameof(subscriptionName)}' cannot be null or empty.", nameof(subscriptionName)); } try { var subscription = new SubscriptionDescription(topicName, subscriptionName) { AutoDeleteOnIdle = deleteOnIdleAfter.GetValueOrDefault(ServiceBusSubscriptionDefaults.DeleteOnIdleAfter), DefaultMessageTimeToLive = timeToLive.GetValueOrDefault(ServiceBusSubscriptionDefaults.TimeToLive), EnableBatchedOperations = true, EnableDeadLetteringOnMessageExpiration = useDeadLetterOnExpiration, MaxDeliveryCount = maxDeliveryCount.GetValueOrDefault(ServiceBusSubscriptionDefaults.MaxDeliveryCount), LockDuration = lockDuration.GetValueOrDefault(ServiceBusSubscriptionDefaults.LockDuration), }; await _client.CreateSubscriptionAsync(subscription); } catch (MessagingEntityAlreadyExistsException) { throw new SubscriptionAlreadyExistsException(subscriptionName); } catch (MessagingEntityNotFoundException) { throw new TopicNotFoundException(topicName); } }
public void CreateTopicAndSubscription() { if (!managementClient.TopicExistsAsync(config["BlockchainNodeSettings:BlockchainTopicName"]).Result) { logger.LogInformation("Topic does not exist. Creating new Topic...."); managementClient.CreateTopicAsync(config["BlockchainNodeSettings:BlockchainTopicName"]).GetAwaiter().GetResult(); } else { logger.LogInformation("Topic already exist...."); } if (!managementClient.SubscriptionExistsAsync(config["BlockchainNodeSettings:BlockchainTopicName"], config["BlockchainNodeSettings:NodeName"]).Result) { logger.LogInformation("Subsription does not exist. Creating new Subsription...."); SubscriptionDescription subscriptionDescription = new SubscriptionDescription(config["BlockchainNodeSettings:BlockchainTopicName"], config["BlockchainNodeSettings:NodeName"]) { }; managementClient.CreateSubscriptionAsync(subscriptionDescription).GetAwaiter().GetResult(); } else { logger.LogInformation("Subsription already exist...."); } }
/// <summary> /// Subscribe to a Topic /// </summary> /// <param name="token">Cancellation Token</param> /// <returns></returns> public async Task Subscribe() { ManagementClient client = null; try { client = new ManagementClient(_serviceBusOptions.Value.ConnectionString); //Create Subscription if it doesn't exists if (!await client.SubscriptionExistsAsync(_serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription).ConfigureAwait(false)) { await client.CreateSubscriptionAsync(_serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription).ConfigureAwait(false); } // Log information _logger.LogInformation($"Subscribed to Topic : {_serviceBusOptions.Value.ProductUpdatedTopic} , Subscription Name : {_serviceBusOptions.Value.ProductUpdatedSubscription}"); //Create subscription client _subscriptionClient = new SubscriptionClient(_serviceBusOptions.Value.ConnectionString, _serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription); //Process Messages RegisterOnMessageHandlerAndReceiveMessage(); } catch (Exception ex) { _logger.LogError($"Error in receiving message from topic {_serviceBusOptions.Value.ProductUpdatedTopic}, , Subscription Name : { _serviceBusOptions.Value.ProductUpdatedSubscription} , ex - {ex}"); throw; } finally { await client.CloseAsync().ConfigureAwait(false); } }
public void CreateSubscription(string topicName, string subscriptionName, int maxDeliveryCount = 2000) { Logger.Value.Info($"Creating subscription {subscriptionName} for topic {topicName}..."); if (!TopicExists(topicName)) { CreateTopic(topicName); } var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName) { MaxDeliveryCount = maxDeliveryCount }; try { _managementClient.CreateSubscriptionAsync(subscriptionDescription).Wait(); } catch (Exception e) { Logger.Value.ErrorException($"Failed to create subscription {subscriptionName} for topic {topicName}.", e); throw; } Logger.Value.Info($"Subscription {subscriptionName} for topic {topicName} created."); }