static void CreateTopicsAndSubscriptions(NamespaceManager namespaceManager) { Console.WriteLine("\nCreating a topic and 3 subscriptions."); // Create a topic and 3 subscriptions. TopicDescription topicDescription = namespaceManager.CreateTopic(Program.TopicName); Console.WriteLine("Topic created."); // Create a subscription for all messages sent to topic. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameAllMessages, new TrueFilter()); Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", Program.SubsNameAllMessages); // Create a subscription that'll receive all orders which have color "blue" and quantity 10. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameColorBlueSize10Orders, new SqlFilter("color = 'blue' AND quantity = 10")); Console.WriteLine("Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".", Program.SubsNameColorBlueSize10Orders); //var ruleDesc = new RuleDescription(); //ruleDesc.Filter = new CorrelationFilter("high"); //ruleDesc.Action = new SbAction(); // Create a subscription that'll receive all high priority orders. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameHighPriorityOrders, new CorrelationFilter("high")); Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", Program.SubsNameHighPriorityOrders); Console.WriteLine("Create completed."); }
public override bool OnStart() { ServicePointManager.DefaultConnectionLimit = 12; var connectionString = CloudConfigurationManager.GetSetting("topicConnectionString"); var topicName = CloudConfigurationManager.GetSetting("topicName"); _nsMgr = NamespaceManager.CreateFromConnectionString(connectionString); if (!_nsMgr.TopicExists(topicName)) { _nsMgr.CreateTopic(topicName); } if (!_nsMgr.SubscriptionExists(topicName, "audit")) { _nsMgr.CreateSubscription(topicName, "audit"); } _client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, "audit", ReceiveMode.ReceiveAndDelete); var result = base.OnStart(); Trace.TraceInformation("NTM.Auditing has been started"); return result; }
public async void Init(MessageReceived messageReceivedHandler) { this.random = new Random(); //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect; // Tcp mode does not work when I run in a VM (VirtualBox) and the host // is using a wireless connection. Hard coding to Http. ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http; string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); this.factory = MessagingFactory.CreateFromConnectionString(connectionString); this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists(topicName)) { namespaceManager.CreateTopic(topicName); } this.subscriptionName = Guid.NewGuid().ToString(); // Not needed really, it's a GUID... if (!namespaceManager.SubscriptionExists(topicName, subscriptionName)) { namespaceManager.CreateSubscription(topicName, subscriptionName); } this.topicClient = factory.CreateTopicClient(topicName); this.subClient = factory.CreateSubscriptionClient(topicName, subscriptionName); while (true) { await ReceiveMessageTaskAsync(messageReceivedHandler); } }
static void Main(string[] args) { GetUserCredentials(); TokenProvider tokenProvider = null; Uri serviceUri = null; CreateTokenProviderAndServiceUri(out tokenProvider, out serviceUri); NamespaceManager namespaceManager = new NamespaceManager(serviceUri, tokenProvider); Console.WriteLine("Creating Topic 'IssueTrackingTopic'..."); if (namespaceManager.TopicExists("IssueTrackingTopic")) namespaceManager.DeleteTopic("IssueTrackingTopic"); MessagingFactory factory = null; TopicDescription myTopic = namespaceManager.CreateTopic(TopicName); // Criar duas Subscrições Console.WriteLine("Creating Subscriptions 'AuditSubscription' and 'AgentSubscription'..."); SubscriptionDescription myAuditSubscription = namespaceManager.CreateSubscription((myTopic.Path, "AuditSubscription"); SubscriptionDescription myAgentSubscription = namespaceManager.CreateSubscription(myTopic.Path, "AgentSubscription"); TopicClient myTopicClient = CreateTopicClient(serviceUri, tokenProvider, myTopic, out factory); List<BrokeredMessage> messageList = new List<BrokeredMessage>(); messageList.Add(CreateIssueMessage("1", "First message information")); messageList.Add(CreateIssueMessage("2", "Second message information")); messageList.Add(CreateIssueMessage("3", "Third message information")); Console.WriteLine("\nSending messages to topic..."); SendListOfMessages(messageList, myTopicClient); Console.WriteLine("\nFinished sending messages, press ENTER to clean up and exit."); myTopicClient.Close(); Console.ReadLine(); namespaceManager.DeleteTopic(TopicName); }
static void Main(string[] args) { Console.Write("Enter some subscription name: "); string name = Console.ReadLine(); var serviceNamespace = "msswit2013relay"; var issuerName = "owner"; var issuerSecret = "IqyIwa7gNjBO89HT+3Vd1CcoBbyibvcv6Hd92J+FtPg="; Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty); TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret); NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider); if (!namespaceManager.TopicExists("MyTopic")) { namespaceManager.CreateTopic(new TopicDescription("MyTopic")); } Console.WriteLine("topic ready"); if (!namespaceManager.SubscriptionExists("MyTopic", "subscription-" + name)) { namespaceManager.CreateSubscription("MyTopic", "subscription-" + name); } Console.WriteLine("subscription ready"); MessagingFactory factory = MessagingFactory.Create(uri, tokenProvider); MessageReceiver receiver = factory.CreateMessageReceiver("MyTopic/subscriptions/subscription-" + name); while (true) { BrokeredMessage receivedMessage = receiver.Receive(); if (receivedMessage != null) { try { Console.WriteLine("label: {0}", receivedMessage.Label); Console.WriteLine("login: {0}", receivedMessage.Properties["login"]); Console.WriteLine("pass: {0}", receivedMessage.GetBody<ServiceBusTestMessage>().Password); receivedMessage.Complete(); } catch (Exception e) { receivedMessage.Abandon(); Console.WriteLine(e.Message); } } else { Thread.Sleep(new TimeSpan(0, 0, 10)); } } }
public given_a_topic_sender() { this.sut = new TestableTopicSender(this.Settings, this.Topic, new Incremental(1, TimeSpan.Zero, TimeSpan.Zero)); var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(this.Settings.TokenIssuer, this.Settings.TokenAccessKey); var serviceUri = ServiceBusEnvironment.CreateServiceUri(this.Settings.ServiceUriScheme, this.Settings.ServiceNamespace, this.Settings.ServicePath); var manager = new NamespaceManager(serviceUri, tokenProvider); manager.CreateSubscription(this.Topic, "Test"); var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider); this.subscriptionClient = messagingFactory.CreateSubscriptionClient(this.Topic, "Test"); }
public ServiceBusMessageBus(string connectionString, string topicName, ISerializer serializer = null) { _topicName = topicName; _serializer = serializer ?? new JsonNetSerializer(); _subscriptionName = "MessageBus"; _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!_namespaceManager.TopicExists(_topicName)) _namespaceManager.CreateTopic(_topicName); _topicClient = TopicClient.CreateFromConnectionString(connectionString, _topicName); if (!_namespaceManager.SubscriptionExists(_topicName, _subscriptionName)) _namespaceManager.CreateSubscription(_topicName, _subscriptionName); _subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, _topicName, _subscriptionName, ReceiveMode.ReceiveAndDelete); _subscriptionClient.OnMessageAsync(OnMessageAsync, new OnMessageOptions { AutoComplete = true }); }
/// <summary> /// Initializes a new instance of the <see cref="TopicSender"/> class, /// automatically creating the given topic if it does not exist. /// </summary> protected TopicSender(ServiceBusSettings settings, string topic, RetryStrategy retryStrategy) { this.settings = settings; this.topic = topic; this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey); this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath); // TODO: This could be injected. this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); this.retryPolicy.Retrying += (s, e) => { var handler = this.Retrying; if (handler != null) { handler(this, EventArgs.Empty); } Trace.TraceWarning("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount); }; var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider); this.topicClient = factory.CreateTopicClient(this.topic); var namespaceManager = new NamespaceManager(this.serviceUri, this.tokenProvider); foreach (var topicSettings in settings.Topics) { if (!namespaceManager.TopicExists(topicSettings.Path)) { namespaceManager.CreateTopic(topicSettings.Path); } foreach (var subscriptionSetting in topicSettings.Subscriptions) { if (!namespaceManager.SubscriptionExists(topicSettings.Path, subscriptionSetting.Name)) { namespaceManager.CreateSubscription(topicSettings.Path, subscriptionSetting.Name); } } } }
private void SetupAzureServiceBus() { Composable.GetExport<IXLogger>().Debug("Azure ServiceBus Scaling - INIT"); _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString); if (!_namespaceManager.TopicExists(TopicPath)) { Composable.GetExport<IXLogger>().Debug("Creating Topic for Azure Service Bus"); TopicDescription td = _namespaceManager.CreateTopic(TopicPath); } if (!_namespaceManager.SubscriptionExists(TopicPath, _sid)) { _namespaceManager.CreateSubscription(TopicPath, _sid); Composable.GetExport<IXLogger>().Debug("Creating Subscription for Azure Service Bus"); } _topicClient = TopicClient.CreateFromConnectionString(_connectionString, TopicPath); _subscriptionClient = SubscriptionClient.CreateFromConnectionString(_connectionString, TopicPath, _sid); }
public SubscriptionDescription CreateSubscription(SubscriptionDescription description, Filter filter) { return(namespaceManager.CreateSubscription(description, filter)); }
private void InitializeSubscriptionClient() { var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(OwnerIssuer, OwnerKey); var serviceUrl = ServiceBusEnvironment.CreateServiceUri("sb", ServiceBusNamespace, string.Empty); var namespaceManager = new NamespaceManager(serviceUrl, tokenProvider); Trace.WriteLine("Initializing Subscription...", "Info"); SubscriptionDescription subscriptionDescription = new SubscriptionDescription(SensorApiTopic, "TemperatureTap"); if (!namespaceManager.SubscriptionExists(SensorApiTopic, "TemperatureTap")) { namespaceManager.CreateSubscription(subscriptionDescription); } Trace.WriteLine("Initialized Subscription.", "Info"); Trace.WriteLine("Initializing SubscriptionClient...", "Info"); var messagingFactory = MessagingFactory.Create(serviceUrl, tokenProvider); _subscriptionClient = messagingFactory.CreateSubscriptionClient(SensorApiTopic, "TemperatureTap"); Trace.WriteLine("Initialized SubscriptionClient...", "Info"); }
static void CreateTopicsAndSubscriptions(NamespaceManager namespaceManager) { // Create a topic and 3 subscriptions. topicDescription = namespaceManager.CreateTopic(Conts.TopicName); try { namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubAllMessages); } catch { } try { namespaceManager.DeleteSubscription(topicDescription.Path, Conts.SubHolding); } catch { } try { namespaceManager.DeleteSubscription(topicDescription.Path, Conts.YoungHorses); } catch { } try { namespaceManager.DeleteSubscription(topicDescription.Path, Conts.OldHorses); } catch { } namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubAllMessages, new TrueFilter()); namespaceManager.CreateSubscription(topicDescription.Path, Conts.SubHolding, new FalseFilter()); //namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new TrueFilter()); //namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new TrueFilter()); namespaceManager.CreateSubscription(topicDescription.Path, Conts.YoungHorses, new SqlFilter("HorseId > 5")); namespaceManager.CreateSubscription(topicDescription.Path, Conts.OldHorses, new SqlFilter("HorseId <= 5")); }
/// <summary> /// Initializes a new instance of the <see cref="SubscriptionReceiver"/> class, /// automatically creating the topic and subscription if they don't exist. /// </summary> protected SubscriptionReceiver(ServiceBusSettings settings, string topic, string subscription, bool processInParallel, RetryStrategy backgroundRetryStrategy) { this.settings = settings; this.topic = topic; this.subscription = subscription; this.processInParallel = processInParallel; this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey); this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath); var messagingFactory = MessagingFactory.Create(this.serviceUri, tokenProvider); this.client = messagingFactory.CreateSubscriptionClient(topic, subscription); if (this.processInParallel) { this.client.PrefetchCount = 18; } else { this.client.PrefetchCount = 14; } this.dynamicThrottling = new DynamicThrottling( maxDegreeOfParallelism: 100, minDegreeOfParallelism: 50, penaltyAmount: 3, workFailedPenaltyAmount: 5, workCompletedParallelismGain: 1, intervalForRestoringDegreeOfParallelism: 8000); this.receiveRetryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(backgroundRetryStrategy); this.receiveRetryPolicy.Retrying += (s, e) => { this.dynamicThrottling.Penalize(); Trace.TraceWarning( "An error occurred in attempt number {1} to receive a message from subscription {2}: {0}", e.LastException.Message, e.CurrentRetryCount, this.subscription); }; var namespaceManager = new NamespaceManager(this.serviceUri, this.tokenProvider); if (!namespaceManager.SubscriptionExists(topic, subscription)) { namespaceManager.CreateSubscription(topic, subscription); } }
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."); }
private void CreateSubscriptionIfNotExists(NamespaceManager namespaceManager, TopicSettings topic, SubscriptionSettings subscription) { var subscriptionDescription = new SubscriptionDescription(topic.Path, subscription.Name) { RequiresSession = subscription.RequiresSession }; try { namespaceManager.CreateSubscription(subscriptionDescription); } catch (MessagingEntityAlreadyExistsException) { } }
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 void CreateSubscribtion(string topicName, string subscriptionName, string ruleName, Filter filter) { var rule = new RuleDescription(ruleName, filter); _namespaceManager.CreateSubscription(topicName, subscriptionName, rule); }