static async Task CreateSecondTopicInBundleForBackwardsCompatibilityTesting(NamespaceManager namespaceManager, string endpointName, string connectionString, string ruleForMyOtherEvent) { const string topicPath = "bundle-2"; if (!await namespaceManager.TopicExistsAsync(topicPath)) { await namespaceManager.CreateTopicAsync(topicPath); } var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicPath, endpointName); Task CreateRuleForMyEvent() => subscriptionClient.AddRuleAsync(MD5HashBuilder.Build(typeof(MyEvent).FullName.Replace("+", string.Empty)), new TrueFilter()); if (!await namespaceManager.SubscriptionExistsAsync(topicPath, endpointName)) { await namespaceManager.CreateSubscriptionAsync(topicPath, endpointName); await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName); await subscriptionClient.AddRuleAsync(ruleForMyOtherEvent, new TrueFilter()); await CreateRuleForMyEvent(); } else { await CreateRuleForMyEvent(); } }
public static async Task <TopicDescription> CreateTopicSafeAsync(this NamespaceManager namespaceManager, TopicDescription topicDescription) { var create = true; try { topicDescription = await namespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); create = false; } catch (MessagingEntityNotFoundException) { } if (create) { var created = false; try { if (_log.IsDebugEnabled) { _log.DebugFormat("Creating topic {0}", topicDescription.Path); } topicDescription = await namespaceManager.CreateTopicAsync(topicDescription).ConfigureAwait(false); created = true; } catch (MessagingEntityAlreadyExistsException) { } catch (MessagingException mex) { if (mex.Message.Contains("(409)")) { } else { throw; } } if (!created) { topicDescription = await namespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); } } if (_log.IsDebugEnabled) { _log.DebugFormat("Topic: {0} ({1})", topicDescription.Path, string.Join(", ", new[] { topicDescription.EnableExpress ? "express" : "", topicDescription.RequiresDuplicateDetection ? "dupe detect" : "" }.Where(x => !string.IsNullOrWhiteSpace(x)))); } return(topicDescription); }
private async static Task TopicCreateAsync(NamespaceManager ns, TopicDescription topicDescription) { if (!await ns.TopicExistsAsync(topicDescription.Path).ConfigureAwait(false)) { await ns.CreateTopicAsync(topicDescription).ConfigureAwait(false); ServiceBusEventSource.Log.CreatedTopic(ns.Address.ToString(), topicDescription.Path); } }
public async Task CreateTopicAsync(TopicDescription topicDescription) { var exists = await _namespaceManager.TopicExistsAsync(topicDescription.Path); if (!exists) { await _namespaceManager.CreateTopicAsync(topicDescription); } }
private async static Task TopicCreateAsync(NamespaceManager ns, TopicDescription topicDescription) { if (!await ns.TopicExistsAsync(topicDescription.Path)) { await ns.CreateTopicAsync(topicDescription); ServiceBusEventSource.Log.CreatedTopic(ns.Address.ToString(), topicDescription.Path); } }
public async Task <TopicDescription> CreateTopicAsync(string connectionString, string topic) { NamespaceManager namespaceManager = ServiceBusConnectionsFactory.GetNamespaceManager(connectionString); TopicDescription topicDescription = new TopicDescription(topic) { RequiresDuplicateDetection = true, DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 60, 0) }; return(await namespaceManager.CreateTopicAsync(topicDescription)); }
public async Task <TopicClient> CreateTopicClientAsync(string name) { var topicName = CreateTopicName(name); var td = new TopicDescription(topicName); if (!_manager.TopicExists(topicName)) { await _manager.CreateTopicAsync(td); } return(TopicClient.CreateFromConnectionString(_settings.AzureServiceBusConnectionString, topicName)); }
static async Task CreateTopic(NamespaceManager namespaceManager, string name) { if (name.Equals("bundle-3")) { await namespaceManager.DeleteTopicAsync(name); } if (!await namespaceManager.TopicExistsAsync(name)) { await namespaceManager.CreateTopicAsync(new TopicDescription(name)); } }
public async Task <TopicDescription> CreateTopic(TopicDescription topicDescription) { var create = true; try { topicDescription = await _namespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); create = false; } catch (MessagingEntityNotFoundException) { } if (create) { var created = false; try { LogContext.Debug?.Log("Creating topic {Topic}", topicDescription.Path); topicDescription = await _namespaceManager.CreateTopicAsync(topicDescription).ConfigureAwait(false); created = true; } catch (MessagingEntityAlreadyExistsException) { } catch (MessagingException mex) { if (mex.Message.Contains("(409)")) { } else { throw; } } if (!created) { topicDescription = await _namespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); } } LogContext.Debug?.Log("Topic: {Topic} ({Attributes})", topicDescription.Path, string.Join(", ", new[] { topicDescription.EnableExpress ? "express" : "", topicDescription.RequiresDuplicateDetection ? "dupe detect" : "" }.Where(x => !string.IsNullOrWhiteSpace(x)))); return(topicDescription); }
/// <summary> /// Create a Topic, if it does not already exist, and indicate if the attempt was successful. /// </summary> public bool CreateTopic() { string topicName = EnvironmentType.AzureTopicName(); bool topicExists = TopicExists; if (!topicExists) { _namespaceManager.CreateTopicAsync(topicName).Wait(); topicExists = TopicExists; } return(topicExists); }
public async Task <TopicDescription> Get <T>() { var topicName = string.Format("Topic_{0}", typeof(T).Name); var existsTask = _namespaceManager.TopicExistsAsync(topicName, null); var createTask = _namespaceManager.CreateTopicAsync(topicName, null); var getTask = _namespaceManager.GetTopicAsync(topicName, null); if (await existsTask) { return(await getTask); } return(await createTask); }
public static async Task <TopicDescription> EnsureTopicExistAsync(this NamespaceManager ns, string topicName) { try { return(await ns.GetTopicAsync(topicName).ConfigureAwait(false)); } catch (MessagingEntityNotFoundException) { } return(await ns.CreateTopicAsync(new TopicDescription(topicName) { DefaultMessageTimeToLive = TimeSpan.FromMinutes(5), AutoDeleteOnIdle = TimeSpan.FromMinutes(5) }).ConfigureAwait(false)); }
public static async Task CreateTopicIfNotExistsAsync(this NamespaceManager manager, string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!await manager.TopicExistsAsync(path)) { try { cancellationToken.ThrowIfCancellationRequested(); await manager.CreateTopicAsync(path); } catch (MessagingEntityAlreadyExistsException) { } } }
private async Task EnsureReceiverExists(string path, string subscription, string filter = null) { Trace(); try { switch (string.IsNullOrEmpty(subscription)) { case true: if (!await NamespaceManager.QueueExistsAsync(path)) { await NamespaceManager.CreateQueueAsync(path); } QueueReceiver = MessagingFactory.CreateQueueClient(path, ReceiveMode.ReceiveAndDelete); break; case false: if (!await NamespaceManager.TopicExistsAsync(path)) { await NamespaceManager.CreateTopicAsync(path); } //recreate subscription if necessary if (await NamespaceManager.SubscriptionExistsAsync(path, subscription)) { await NamespaceManager.DeleteSubscriptionAsync(path, subscription); } if (!await NamespaceManager.SubscriptionExistsAsync(path, subscription)) { if (!string.IsNullOrEmpty(filter)) { SqlFilter sf = new SqlFilter(filter); await NamespaceManager.CreateSubscriptionAsync(path, subscription, sf); } else { await NamespaceManager.CreateSubscriptionAsync(path, subscription); } } TopicReceiver = MessagingFactory.CreateSubscriptionClient(path, subscription, ReceiveMode.ReceiveAndDelete); break; } } catch (Exception e) { Error(e.ToString()); } }
public async Task <ActionResult> Index(VideoModel model) { if (!ModelState.IsValid) { return(View(model)); } var cloudStorageAccount = CloudStorageAccount.Parse(_azureStorageConnectionString); var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); var container = cloudBlobClient.GetContainerReference("uploads"); await container.CreateIfNotExistsAsync(); var blob = container.GetBlockBlobReference(System.IO.Path.GetFileName(model.File.FileName)); await blob.UploadFromStreamAsync(model.File.InputStream); var newVideo = new BackOffice.Common.Video { Description = model.Description, Id = model.Id, OriginalUrl = blob.Uri.ToString(), Title = model.Name, UploadedDate = DateTime.UtcNow }; NamespaceManager nsMgr = NamespaceManager.CreateFromConnectionString(_azureServiceBusConnectionString); TopicDescription topic = null; if (!(await nsMgr.TopicExistsAsync("NewMediaUploaded"))) { topic = await nsMgr.CreateTopicAsync("NewMediaUploaded"); } else { topic = await nsMgr.GetTopicAsync("NewMediaUploaded"); } MessagingFactory factory = MessagingFactory.CreateFromConnectionString(_azureServiceBusConnectionString); TopicClient topicClient = factory.CreateTopicClient(topic.Path); await topicClient.SendAsync(new BrokeredMessage(newVideo)); return(RedirectToAction("Index", "Home")); }
public Task CreateQueueAsync(QueueName name) { if (name.IsSimpleQueue) { return(_namespaceManager.CreateQueueAsync(name.TopicName)); } else { if (name.IsTopic) { return(_namespaceManager.CreateTopicAsync(name.TopicName)); } else { return(_namespaceManager.CreateSubscriptionAsync(name.TopicName, name.SubscriptionName)); } } }
private void CreateTopicTransient(string name) { if (NamespaceManager.TopicExists(name)) { return; } try { // Configure Topic Settings var qd = new TopicDescription(name); RetryPolicy.ExecuteAsync(async() => await NamespaceManager.CreateTopicAsync(qd)); } catch (Exception) { if (NamespaceManager.TopicExists(name)) { return; } throw; } }
public async Task Setup() { namespaceConnectionString = Environment.GetEnvironmentVariable("NServiceBus.AzureServiceBusForwarder.ConnectionString", EnvironmentVariableTarget.Process); destinationQueue = GetType().Name; messageForwarder = A.Fake<IMessageForwarder>(); messageReceiver = new QueueBatchMessageReceiver(QueueClient.CreateFromConnectionString(namespaceConnectionString, destinationQueue)); await MessageEntityHelper.CreateQueue(destinationQueue); namespaceManager = NamespaceManager.CreateFromConnectionString(namespaceConnectionString); if (await namespaceManager.TopicExistsAsync(TopicName)) { await namespaceManager.DeleteTopicAsync(TopicName); } await namespaceManager.CreateTopicAsync(TopicName); forwarder = new Forwarder( new ForwarderConfiguration( new ForwarderSourceConfiguration(500, () => messageReceiver), new ForwarderDestinationConfiguration(destinationQueue, () => messageForwarder))); }
private async Task EnsureTopics() { var checks = ShipHubTopicNames.AllTopics .Select(x => new { TopicName = x, ExistsTask = NamespaceManager.TopicExistsAsync(x) }) .ToArray(); await Task.WhenAll(checks.Select(x => x.ExistsTask)); // Ensure AutoDeleteOnIdle IS NOT SET on the topic. Only subscriptions should delete. var creations = checks .Where(x => !x.ExistsTask.Result) .Select(x => NamespaceManager.CreateTopicAsync(new TopicDescription(x.TopicName) { DefaultMessageTimeToLive = DefaultTimeToLive, EnableExpress = true, EnableBatchedOperations = true, EnablePartitioning = true, IsAnonymousAccessible = false, MaxSizeInMegabytes = 5120, })); await Task.WhenAll(creations); }
protected override async Task EnsureTopicCreatedAsync(CancellationToken cancellationToken) { if (TopicIsCreated) { return; } using (await _lock.LockAsync().AnyContext()) { if (TopicIsCreated) { return; } var sw = Stopwatch.StartNew(); try { await _namespaceManager.CreateTopicAsync(CreateTopicDescription()).AnyContext(); } catch (MessagingEntityAlreadyExistsException) { } _topicClient = TopicClient.CreateFromConnectionString(_options.ConnectionString, _options.Topic); sw.Stop(); _logger.LogTrace("Ensure topic exists took {0}ms.", sw.ElapsedMilliseconds); } }
private static async void OnJobStateChanged(object sender, Microsoft.WindowsAzure.MediaServices.Client.JobStateChangedEventArgs e) { NamespaceManager nsMgr = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString); TopicDescription topic = null; if (!(await nsMgr.TopicExistsAsync("MediaJobStateChanged"))) { topic = await nsMgr.CreateTopicAsync("MediaJobStateChanged"); } else { topic = await nsMgr.GetTopicAsync("MediaJobStateChanged"); } MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString); TopicClient topicClient = factory.CreateTopicClient(topic.Path); var job = ((IJob)sender); Common.AdaptiveStreamingInfo streamingInfo = null; if (job.State == JobState.Finished) { var mediaServicesWrapper = new MediaServicesWrapper(MediaServiceName, MediaServiceKey, StorageConnectionString); streamingInfo = await mediaServicesWrapper.PrepareAssetsForAdaptiveStreamingAsync(job.Id); } var jobStateChangedMessage = new Common.JobStateChangedMessage { JobId = job.Id, NewState = e.CurrentState.ToString(), OldState = e.PreviousState.ToString(), StreamingInfo = streamingInfo }; await topicClient.SendAsync(new BrokeredMessage(jobStateChangedMessage)); }
public async Task<IEnumerable<string>> Post() { var namespaceManager = new NamespaceManager(_address, _settings.TokenProvider); if (!await namespaceManager.TopicExistsAsync(TopicName)) { var topicDescription = new TopicDescription(TopicName); var subscriptionDescription = new SubscriptionDescription(TopicName, SubscriptionName); topicDescription.EnablePartitioning = true; topicDescription.EnableBatchedOperations = false; subscriptionDescription.EnableBatchedOperations = false; await namespaceManager.CreateTopicAsync(topicDescription); await namespaceManager.CreateSubscriptionAsync(subscriptionDescription); } var messagingFactory = MessagingFactory.Create(_address, _settings); var client = messagingFactory.CreateTopicClient(TopicName); IEnumerable<string> result = ProcessPost(client); Task clientTask = client.CloseAsync(); Task factoryTask = messagingFactory.CloseAsync(); await Task.WhenAll(clientTask, factoryTask); return result; }
public Task <TopicDescription> CreateTopic(TopicDescription topicDescription) { return(manager.CreateTopicAsync(topicDescription)); }
public async Task Run(string namespaceAddress, string manageToken) { Console.WriteLine("\nCreating topology\n"); this.sharedAccessRuleKey = SharedAccessAuthorizationRule.GenerateRandomKey(); var namespaceManageTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken); // Create namespace manager and create destination queue with a SAS rule that allows sending to that queue. var namespaceManager = new NamespaceManager(namespaceAddress, namespaceManageTokenProvider); var targetQueue = new QueueDescription("TargetQueue") { Authorization = { new SharedAccessAuthorizationRule("SendKey", this.sharedAccessRuleKey, new[] { AccessRights.Send }) }, }; targetQueue = (await namespaceManager.QueueExistsAsync(targetQueue.Path)) ? await namespaceManager.UpdateQueueAsync(targetQueue) : await namespaceManager.CreateQueueAsync(targetQueue); var topic = new TopicDescription("SourceTopic") { Authorization = { new SharedAccessAuthorizationRule("SendKey", this.sharedAccessRuleKey, new[] { AccessRights.Send }) } }; topic = (await namespaceManager.TopicExistsAsync(topic.Path)) ? await namespaceManager.UpdateTopicAsync(topic) : await namespaceManager.CreateTopicAsync(topic); var forwardingSubscription = namespaceManager.CreateSubscription( new SubscriptionDescription(topic.Path, "Sub1") { ForwardTo = targetQueue.Path }); var forwardingQueue = new QueueDescription("SourceQueue") { ForwardTo = targetQueue.Path, Authorization = { new SharedAccessAuthorizationRule( "SendKey", this.sharedAccessRuleKey, new[] { AccessRights.Send }) } }; forwardingQueue = (await namespaceManager.QueueExistsAsync(forwardingQueue.Path)) ? await namespaceManager.UpdateQueueAsync(forwardingQueue) : await namespaceManager.CreateQueueAsync(forwardingQueue); Console.WriteLine("\nSending messages\n"); var topicFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedAccessSignatureTokenProvider("SendKey", this.sharedAccessRuleKey)); var topicSender = await topicFactory.CreateMessageSenderAsync(topic.Path); await topicSender.SendAsync(CreateMessage("M1")); var queueFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedAccessSignatureTokenProvider("SendKey", this.sharedAccessRuleKey)); var queueSender = await queueFactory.CreateMessageSenderAsync(forwardingQueue.Path); await queueSender.SendAsync(CreateMessage("M1")); var messagingFactory = MessagingFactory.Create(namespaceAddress, namespaceManageTokenProvider); var targetQueueReceiver = messagingFactory.CreateQueueClient(targetQueue.Path); while (true) { var message = await targetQueueReceiver.ReceiveAsync(TimeSpan.FromSeconds(10)); if (message != null) { await this.PrintReceivedMessage(message); await message.CompleteAsync(); } else { break; } } await targetQueueReceiver.CloseAsync(); Console.WriteLine("\nPress ENTER to delete topics and exit\n"); Console.ReadLine(); messagingFactory.Close(); Task.WaitAll( namespaceManager.DeleteQueueAsync(targetQueue.Path), namespaceManager.DeleteQueueAsync(forwardingQueue.Path), namespaceManager.DeleteTopicAsync(topic.Path)); }
public async Task Run(string namespaceAddress, string manageToken) { Console.WriteLine("\nCreating topology\n"); this.sharedAccessRuleKey = SharedAccessAuthorizationRule.GenerateRandomKey(); var namespaceManageTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken); // Create namespace manager and create destination queue with a SAS rule that allows sending to that queue. var namespaceManager = new NamespaceManager(namespaceAddress, namespaceManageTokenProvider); var targetQueue = new QueueDescription("TargetQueue") { Authorization = { new SharedAccessAuthorizationRule("SendKey", this.sharedAccessRuleKey, new[] { AccessRights.Send }) }, }; targetQueue = (await namespaceManager.QueueExistsAsync(targetQueue.Path)) ? await namespaceManager.UpdateQueueAsync(targetQueue) : await namespaceManager.CreateQueueAsync(targetQueue); var topic = new TopicDescription("SourceTopic") { Authorization = { new SharedAccessAuthorizationRule("SendKey", this.sharedAccessRuleKey, new[] { AccessRights.Send }) } }; topic = (await namespaceManager.TopicExistsAsync(topic.Path)) ? await namespaceManager.UpdateTopicAsync(topic) : await namespaceManager.CreateTopicAsync(topic); var forwardingSubscription = namespaceManager.CreateSubscription( new SubscriptionDescription(topic.Path, "Sub1") { ForwardTo = targetQueue.Path }); var forwardingQueue = new QueueDescription("SourceQueue") { ForwardTo = targetQueue.Path, Authorization = { new SharedAccessAuthorizationRule( "SendKey", this.sharedAccessRuleKey, new[] {AccessRights.Send}) } }; forwardingQueue = (await namespaceManager.QueueExistsAsync(forwardingQueue.Path)) ? await namespaceManager.UpdateQueueAsync(forwardingQueue) : await namespaceManager.CreateQueueAsync(forwardingQueue); Console.WriteLine("\nSending messages\n"); var topicFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedAccessSignatureTokenProvider("SendKey", this.sharedAccessRuleKey)); var topicSender = await topicFactory.CreateMessageSenderAsync(topic.Path); await topicSender.SendAsync(CreateMessage("M1")); var queueFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedAccessSignatureTokenProvider("SendKey", this.sharedAccessRuleKey)); var queueSender = await queueFactory.CreateMessageSenderAsync(forwardingQueue.Path); await queueSender.SendAsync(CreateMessage("M1")); var messagingFactory = MessagingFactory.Create(namespaceAddress, namespaceManageTokenProvider); var targetQueueReceiver = messagingFactory.CreateQueueClient(targetQueue.Path); while (true) { var message = await targetQueueReceiver.ReceiveAsync(TimeSpan.FromSeconds(10)); if (message != null) { await this.PrintReceivedMessage(message); await message.CompleteAsync(); } else { break; } } await targetQueueReceiver.CloseAsync(); Console.WriteLine("\nPress ENTER to delete topics and exit\n"); Console.ReadLine(); messagingFactory.Close(); Task.WaitAll( namespaceManager.DeleteQueueAsync(targetQueue.Path), namespaceManager.DeleteQueueAsync(forwardingQueue.Path), namespaceManager.DeleteTopicAsync(topic.Path)); }
public static async Task SendAndCreateEntityIfNotExists(this MessageSender sender, BrokeredMessage message, Guid functionInstanceId, NamespaceManager namespaceManager, AccessRights accessRights, EntityType entityType, CancellationToken cancellationToken) { if (sender == null) { throw new ArgumentNullException("sender"); } else if (namespaceManager == null) { throw new ArgumentNullException("namespaceManager"); } ServiceBusCausalityHelper.EncodePayload(functionInstanceId, message); bool threwMessgingEntityNotFoundException = false; cancellationToken.ThrowIfCancellationRequested(); try { await sender.SendAsync(message); return; } catch (MessagingEntityNotFoundException) { if (accessRights != AccessRights.Manage) { // if we don't have the required rights to create the entity // rethrow the exception throw; } threwMessgingEntityNotFoundException = true; } Debug.Assert(threwMessgingEntityNotFoundException); cancellationToken.ThrowIfCancellationRequested(); try { switch (entityType) { case EntityType.Topic: await namespaceManager.CreateTopicAsync(sender.Path); break; case EntityType.Queue: default: await namespaceManager.CreateQueueAsync(sender.Path); break; } } catch (MessagingEntityAlreadyExistsException) { } // Clone the message because it was already consumed before (when trying to send) // otherwise, you get an exception message = message.Clone(); cancellationToken.ThrowIfCancellationRequested(); await sender.SendAsync(message); }
public async Task Run(string namespaceAddress, string manageToken) { // Create the Topic / Subscription entities var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken); var namespaceManager = new NamespaceManager(namespaceAddress, tokenProvider); var topicDescription = new TopicDescription(TopicName); // Delete the topic if it already exists before creation. if (await namespaceManager.TopicExistsAsync(topicDescription.Path)) { await namespaceManager.DeleteTopicAsync(topicDescription.Path); } await namespaceManager.CreateTopicAsync(topicDescription); await Task.WhenAll( // this sub receives messages for Priority = 1 namespaceManager.CreateSubscriptionAsync( new SubscriptionDescription(TopicName, "Priority1Subscription"), new RuleDescription(new SqlFilter("Priority = 1"))), // this sub receives messages for Priority = 2 namespaceManager.CreateSubscriptionAsync( new SubscriptionDescription(TopicName, "Priority2Subscription"), new RuleDescription(new SqlFilter("Priority = 2"))), // this sub receives messages for Priority Less than 2 namespaceManager.CreateSubscriptionAsync( new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription"), new RuleDescription(new SqlFilter("Priority > 2"))) ); // Start senders and receivers: Console.WriteLine("\nLaunching senders and receivers..."); //send messages to topic var messagingFactory = MessagingFactory.Create(namespaceAddress, tokenProvider); var topicClient = messagingFactory.CreateTopicClient(TopicName); Console.WriteLine("Preparing to send messages to {0}...", topicClient.Path); // Send messages to queue: Console.WriteLine("Sending messages to topic {0}", topicClient.Path); var rand = new Random(); for (var i = 0; i < 100; ++i) { var msg = new BrokeredMessage() { TimeToLive = TimeSpan.FromMinutes(2), Properties = { { "Priority", rand.Next(1, 4) } } }; await topicClient.SendAsync(msg); this.OutputMessageInfo("Sent: ", msg); } Console.WriteLine(); // All messages sent Console.WriteLine("\nSender complete. Press ENTER"); Console.ReadLine(); // start receive Console.WriteLine("Receiving messages by priority ..."); var subClient1 = messagingFactory.CreateSubscriptionClient( TopicName, new SubscriptionDescription(TopicName, "Priority1Subscription").Name, ReceiveMode.ReceiveAndDelete); var subClient2 = messagingFactory.CreateSubscriptionClient( TopicName, new SubscriptionDescription(TopicName, "Priority2Subscription").Name, ReceiveMode.ReceiveAndDelete); var subClient3 = messagingFactory.CreateSubscriptionClient( TopicName, new SubscriptionDescription(TopicName, "PriorityLessThan2Subscription").Name, ReceiveMode.ReceiveAndDelete); while (true) { try { // Please see the README.md file regarding this loop and // the handling strategy below. var message = await subClient1.ReceiveAsync(TimeSpan.Zero) ?? (await subClient2.ReceiveAsync(TimeSpan.Zero) ?? await subClient3.ReceiveAsync(TimeSpan.Zero)); if (message != null) { this.OutputMessageInfo("Received: ", message); } else { break; } } catch (MessageNotFoundException) { Console.WriteLine("Got MessageNotFoundException, waiting for messages to be available"); } catch (MessagingException e) { Console.WriteLine("Error: " + e.Message); } } Console.WriteLine("\nReceiver complete. press ENTER"); Console.ReadLine(); // Cleanup: namespaceManager.DeleteTopic(TopicName); }
public async Task Run(string namespaceAddress, string manageToken) { // This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions. // The sample creates a topic and 3 subscriptions with different filter definitions. // Each receiver will receive matching messages depending on the filter associated with a subscription. // NOTE: // This is primarily an example illustrating the management features related to setting up // Service Bus subscriptions. It is DISCOURAGED for applications to routinely set up and // tear down topics and subscriptions as a part of regular message processing. Managing // topics and subscriptions is a system configuration operation. // Create messaging factory and ServiceBus namespace client. var sharedAccessSignatureTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken); var namespaceManager = new NamespaceManager(namespaceAddress, sharedAccessSignatureTokenProvider); Console.WriteLine("\nCreating a topic and 3 subscriptions."); // Create a topic and several subscriptions; clean house ahead of time if (await namespaceManager.TopicExistsAsync(TopicName)) { await namespaceManager.DeleteTopicAsync(TopicName); } var topicDescription = await namespaceManager.CreateTopicAsync(TopicName); Console.WriteLine("Topic created."); // Create a subscription for all messages sent to topic. await namespaceManager.CreateSubscriptionAsync(topicDescription.Path, SubscriptionAllMessages, new TrueFilter()); Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", SubscriptionAllMessages); // Create a subscription that'll receive all orders which have color "blue" and quantity 10. await namespaceManager.CreateSubscriptionAsync( topicDescription.Path, SubscriptionColorBlueSize10Orders, new SqlFilter("color = 'blue' AND quantity = 10")); Console.WriteLine( "Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".", SubscriptionColorBlueSize10Orders); // Create a subscription that'll receive all orders which have color "red" await namespaceManager.CreateSubscriptionAsync( topicDescription.Path, SubscriptionColorRed, new RuleDescription { Name = "RedRule", Filter = new SqlFilter("color = 'red'"), Action = new SqlRuleAction( "SET quantity = quantity / 2;" + "REMOVE priority;" + "SET sys.CorrelationId = 'low';") }); Console.WriteLine("Subscription {0} added with filter definition \"color = 'red'\" and action definition.", SubscriptionColorRed); // Create a subscription that'll receive all high priority orders. namespaceManager.CreateSubscription(topicDescription.Path, SubscriptionHighPriorityOrders, new CorrelationFilter { Label = "red", CorrelationId = "high" }); Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", SubscriptionHighPriorityOrders); Console.WriteLine("Create completed."); await this.SendAndReceiveTestsAsync(namespaceAddress, sharedAccessSignatureTokenProvider); Console.WriteLine("Press [Enter] to quit..."); Console.ReadLine(); Console.WriteLine("\nDeleting topic and subscriptions from previous run if any."); try { namespaceManager.DeleteTopic(TopicName); } catch (MessagingEntityNotFoundException) { Console.WriteLine("No topic found to delete."); } Console.WriteLine("Delete completed."); }
public async Task Run(string namespaceAddress, string manageToken) { // This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions. // The sample creates a topic and 3 subscriptions with different filter definitions. // Each receiver will receive matching messages depending on the filter associated with a subscription. // NOTE: // This is primarily an example illustrating the management features related to setting up // Service Bus subscriptions. It is DISCOURAGED for applications to routinely set up and // tear down topics and subscriptions as a part of regular message processing. Managing // topics and subscriptions is a system configuration operation. // Create messaging factory and ServiceBus namespace client. var sharedAccessSignatureTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(manageToken); var namespaceManager = new NamespaceManager(namespaceAddress, sharedAccessSignatureTokenProvider); Console.WriteLine("\nCreating a topic and 3 subscriptions."); // Create a topic and several subscriptions; clean house ahead of time if (await namespaceManager.TopicExistsAsync(TopicName)) { await namespaceManager.DeleteTopicAsync(TopicName); } var topicDescription = await namespaceManager.CreateTopicAsync(TopicName); Console.WriteLine("Topic created."); // Create a subscription for all messages sent to topic. await namespaceManager.CreateSubscriptionAsync(topicDescription.Path, SubscriptionAllMessages, new TrueFilter()); Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", SubscriptionAllMessages); // Create a subscription that'll receive all orders which have color "blue" and quantity 10. await namespaceManager.CreateSubscriptionAsync( topicDescription.Path, SubscriptionColorBlueSize10Orders, new SqlFilter("color = 'blue' AND quantity = 10")); Console.WriteLine( "Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".", SubscriptionColorBlueSize10Orders); // Create a subscription that'll receive all orders which have color "red" await namespaceManager.CreateSubscriptionAsync( topicDescription.Path, SubscriptionColorRed, new RuleDescription { Name = "RedRule", Filter = new SqlFilter("color = 'red'"), Action = new SqlRuleAction( "SET quantity = quantity / 2;" + "REMOVE priority;" + "SET sys.CorrelationId = 'low';") }); Console.WriteLine("Subscription {0} added with filter definition \"color = 'red'\" and action definition.", SubscriptionColorRed); // Create a subscription that'll receive all high priority orders. namespaceManager.CreateSubscription(topicDescription.Path, SubscriptionHighPriorityOrders, new CorrelationFilter { Label = "red", CorrelationId = "high"}); Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", SubscriptionHighPriorityOrders); Console.WriteLine("Create completed."); await this.SendAndReceiveTestsAsync(namespaceAddress, sharedAccessSignatureTokenProvider); Console.WriteLine("Press [Enter] to quit..."); Console.ReadLine(); Console.WriteLine("\nDeleting topic and subscriptions from previous run if any."); try { namespaceManager.DeleteTopic(TopicName); } catch (MessagingEntityNotFoundException) { Console.WriteLine("No topic found to delete."); } Console.WriteLine("Delete completed."); }