public async Task <QueueDetailViewModel> GetQueueByName(string queueName, bool isLookDeadletter = false) { if (string.IsNullOrEmpty(queueName)) { return(null); } var managementClient = new ManagementClient(_connectionString); var queue = await managementClient.GetQueueRuntimeInfoAsync(queueName); if (queue == null) { return(null); } var model = new QueueDetailViewModel { Path = queue.Path, MessageCount = queue.MessageCount, CreatedAt = queue.CreatedAt, UpdatedAt = queue.UpdatedAt, AccessedAt = queue.AccessedAt, ActiveMessageCount = queue.MessageCountDetails.ActiveMessageCount, DeadLetterMessageCount = queue.MessageCountDetails.DeadLetterMessageCount, ScheduledMessageCount = queue.MessageCountDetails.ScheduledMessageCount, TransferMessageCount = queue.MessageCountDetails.TransferMessageCount, TransferDeadLetterMessageCount = queue.MessageCountDetails.TransferDeadLetterMessageCount, }; await managementClient.CloseAsync(); return(model); }
public async Task Stop() { stop.Cancel(); await poller.ConfigureAwait(false); await managementClient.CloseAsync().ConfigureAwait(false); }
/// <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); } }
private async Task DeleteTopicSubscriptionAsync(CancellationToken cancellationToken) { ServiceBusConnectionStringBuilder serviceBusConnectionString = await GetServiceBusConnectionStringAsync(); var serviceBusClient = new ManagementClient(serviceBusConnectionString); try { bool subscriptionExists = await serviceBusClient.SubscriptionExistsAsync( serviceBusConnectionString.EntityPath, SubscriptionName, cancellationToken); if (subscriptionExists) { Logger.LogTrace( "[Job: {JobId}] Deleting subscription '{SubscriptionName}' on topic '{Path}'...", JobId, SubscriptionName, serviceBusConnectionString.EntityPath); await serviceBusClient.DeleteSubscriptionAsync(serviceBusConnectionString.EntityPath, SubscriptionName, cancellationToken); Logger.LogTrace( "[Job: {JobId}] Subscription '{SubscriptionName}' deleted on topic '{Path}'", JobId, SubscriptionName, serviceBusConnectionString.EntityPath); } else { Logger.LogTrace( "[Job: {JobId}] Cannot delete topic subscription with name '{SubscriptionName}' because no subscription exists on Service Bus resource", JobId, SubscriptionName); } } finally { await serviceBusClient.CloseAsync().ConfigureAwait(continueOnCapturedContext: false); } }
public override void Dispose() { base.Dispose(); CloseSender(); CloseReceiver(); _managementClient.CloseAsync(); }
public async Task TopicDescriptionParsedFromResponseEqualityCheckTest() { var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString)); var name = Guid.NewGuid().ToString("D").Substring(0, 8); try { var topicDescription = new TopicDescription(name); var createdTopicDescription = await client.CreateTopicAsync(topicDescription); var identicalTopicDescription = new TopicDescription(name); Assert.Equal(identicalTopicDescription, createdTopicDescription); await client.DeleteTopicAsync(name); } catch { await SafeDeleteTopic(client, name); throw; } finally { await client.CloseAsync(); } }
static void Main(string[] args) { Start().Wait(); //Console.ReadLine(); _queueClient.CloseAsync().Wait(); _managementClient.CloseAsync().Wait(); }
public async Task Subscribe(Type eventType, ContextBag context) { await CheckForManagePermissions().ConfigureAwait(false); var ruleName = eventType.FullName.Length > maxNameLength?ruleShortener(eventType.FullName) : eventType.FullName; var sqlExpression = $"[{Headers.EnclosedMessageTypes}] LIKE '%{eventType.FullName}%'"; var rule = new RuleDescription(ruleName, new SqlFilter(sqlExpression)); var client = new ManagementClient(connectionStringBuilder, tokenProvider); try { var existingRule = await client.GetRuleAsync(topicPath, subscriptionName, rule.Name).ConfigureAwait(false); if (existingRule.Filter.ToString() != rule.Filter.ToString()) { rule.Action = existingRule.Action; await client.UpdateRuleAsync(topicPath, subscriptionName, rule).ConfigureAwait(false); } } catch (MessagingEntityNotFoundException) { try { await client.CreateRuleAsync(topicPath, subscriptionName, rule).ConfigureAwait(false); } catch (MessagingEntityAlreadyExistsException) { } } await client.CloseAsync().ConfigureAwait(false); }
public async Task InitializeAsync() { Console.WriteLine("Initializing AMQP..."); var managementClient = new ManagementClient(_connectionString); for (int i = 0; i < _addresses.Length; i++) { string address = _addresses[i]; int listenerCount = _addressListenerCounts[i]; if (!await managementClient.QueueExistsAsync(address).ConfigureAwait(false)) { Console.WriteLine($"Creating AMQP queue {address}..."); await managementClient.CreateQueueAsync(new QueueDescription(address) { LockDuration = TimeSpan.FromMinutes(1), MaxDeliveryCount = Int32.MaxValue, EnablePartitioning = true, MaxSizeInMB = 2048 }).ConfigureAwait(false); Console.WriteLine($"Created AMQP queue {address}"); } await AddQueueClientAsync(listenerCount, address).ConfigureAwait(false); } await managementClient.CloseAsync().ConfigureAwait(false); Console.WriteLine($"AMQP initialized successfully"); }
public override void Dispose() { base.Dispose(); CloseTopicClient(); CloseSubscriptionClient(); _managementClient?.CloseAsync(); }
public override async Task <CheckResult> PerformCheck() { if (!runCheck) { return(CheckResult.Pass); } Logger.Debug("Checking Dead Letter Queue length"); var managementClient = new ManagementClient(connectionString); try { var queueRuntimeInfo = await managementClient.GetQueueRuntimeInfoAsync(stagingQueue).ConfigureAwait(false); var deadLetterMessageCount = queueRuntimeInfo.MessageCountDetails.DeadLetterMessageCount; if (deadLetterMessageCount > 0) { var result = $"{deadLetterMessageCount} messages in the Dead Letter Queue '{stagingQueue}'. This could indicate a problem with ServiceControl's retries. Please submit a support ticket to Particular using [email protected] if you would like help from our engineers to ensure no message loss while resolving these dead letter messages."; Logger.Warn(result); return(CheckResult.Failed(result)); } Logger.Debug("No messages in Dead Letter Queue"); } finally { await managementClient.CloseAsync().ConfigureAwait(false); } return(CheckResult.Pass); }
static async Task Main(string[] args) { var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString"); var management = new ManagementClient(connectionString); if (!await management.QueueExistsAsync("queue")) { await management.CreateQueueAsync("queue"); } var sender = new MessageSender(connectionString, "queue"); while (true) { using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)) { Debugger.Break(); await sender.SendAsync(new Message(Encoding.Default.GetBytes(DateTime.Now.ToString("s")))); Console.WriteLine("message sent"); tx.Complete(); Console.WriteLine("tx completed"); } } await management.CloseAsync(); await sender.CloseAsync(); }
static void Main(string[] args) { //Initialize(); Initialize(20); Console.ReadLine(); _queueClient.CloseAsync().Wait(); _managementClient.CloseAsync().Wait(); }
public void Dispose() { Task.Run(async() => { await managementClient.CloseAsync(); await topicClient.CloseAsync(); }).Wait(TimeSpan.FromSeconds(10)); }
public async Task <IEnumerable <QueueDescription> > GetQueues() { var managementClient = new ManagementClient(_connectionString); IList <QueueDescription> queues = await managementClient.GetQueuesAsync(); await managementClient.CloseAsync(); return(queues); }
public static async Task Run(CommandOption connectionString, Func <ManagementClient, Task> func) { var connectionStringToUse = connectionString.HasValue() ? connectionString.Value() : Environment.GetEnvironmentVariable(EnvironmentVariableName); var client = new ManagementClient(connectionStringToUse); await func(client); await client.CloseAsync(); }
public async Task Init() { var managementClient = new ManagementClient(_connectionSettings.ConnectionString); if (!await managementClient.SubscriptionExistsAsync(ChannelName, _subscriptionName).ConfigureAwait(false)) { await managementClient.CreateSubscriptionAsync(new SubscriptionDescription(ChannelName, _subscriptionName)).ConfigureAwait(false); } await managementClient.CloseAsync().ConfigureAwait(false); }
public async Task ShutdownAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); _messageSendTimer.Stop(); await _managementClient.CloseAsync(); await _messageReceiver.CloseAsync(); await _messageSender.CloseAsync(); }
public async Task <SubscriptionRuntimeInfo> GetSubscriptionRuntimeInfo(string connectionString, string topicPath, string subscriptionName) { ManagementClient client = new ManagementClient(connectionString); var runtimeInfo = await client.GetSubscriptionRuntimeInfoAsync(topicPath, subscriptionName); await client.CloseAsync(); return(runtimeInfo); }
public async Task <HealthCheckResult> CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default) { try { ServiceBusConnectionStringBuilder connectionStringBuilder = new ServiceBusConnectionStringBuilder(_rulesConfiguration.ConnectionString); var managementClient = new ManagementClient(connectionStringBuilder); foreach (Topic topic in _rulesConfiguration.Topics) { if (!await managementClient.TopicExistsAsync(topic.Name, cancellationToken)) { return(new HealthCheckResult( context.Registration.FailureStatus, description: $"Topic with name: {topic.Name} doesn't exists.")); } connectionStringBuilder.EntityPath = topic.Name; foreach (Subscriber subscriber in topic.Subscribers) { if (!await managementClient.SubscriptionExistsAsync(topic.Name, subscriber.Name, cancellationToken)) { return(new HealthCheckResult( context.Registration.FailureStatus, description: $"Subscription with name: {subscriber.Name} doesn't exists.")); } SubscriptionClient subscriptionClient = new SubscriptionClient(connectionStringBuilder, subscriber.Name); bool allRuleApplied = await CheckRulesAsync(subscriber, subscriptionClient); if (!allRuleApplied) { return(new HealthCheckResult(HealthStatus.Unhealthy, "Not all rules were applied")); } await subscriptionClient.CloseAsync(); } } await managementClient.CloseAsync(); return(new HealthCheckResult(HealthStatus.Healthy)); } catch (Exception ex) { return(new HealthCheckResult(context.Registration.FailureStatus, exception: ex)); } }
private async Task DeleteQueueAsync(string connectionString, string path) { var managementClient = new ManagementClient(connectionString); if (await managementClient.QueueExistsAsync(path)) { await managementClient.DeleteQueueAsync(path); } await managementClient.CloseAsync(); }
public async ValueTask DisposeAsync() { var address = _connection.Endpoint.ToString(); TransportLogMessages.DisconnectHost(address); await _managementClient.CloseAsync().ConfigureAwait(false); await _connection.CloseAsync().ConfigureAwait(false); TransportLogMessages.DisconnectedHost(address); }
static void Main(string[] args) { _queueClient.RegisterMessageHandler(MessageHandler, new MessageHandlerOptions(ErrorHandler) { AutoComplete = false, MaxAutoRenewDuration = TimeSpan.FromMinutes(10), MaxConcurrentCalls = 5 }); Console.ReadLine(); _queueClient.CloseAsync().Wait(); _managementClient.CloseAsync().Wait(); }
static async Task Main(string[] args) { var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString"); const string sqlConnectionString = Environment.GetEnvironmentVariable("SQLServer_ConnectionString"); var management = new ManagementClient(connectionString); if (!await management.QueueExistsAsync("input")) { await management.CreateQueueAsync("input"); } if (!await management.QueueExistsAsync("output")) { await management.CreateQueueAsync("output"); } var message = new Message(Encoding.UTF8.GetBytes("test message")); var sender = new MessageSender(connectionString, "input"); await sender.SendAsync(message); await sender.CloseAsync(); // receive a message var connection = new ServiceBusConnection(connectionString); var receiver = new MessageReceiver(connection, "input"); sender = new MessageSender(connection, entityPath: "output", viaEntityPath: "input"); var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(30)); message = await receiver.ReceiveAsync(); using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendAsync(new Message(Encoding.Default.GetBytes("response"))); await receiver.CompleteAsync(message.SystemProperties.LockToken); using (var suppress = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { await ExecuteInnerTransaction(sqlConnectionString); suppress.Complete(); } tx.Complete(); } await management.CloseAsync(); await sender.CloseAsync(); await receiver.CloseAsync(); }
public static async Task Stage(string connectionString, string destination) { var client = new ManagementClient(connectionString); if (await client.QueueExistsAsync(destination)) { await client.DeleteQueueAsync(destination); } await client.CreateQueueAsync(destination); await client.CloseAsync(); }
static void Main(string[] args) { _queueClient.RegisterSessionHandler(SessionHandler, new SessionHandlerOptions(ErrorSessionHandler) { AutoComplete = false, MessageWaitTimeout = TimeSpan.FromSeconds(5), MaxConcurrentSessions = 10, MaxAutoRenewDuration = TimeSpan.FromMinutes(5) }); Console.WriteLine("Session handler registered"); Console.ReadLine(); _queueClient.CloseAsync().Wait(); _managementClient.CloseAsync().Wait(); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { GetSettings(context, log); string[] playTypes = { "offense_sideline", "offense_endzone", "defense_sideline", "defense_endzone", "specialteams" }; var managementClient = new ManagementClient(settings.ServiceBusConnectionString); string GameKey = req.Query["GameKey"]; long count = 0; List <string> gameKeys = new List <string>(); foreach (string plays in playTypes) { IMessageReceiver messageReceiver = new MessageReceiver(settings.ServiceBusConnectionString, plays, ReceiveMode.PeekLock); var queue = await managementClient.GetQueueRuntimeInfoAsync(plays); var messageCount = queue.MessageCount; count += messageCount; // Retrieve the exact number of messages for each queue var messages = await messageReceiver.PeekAsync((int)count); foreach (Message ms in messages) { var newGameMessage = JsonConvert.DeserializeObject <messageBody>(Encoding.UTF8.GetString(ms.Body)); gameKeys.Add(newGameMessage.gamekey); } } await managementClient.CloseAsync(); log.LogInformation($"Game Key is {GameKey}"); if (gameKeys.Contains(GameKey)) { req.HttpContext.Response.Headers.Add("location", settings.FunctionURL + "&GameKey=" + GameKey); req.HttpContext.Response.Headers.Add("retry-after", "30"); log.LogInformation($"Messages remaining for game {GameKey}: {count}"); return(new StatusCodeResult((int)HttpStatusCode.Accepted)); } log.LogInformation($"Message count for {GameKey}: {count}"); return(new OkObjectResult("Completed")); }
public async Task Init() { var managementClient = new ManagementClient(_connectionSettings.ConnectionString); if (!await managementClient.TopicExistsAsync(ChannelName).ConfigureAwait(false)) { await managementClient.CreateTopicAsync(new TopicDescription(ChannelName) { DefaultMessageTimeToLive = TimeSpan.FromDays(7), EnableBatchedOperations = true, }).ConfigureAwait(false); } await managementClient.CloseAsync().ConfigureAwait(false); }
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 <IList <ServiceBusSubscription> > GetSubscriptions(string connectionString, string topicPath) { IList <ServiceBusSubscription> subscriptions = new List <ServiceBusSubscription>(); var client = new ManagementClient(connectionString); var topicSubscription = await client.GetSubscriptionsRuntimeInfoAsync(topicPath); await client.CloseAsync(); foreach (var sub in topicSubscription) { subscriptions.Add(new ServiceBusSubscription(sub)); } return(subscriptions); }