public async Task Get() { #region Snippet:Managing_ServiceBusQueues_GetQueue ServiceBusQueue serviceBusQueue = await serviceBusQueueCollection.GetAsync("myQueue"); #endregion }
/// <summary> /// Get queue from queue identifier /// </summary> /// <param name="queueIdentifier">Queue identifier</param> /// <returns>Messaging queue</returns> public async Task <Queue> GetQueue(QueueIdentifier queueIdentifier) { QueueDescriptor queueDescriptor = QueueDescriptorProvider.Queues[queueIdentifier]; string serviceBusConnectionString = await this.connectionStringProvider.GetServiceBusConnectionString(queueDescriptor.ServiceBusInstanceType); string queueName = queueDescriptor.QueueName; string uniqueQueueIdentity = string.Join(":", serviceBusConnectionString, queueName); // cachedQueueObjects is a thread-safe dictionary (ConcurrentDictionary). If uniqueQueueIdentity is not present // in cachedStoreObjects, try adding it. Since GetQueue can be called concurrently by // different threads, it is possible for two (or more) threads to attempt inserting uniqueQueueIdentity // concurrently in the cachedQueueObjects. That's ok, because the call to TryAdd is guaranteed to be thread-safe. // One of the threads will not be able to insert (i.e., TryAdd will return false), but the code will happily execute // and fall through to the return statement. // This code makes no use of locking on the common path (i.e., reads of cachedStoreObjects). if (!cachedQueueObjects.ContainsKey(uniqueQueueIdentity)) { ServiceBusQueue serviceBusQueue = await ServiceBusQueue.Create(serviceBusConnectionString, queueName, this.batchIntervalMs); Queue queue = new Queue(serviceBusQueue); cachedQueueObjects.TryAdd(uniqueQueueIdentity, queue); } return(cachedQueueObjects[uniqueQueueIdentity]); }
/// <summary> /// Delete a queue message from the dead letter queue given its sequence number /// </summary> /// <param name="queueName">queue name</param> /// <param name="sbq">service bus queue</param> /// <param name="seqNum">sequence number</param> /// <returns>delete message task</returns> public async Task DeleteDeadLetterMessage(string queueName, ServiceBusQueue sbq, long seqNum) { var deadLetterMessageCount = await sbq.DeadLetterMessageCount(); var remaining = deadLetterMessageCount; bool deleted = false; while (remaining > 0 && deleted == false) { var msgList = await sbq.ReceiveDeadLetterBatchAsync((int)remaining); remaining -= msgList.Count; foreach (var msg in msgList) { if (msg.SequenceNumber == seqNum) { await sbq.CompleteAsync(msg); deleted = true; break; } else { await sbq.AbandonAsync(msg); } } } }
public async Task CreateDeleteQueue() { IgnoreTestInLiveMode(); //create queue string queueName = Recording.GenerateAssetName("queue"); ServiceBusQueue queue = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value; Assert.NotNull(queue); Assert.AreEqual(queue.Id.Name, queueName); //validate if created successfully queue = await _queueCollection.GetIfExistsAsync(queueName); Assert.NotNull(queue); Assert.IsTrue(await _queueCollection.ExistsAsync(queueName)); //delete queue await queue.DeleteAsync(WaitUntil.Completed); //validate queue = await _queueCollection.GetIfExistsAsync(queueName); Assert.Null(queue); Assert.IsFalse(await _queueCollection.ExistsAsync(queueName)); }
public async Task Create() { #region Snippet:Managing_ServiceBusQueues_CreateQueue string queueName = "myQueue"; ServiceBusQueue serviceBusQueue = (await serviceBusQueueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value; #endregion }
static void Main(string[] args) { IPublisher azureSBQPublisherPrimary = new ServiceBusQueue(connectionString, queueName); IPublisher azureSBQPublisherSecondary = new ServiceBusQueue(connectionString, secondaryQueueName); IPublisher publisher = null; Console.WriteLine("Select 1. for simple publisher, 2. for HA publisher"); string response = Console.ReadLine(); if (int.Parse(response) == 1) { publisher = new SimplePublisher(azureSBQPublisherPrimary); } else if (int.Parse(response) == 2) { publisher = new HAPublisher(azureSBQPublisherPrimary, azureSBQPublisherSecondary); } else { Logger.Log("Invalid choise", LoggerState.Failure); } Task.Run(() => SendRequestInLoop(publisher, 1)); Console.ReadKey(); }
/// <summary> /// Show the messages in a queue /// </summary> /// <param name="queueName">queue name</param> /// <param name="sbq">service bus queue</param> /// <returns>show messages task</returns> public async Task ShowMessages(string queueName, ServiceBusQueue sbq) { Console.WriteLine($"Messages in {queueName} queue:"); int messageCount = (int)await sbq.MessageCount(); Console.WriteLine($"Number of queued messages = {messageCount}"); var msgList = await sbq.PeekBatchAsync(messageCount); var remaining = messageCount - msgList.Count; // Because our queues are partitioned, peek will not see all messages // on the first attempt. So we call peek repeatedly until all messages are seen. while (remaining > 0) { var newMsgList = await sbq.PeekBatchAsync(remaining); if (newMsgList.Count == 0) { break; } remaining -= newMsgList.Count; foreach (var msg in newMsgList) { msgList.Add(msg); } } foreach (var msg in msgList) { Console.WriteLine($"Queue message: enqueued time = {msg.EnqueuedTime}, dequeue count = {msg.DequeueCount}"); this.ShowMessageContents(msg); } }
/// <summary> /// Initialization routine /// </summary> /// <param name="action">action</param> /// <returns>initialization task</returns> private async Task Initialize(Action action) { // load the environment configuration file from UtilsInternal var sr = new FileSettingsReader(ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + environmentName + ".config"); var certThumbprint = sr.ReadValue(SocialPlusCertThumbprint); var clientID = sr.ReadValue(EmbeddedSocialClientIdSetting); var storeLocation = StoreLocation.CurrentUser; var vaultUrl = sr.ReadValue(SocialPlusVaultUrlSetting); ICertificateHelper cert = new CertificateHelper(certThumbprint, clientID, storeLocation); IKeyVaultClient client = new AzureKeyVaultClient(cert); var log = new Log(LogDestination.Console, Log.DefaultCategoryName); var kv = new KV(log, clientID, vaultUrl, certThumbprint, storeLocation, client); var kvReader = new KVSettingsReader(sr, kv); IConnectionStringProvider connectionStringProvider = new ConnectionStringProvider(kvReader); int queueBatchIntervalMs = int.Parse(sr.ReadValue(ServiceBusBatchIntervalMsSetting)); QueueManager queueManager = new QueueManager(connectionStringProvider, queueBatchIntervalMs); var sbConnect = await connectionStringProvider.GetServiceBusConnectionString(ServiceBusInstanceType.Default); // the ListQueues action requires an instance of a ServiceBus object if (action == Action.ListQueues) { this.sb = new ServiceBus(sbConnect); } // all the remaining actions operate on an instance of a ServiceBusQueue object if (action != Action.ListQueues) { // ParseArgs() ensures that queueName is valid here this.sbQueue = await ServiceBusQueue.Create(sbConnect, queueName, queueBatchIntervalMs); this.selectedQueue = await queueManager.GetQueue((QueueIdentifier)selectedQueueId); } }
/// <summary> /// Show the message stats for a queue /// </summary> /// <param name="queueName">queue name</param> /// <param name="sbq">service bus queue</param> /// <returns>queue stats task</returns> public async Task QueueStats(string queueName, ServiceBusQueue sbq) { var messageCount = await sbq.MessageCount(); var deadLetterMessageCount = await sbq.DeadLetterMessageCount(); Console.WriteLine($"Number of messages in {queueName} queue: Active = {messageCount}, DeadLetter = {deadLetterMessageCount}"); }
public async Task Delete() { #region Snippet:Managing_ServiceBusQueues_DeleteQueue ServiceBusQueue serviceBusQueue = await serviceBusQueueCollection.GetAsync("myQueue"); await serviceBusQueue.DeleteAsync(WaitUntil.Completed); #endregion }
public async Task QueueCreateGetUpdateDeleteAuthorizationRule() { IgnoreTestInLiveMode(); //create queue string queueName = Recording.GenerateAssetName("queue"); ServiceBusQueue queue = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value; //create an authorization rule string ruleName = Recording.GenerateAssetName("authorizationrule"); NamespaceQueueAuthorizationRuleCollection ruleCollection = queue.GetNamespaceQueueAuthorizationRules(); ServiceBusAuthorizationRuleData parameter = new ServiceBusAuthorizationRuleData() { Rights = { AccessRights.Listen, AccessRights.Send } }; NamespaceQueueAuthorizationRule authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value; Assert.NotNull(authorizationRule); Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count); //get authorization rule authorizationRule = await ruleCollection.GetAsync(ruleName); Assert.AreEqual(authorizationRule.Id.Name, ruleName); Assert.NotNull(authorizationRule); Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count); //get all authorization rules List <NamespaceQueueAuthorizationRule> rules = await ruleCollection.GetAllAsync().ToEnumerableAsync(); //validate Assert.True(rules.Count == 1); bool isContainAuthorizationRuleName = false; foreach (NamespaceQueueAuthorizationRule rule in rules) { if (rule.Id.Name == ruleName) { isContainAuthorizationRuleName = true; } } Assert.True(isContainAuthorizationRuleName); //update authorization rule parameter.Rights.Add(AccessRights.Manage); authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value; Assert.NotNull(authorizationRule); Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count); //delete authorization rule await authorizationRule.DeleteAsync(WaitUntil.Completed); //validate if deleted Assert.IsFalse(await ruleCollection.ExistsAsync(ruleName)); rules = await ruleCollection.GetAllAsync().ToEnumerableAsync(); Assert.True(rules.Count == 0); }
public async Task SendMessage_Failure() { var queueClient = new Mock <IQueueClient>(); var service = new ServiceBusQueue(queueClient.Object); await Assert.ThrowsAnyAsync <Exception>(() => service.SendMessagesAsync(null, "testid")); queueClient.Verify(e => e.SendAsync(It.IsAny <Message>()), Times.Never); queueClient.Verify(e => e.CloseAsync(), Times.Never); }
public void TestNuGetMessaging() { var connectionString = TestUtilities.CreateUniqueDigits(); var queueName = TestUtilities.CreateUniqueDigits(); int batchIntervalInMs = 100; var sbQueue = new ServiceBusQueue(connectionString, queueName, batchIntervalInMs); // Check that the queue was initialized with the correct parameters Assert.AreEqual(connectionString, sbQueue.ConnectionString); Assert.AreEqual(queueName, sbQueue.QueueName); }
public ServiceBusQueueTests() { if (!Settings.Current.UseAzureServiceBus) return; _queue = new ServiceBusQueue<SimpleWorkItem>(Settings.Current.AzureServiceBusConnectionString, "test-_queue", workItemTimeoutMilliseconds: 1000, retries: 1, shouldRecreate: true, retryPolicy: new RetryExponential(TimeSpan.Zero, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(100), 1)); }
public async Task SendMessage_Success() { var queueClient = new Mock <IQueueClient>(); var service = new ServiceBusQueue(queueClient.Object); var task = service.SendMessagesAsync("Test", "testid"); await task.ConfigureAwait(false); task.IsCompletedSuccessfully.Should().BeTrue(); queueClient.Verify(e => e.SendAsync(It.IsAny <Message>()), Times.Exactly(1)); queueClient.Verify(e => e.CloseAsync(), Times.Exactly(1)); }
public ServiceBusQueueTests() { if (!Settings.Current.UseAzureServiceBus) { return; } _queue = new ServiceBusQueue <SimpleWorkItem>(Settings.Current.AzureServiceBusConnectionString, "test-_queue", workItemTimeoutMilliseconds: 1000, retries: 1, shouldRecreate: true, retryPolicy: new RetryExponential(TimeSpan.Zero, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(100), 1)); }
public async Task GetIfExist() { #region Snippet:Managing_ServiceBusQueues_GetQueueIfExists ServiceBusQueue serviceBusQueue = await serviceBusQueueCollection.GetIfExistsAsync("foo"); if (serviceBusQueue != null) { Console.WriteLine("queue 'foo' exists"); } if (await serviceBusQueueCollection.ExistsAsync("bar")) { Console.WriteLine("queue 'bar' exists"); } #endregion }
public async Task UpdateQueue() { IgnoreTestInLiveMode(); //create queue string queueName = Recording.GenerateAssetName("queue"); ServiceBusQueue queue = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value; Assert.NotNull(queue); Assert.AreEqual(queue.Id.Name, queueName); //update queue ServiceBusQueueData parameters = new ServiceBusQueueData() { MaxSizeInMegabytes = 1024 }; queue = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, parameters)).Value; Assert.AreEqual(queue.Data.MaxMessageSizeInKilobytes, 1024); }
public async Task QueueAuthorizationRuleRegenerateKey() { IgnoreTestInLiveMode(); //create queue string queueName = Recording.GenerateAssetName("queue"); ServiceBusQueue queue = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value; NamespaceQueueAuthorizationRuleCollection ruleCollection = queue.GetNamespaceQueueAuthorizationRules(); //create authorization rule string ruleName = Recording.GenerateAssetName("authorizationrule"); ServiceBusAuthorizationRuleData parameter = new ServiceBusAuthorizationRuleData() { Rights = { AccessRights.Listen, AccessRights.Send } }; NamespaceQueueAuthorizationRule authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value; Assert.NotNull(authorizationRule); Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count); AccessKeys keys1 = await authorizationRule.GetKeysAsync(); Assert.NotNull(keys1); Assert.NotNull(keys1.PrimaryConnectionString); Assert.NotNull(keys1.SecondaryConnectionString); AccessKeys keys2 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.PrimaryKey)); //the recordings are sanitized therefore cannot be compared if (Mode != RecordedTestMode.Playback) { Assert.AreNotEqual(keys1.PrimaryKey, keys2.PrimaryKey); Assert.AreEqual(keys1.SecondaryKey, keys2.SecondaryKey); } AccessKeys keys3 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.SecondaryKey)); if (Mode != RecordedTestMode.Playback) { Assert.AreEqual(keys2.PrimaryKey, keys3.PrimaryKey); Assert.AreNotEqual(keys2.SecondaryKey, keys3.SecondaryKey); } }
public async Task <IList <ServiceBusQueue> > GetQueues(string connectionString) { IList <ServiceBusQueue> queues = new List <ServiceBusQueue>(); var client = new ManagementClient(connectionString); var queuesInfo = await client.GetQueuesRuntimeInfoAsync(); await client.CloseAsync(); await Task.WhenAll(queuesInfo.Select(async queue => { var queueName = queue.Path; var newQueue = new ServiceBusQueue(queue) { Name = queueName }; queues.Add(newQueue); })); return(queues); }
/// <summary> /// Updates the queue description and makes a call to update /// corresponding DB entries. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856305.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ServiceBus.IQueueOperations. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queue'> /// The service bus queue. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> public static ServiceBusQueueResponse Update(this IQueueOperations operations, string namespaceName, ServiceBusQueue queue) { try { return(operations.UpdateAsync(namespaceName, queue).Result); } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } }
public ServiceBusProgram() { serviceBusQueue = new ServiceBusQueue(AppSettings.ServiceBusConnectionString, AppSettings.ServiceBusQueueName); serviceBusTopic = new ServiceBusTopic(AppSettings.ServiceBusConnectionString, AppSettings.ServiceBusTopicName, AppSettings.ServiceBusTopicSubscriptionName); }
/// <summary> /// Updates the queue description and makes a call to update /// corresponding DB entries. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856305.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ServiceBus.IQueueOperations. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='queue'> /// Required. The service bus queue. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> public static Task <ServiceBusQueueResponse> UpdateAsync(this IQueueOperations operations, string namespaceName, ServiceBusQueue queue) { return(operations.UpdateAsync(namespaceName, queue, CancellationToken.None)); }
/// <summary> /// Updates the queue description and makes a call to update /// corresponding DB entries. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856305.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ServiceBus.IQueueOperations. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='queue'> /// Required. The service bus queue. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> public static ServiceBusQueueResponse Update(this IQueueOperations operations, string namespaceName, ServiceBusQueue queue) { return(Task.Factory.StartNew((object s) => { return ((IQueueOperations)s).UpdateAsync(namespaceName, queue); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }