static void Receive(MessagingFactory factory) { SubscriptionClient agentSubscriptionClient = factory.CreateSubscriptionClient(Program.IssueTrackingTopic, Program.AgentSubscription, ReceiveMode.PeekLock); SubscriptionClient auditSubscriptionClient = factory.CreateSubscriptionClient(Program.IssueTrackingTopic, Program.AuditSubscription, ReceiveMode.ReceiveAndDelete); //***************************************************************************************************** // Receiving messages from a Subscription //***************************************************************************************************** BrokeredMessage message; Console.WriteLine("\nReceiving message from AgentSubscription..."); while ((message = agentSubscriptionClient.Receive(TimeSpan.FromSeconds(5))) != null) { Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>())); // Further custom message processing could go here... message.Complete(); } // Create a receiver using ReceiveAndDelete mode Console.WriteLine("\nReceiving message from AuditSubscription..."); while ((message = auditSubscriptionClient.Receive(TimeSpan.FromSeconds(5))) != null) { Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>())); // Further custom message processing could go here... } }
public Subscription(int num) { _subscriptionName = $"subscription{num}"; // Create namespace client NamespaceManager namespaceClient = NamespaceManager.CreateFromConnectionString(_connectionString); SubscriptionDescription subscriptionDescription = null; foreach (var item in namespaceClient.GetSubscriptions(_topicPath)) { if (item.Name == _subscriptionName) { subscriptionDescription = item; break; } } if (subscriptionDescription == null) { subscriptionDescription = namespaceClient.CreateSubscription(_topicPath, _subscriptionName); } MessagingFactory factory = MessagingFactory.CreateFromConnectionString(_connectionString); _client = factory.CreateSubscriptionClient(_topicPath, _subscriptionName, ReceiveMode.PeekLock); //_client = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicPath, _subscriptionName, ReceiveMode.PeekLock); }
// Delete the first published message from service bus subscription public void RemoveFirstPublishedMessage(string ServiceBusConnectionString, string TopicName, string SubscriptionName) { // Create service Bus namespace manager var namespaceManager = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString); // Get subscrition information of the topic var subscriptionDesc = namespaceManager.GetSubscription(TopicName, SubscriptionName); // Check number of published messages long messageCount = subscriptionDesc.MessageCount; // Skip removing message if none exists if (messageCount != 0) { // Create service bus messageing factory Factory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString); // Create subscription client for the topic SubscriptionClient mySubscriptionClient = Factory.CreateSubscriptionClient(TopicName, SubscriptionName); // Get first broker message from the subscription. // Use Receive function BrokeredMessage MessageReceived = mySubscriptionClient.Receive(); // Use lock token of the received brokered message to mark the message is completed. // The message will be removed from the subscription mySubscriptionClient.Complete(MessageReceived.LockToken); //Clean up MessageReceived.Dispose(); mySubscriptionClient.Close(); } }
private static void TopicReceive(int subscription) { var topicName = "topicdemo"; var subToProcess = "Subscription" + subscription; var connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=Receiver;SharedAccessKey=Vqa3SwP4qH5/+8ikB4B/BNMPQCRDuV/AiUYsUofWebo=;TransportType=Amqp"; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection); SubscriptionClient clientA = factory.CreateSubscriptionClient(topicName, subToProcess); while (true) { BrokeredMessage message = clientA.Receive(); if (message != null) { try { Console.WriteLine("MessageId:{0}", message.MessageId); Console.WriteLine(message.GetBody <string>()); message.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); message.Abandon(); } } } }
//public async Task Receive() //{ // string subscriptionName = Guid.NewGuid().ToString("N"); // MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]); // // Create subscription // SubscriptionDescription description = new SubscriptionDescription(Helpers.BasicTopicName, subscriptionName) // { // AutoDeleteOnIdle = TimeSpan.FromMinutes(5) // }; // NamespaceManager manager = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]); // SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(Helpers.BasicTopicName, subscriptionName); // await manager.CreateSubscriptionAsync(description); // // Receive message // BrokeredMessage message = await subscriptionClient.ReceiveAsync(); // await Helpers.PrintMessageInfo(message); //} public async Task Receive() { string subscriptionName = Guid.NewGuid().ToString("N"); MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]); // Create subscription SubscriptionDescription description = new SubscriptionDescription(Helpers.BasicTopicName, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromMinutes(25) }; NamespaceManager manager = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]); if (!manager.SubscriptionExists(Helpers.BasicTopicName, subscriptionName)) { await manager.CreateSubscriptionAsync(description); } // Receive messagea. var tcs = new TaskCompletionSource <bool>(); SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(Helpers.BasicTopicName, subscriptionName); subscriptionClient.OnMessageAsync(async message => { await Helpers.PrintMessageInfo(message); }); await Task.Delay(TimeSpan.FromMinutes(1)); tcs.SetResult(true); await tcs.Task; }
public ServiceBus Subscribe <T>(Action <T> receiveHandler) { SetupServiceBusEnvironment(); var topicName = string.Format("Topic_{0}", typeof(T).Name); var subscriptionName = string.Format("Subscription_{0}", typeof(T).Name); if (!_namespaceManager.TopicExists(topicName)) { _namespaceManager.CreateTopic(topicName); } var topic = _namespaceManager.GetTopic(topicName); SubscriptionDescription subscription; if (!_namespaceManager.SubscriptionExists(topic.Path, subscriptionName)) { subscription = _namespaceManager.CreateSubscription(topic.Path, subscriptionName); } else { subscription = _namespaceManager.GetSubscription(topic.Path, subscriptionName); } var subscriptionClient = _messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, ReceiveMode.ReceiveAndDelete); _subscribers.Add(new Tuple <string, SubscriptionClient>(topicName, subscriptionClient)); Begin <T>(receiveHandler, subscriptionClient); return(this); }
private void createSubscriptionTimer_Tick(object sender, EventArgs e) { if (_namespaceManager.TopicExists(TopicName)) { //Stop trying to create the subscription createSubscriptionTimer.Stop(); //Create the subscription if it doesn't exist if (!_namespaceManager.SubscriptionExists(TopicName, SubscriptionName)) { var subscription = new SubscriptionDescription(TopicName, SubscriptionName) { RequiresSession = true }; _namespaceManager.CreateSubscription(subscription); } // Create the subscription client _subscriptionClient = _messagingFactory.CreateSubscriptionClient(TopicName, SubscriptionName, ReceiveMode.PeekLock); statusLabel.Text = @"Created subscription."; //Start receiving fetchTimer.Start(); } }
public async Task OpenAsync() { var namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString); var tokenProvider = namespaceManager.Settings.TokenProvider; var settings = new MessagingFactorySettings { TokenProvider = tokenProvider, TransportType = TransportType.Amqp, AmqpTransportSettings = new Microsoft.ServiceBus.Messaging.Amqp.AmqpTransportSettings { BatchFlushInterval = TimeSpan.FromMilliseconds(50), } }; _factory = await MessagingFactory.CreateAsync(namespaceManager.Address, settings); var subClient = _factory.CreateSubscriptionClient(_topicName, _subscriptionName); subClient.PrefetchCount = 100; subClient.OnMessageAsync(async message => { await Task.Run(() => { var messageBody = message.GetBody <string>(); var serviceMessage = JsonConvert.DeserializeObject <ServiceMessage>(messageBody); _callback?.Invoke(serviceMessage); }).ContinueWith(async t => { await message.CompleteAsync(); }); }); await Task.Yield(); }
static void ReceiveAllMessageFromSubscription(MessagingFactory messagingFactory, string subsName) { int receivedMessages = 0; // Create subscription client. SubscriptionClient subsClient = messagingFactory.CreateSubscriptionClient(Program.TopicName, subsName, ReceiveMode.ReceiveAndDelete); // Create a receiver from the subscription client and receive all messages. Console.WriteLine("\nReceiving messages from subscription {0}.", subsName); while (true) { BrokeredMessage receivedMessage; receivedMessage = subsClient.Receive(TimeSpan.FromSeconds(10)); if (receivedMessage != null) { receivedMessage.Dispose(); receivedMessages++; } else { // No more messages to receive. break; } } Console.WriteLine("Received {0} messages from subscription {1}.", receivedMessages, subsClient.Name); }
public AzureSubscriber(string serviceBusName, string topicName, string subscriptionName, string serviceBusTokenKeyName, string serviceBusToken, ReceiveMode mode, int?prefetchCount = null) { var namespaceManager = AzureFunctions.CreateNamespaceManager(serviceBusName, serviceBusTokenKeyName, serviceBusToken ); MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings(); messagingFactorySettings.TransportType = TransportType.NetMessaging; messagingFactorySettings.OperationTimeout = TimeSpan.FromMinutes(60); messagingFactorySettings.TokenProvider = namespaceManager.Settings.TokenProvider; MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, messagingFactorySettings); _subscriptionClient = messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, mode); if (prefetchCount.HasValue) { _subscriptionClient.PrefetchCount = prefetchCount.Value; } }
private static void ReceiveFromSubscriptions(string topicPath) { // Create a SubscriptionClient SubscriptionClient subClient = Factory.CreateSubscriptionClient(topicPath, JobType.Testing.ToString()); while (true) { // Recieve any message with a one second timeout. BrokeredMessage msg = subClient.Receive(TimeSpan.FromSeconds(1)); if (msg != null) { // Deserialize the message body to an order. var job = msg.GetBody <Job>(); Console.WriteLine(job.ToString()); // Mark the message as complete. msg.Complete(); } else { //Console.WriteLine(); //break; } } //subClient.Close(); }
public async Task StartListening(TriggerConfig triggerInput) { // Configure the callback options OnMessageOptions options = new OnMessageOptions(); options.AutoComplete = false; options.MaxConcurrentCalls = 10; // create the relevant client and the onMessage listener if (triggerInput.QueueName != null && triggerInput.QueueName.Length > 1) { queueReceiver = messagingFactory.CreateQueueClient(triggerInput.QueueName, ReceiveMode.PeekLock); queueReceiver.OnMessageAsync(async message => { await processMessage(message, logMessageStub); }, options); isListening = true; } else { subscriptionReceiver = messagingFactory.CreateSubscriptionClient(triggerInput.TopicName, triggerInput.SubscriptionName, ReceiveMode.PeekLock); subscriptionReceiver.OnMessageAsync(async message => { await processMessage(message, logMessageStub); }, options); isListening = true; } }
private void SetGreaterThenSubscription(MessagingFactory factory, NamespaceManager namespaceManager) { if (!namespaceManager.SubscriptionExists(this._currentTopic, "GreaterThenSubscription")) { return; } var client = factory.CreateSubscriptionClient(this._currentTopic, "GreaterThenSubscription"); var options = new OnMessageOptions { AutoComplete = false, AutoRenewTimeout = TimeSpan.FromMinutes(1) }; client.OnMessage((message) => { try { var m = message.GetBody <string>(); this._sync.Send(arg => { GreaterThenMessages.Add(m); }, null); } catch (Exception ex) { message.Abandon(); } }, options); }
private static void CreateSubscription(NamespaceManager namespaceManager, MessagingFactory messagingFactory, string topicName, string subscriptionName) { Guid subscriberId = Guid.NewGuid(); TopicDescription topicDescription = namespaceManager.GetTopic(topicName); SubscriptionDescription subscription = null; if (!namespaceManager.SubscriptionExists(topicDescription.Path, subscriptionName)) { subscription = namespaceManager.CreateSubscription(topicDescription.Path, subscriptionName); } else { subscription = namespaceManager.GetSubscription(topicDescription.Path, subscriptionName); } Task.Factory.StartNew(() => { SubscriptionClient subscriptionClient = messagingFactory.CreateSubscriptionClient(topicDescription.Path, subscription.Name); BrokeredMessage message = null; while ((message = subscriptionClient.Receive(TimeSpan.FromSeconds(30))) != null) { Console.WriteLine("Subscriber {0} - Receiving message from subscription '{1}': {2}", subscriberId, subscriptionName, message.GetBody <string>()); message.Complete(); } }, TaskCreationOptions.LongRunning); }
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); } }
async Task ReceiveAllMessageFromSubscription(MessagingFactory messagingFactory, string subsName) { var receivedMessages = 0; // Create subscription client. var subscriptionClient = messagingFactory.CreateSubscriptionClient(TopicName, subsName, ReceiveMode.ReceiveAndDelete); // Create a receiver from the subscription client and receive all messages. Console.WriteLine("\nReceiving messages from subscription {0}.", subsName); while (true) { var receivedMessage = await subscriptionClient.ReceiveAsync(TimeSpan.Zero); if (receivedMessage != null) { foreach (var prop in receivedMessage.Properties) { Console.Write("{0}={1},", prop.Key, prop.Value); } Console.WriteLine("CorrelationId={0}", receivedMessage.CorrelationId); receivedMessage.Dispose(); receivedMessages++; } else { // No more messages to receive. break; } } Console.WriteLine("Received {0} messages from subscription {1}.", receivedMessages, subscriptionClient.Name); }
public SubscriptionClient CreateSubscriptionClient(string nsName, string topicName, string subscriptionName, string keyName, string key) { string cs = _csp.GetConnectionString(nsName, keyName, key); MessagingFactory mf = MessagingFactory.CreateFromConnectionString(cs); return(mf.CreateSubscriptionClient(topicName, subscriptionName)); }
private static void CreateSubscriptionToListenMessages(TopicClient topicClient, StockItemHandler stockMessageHandler, string name) { var subscriptionClient = factory.CreateSubscriptionClient(topicClient.Path, name); var stockListener = new StockListenerService(subscriptionClient, stockMessageHandler); // stockListener.ListenToBatchMessages(CancellationToken.None); stockListener.ListenToMessages(CancellationToken.None); }
public async Task <SubscriptionClient> CreateFor <T>(SubscriptionConfiguration config) { var subscription = await _subscriptionRepository.Get <T>(config.SubscriptionName); var topicPath = subscription.TopicPath; //TODO async return(_messagingFactory.CreateSubscriptionClient(topicPath, subscription.Name, config.ReceiveMode)); }
public static SubscriptionClient CreateSubscriptionClient(string topicPath, string subName) { TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey); Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty); MessagingFactory messagingFactory = MessagingFactory.Create(uri, tokenProvider); return(messagingFactory.CreateSubscriptionClient(topicPath, subName, ReceiveMode.ReceiveAndDelete)); }
public async static Task <SubscriptionClient> EnsureSubscriptionAsync(this MessagingFactory factory, SubscriptionDescription subscriptionDescription, ReceiveMode mode = ReceiveMode.PeekLock) { await new NamespaceManager(factory.Address, factory.GetSettings().TokenProvider) .TryCreateEntity( mgr => SubscriptionCreateAsync(mgr, subscriptionDescription), mgr => SubscriptionShouldExistAsync(mgr, subscriptionDescription)).ConfigureAwait(false); return(factory.CreateSubscriptionClient(subscriptionDescription.TopicPath, subscriptionDescription.Name, mode)); }
static void Main(string[] args) { // The connection string for the RootManageSharedAccessKey can be accessed from the Azure portal // by selecting the SB namespace and clicking on "Connection Information" Console.Write("Enter your connection string for the RootManageSharedAccessKey for your Service Bus namespace: "); nsConnectionString = Console.ReadLine(); /////////////////////////////////////////////////////////////////////////////////////// // Create a topic with a SAS Listen rule and an associated subscription /////////////////////////////////////////////////////////////////////////////////////// NamespaceManager nm = NamespaceManager.CreateFromConnectionString(nsConnectionString); contosoTListenRule = new SharedAccessAuthorizationRule("contosoTListenKey", SharedAccessAuthorizationRule.GenerateRandomKey(), new[] { AccessRights.Listen }); TopicDescription td = new TopicDescription(topicPath); td.Authorization.Add(contosoTListenRule); nm.CreateTopic(td); nm.CreateSubscription(topicPath, subscriptionName); /////////////////////////////////////////////////////////////////////////////////////// // Send a message to the topic // Note that this uses the connection string for RootManageSharedAccessKey // configured on the namespace root /////////////////////////////////////////////////////////////////////////////////////// MessagingFactory sendMF = MessagingFactory.CreateFromConnectionString(nsConnectionString); TopicClient tc = sendMF.CreateTopicClient(topicPath); BrokeredMessage sentMessage = CreateHelloMessage(); tc.Send(sentMessage); Console.WriteLine("Sent Hello message to topic: ID={0}, Body={1}.", sentMessage.MessageId, sentMessage.GetBody <string>()); /////////////////////////////////////////////////////////////////////////////////////// // Generate a SAS token scoped to a subscription using the SAS rule with // a Listen right configured on the Topic & TTL of 1 day /////////////////////////////////////////////////////////////////////////////////////// ServiceBusConnectionStringBuilder csBuilder = new ServiceBusConnectionStringBuilder(nsConnectionString); IEnumerable <Uri> endpoints = csBuilder.Endpoints; string subscriptionUri = endpoints.First <Uri>().ToString() + topicPath + "/subscriptions/" + subscriptionName; string subscriptionToken = SASTokenGenerator.GetSASToken(subscriptionUri, contosoTListenRule.KeyName, contosoTListenRule.PrimaryKey, TimeSpan.FromDays(1)); /////////////////////////////////////////////////////////////////////////////////////// // Use the SAS token scoped to a subscription to receive the messages /////////////////////////////////////////////////////////////////////////////////////// MessagingFactory listenMF = MessagingFactory.Create(endpoints, new StaticSASTokenProvider(subscriptionToken)); SubscriptionClient sc = listenMF.CreateSubscriptionClient(topicPath, subscriptionName); BrokeredMessage receivedMessage = sc.Receive(TimeSpan.FromSeconds(10)); Console.WriteLine("Received message from subscription: ID = {0}, Body = {1}.", receivedMessage.MessageId, receivedMessage.GetBody <string>()); /////////////////////////////////////////////////////////////////////////////////////// // Clean-up /////////////////////////////////////////////////////////////////////////////////////// nm.DeleteTopic(topicPath); }
public SubscriptionClient CreateSubscriptionClient(string nsName, string topicName, string subscriptionName, string keyName, string key) { Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", nsName, string.Empty); TokenProvider tp = GetTokenProvider(keyName, key); MessagingFactory mf = MessagingFactory.Create(runtimeUri, tp); return(mf.CreateSubscriptionClient(topicName, subscriptionName)); }
public ServiceBusTopicHelper Subscribe <T>(Action <T> receiveHandler, string filterSqlStatement = null, string subscriptionName = null, ReceiveMode receiveMode = ReceiveMode.ReceiveAndDelete) { // if they asked for a subscription with a filter and no name, blow up if (!string.IsNullOrEmpty(filterSqlStatement) && string.IsNullOrEmpty(subscriptionName)) { throw new ArgumentException("If filterSqlStatement is provided, subscriptionName must also be provided."); } _receiveMode = receiveMode; SetupServiceBusEnvironment(); var topicName = string.Format("Topic_{0}", typeof(T).Name); subscriptionName = string.IsNullOrEmpty(subscriptionName) ? string.Format("Subscription_{0}", typeof(T).Name) : subscriptionName; if (!_namespaceManager.TopicExists(topicName)) { _namespaceManager.CreateTopic(topicName); } var topic = _namespaceManager.GetTopic(topicName); SubscriptionDescription subscription; // always create a new subscription just in case the calling code's changed expectations if (_namespaceManager.SubscriptionExists(topic.Path, subscriptionName)) { _namespaceManager.DeleteSubscription(topic.Path, subscriptionName); } if (string.IsNullOrEmpty(filterSqlStatement)) { subscription = _namespaceManager.CreateSubscription(topic.Path, subscriptionName); } else { var filter = new SqlFilter(filterSqlStatement); subscription = _namespaceManager.CreateSubscription(topic.Path, subscriptionName, filter); } var subscriptionClient = _messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, receiveMode); _subscribers.Add(new Tuple <string, SubscriptionClient>(topicName, subscriptionClient)); Begin <T>(receiveHandler, subscriptionClient); return(this); }
public void RequeueAll(string topicPath, string subscriptionName) { var client = _messagingFactory.CreateSubscriptionClient(topicPath, subscriptionName.MakeDeadLetterPath()); var sub = _namespaceManager.GetSubscription(topicPath, subscriptionName); var count = sub.MessageCountDetails.DeadLetterMessageCount; var sender = client.MessagingFactory.CreateMessageSender(client.TopicPath); for (var i = 0; i < count; i++) { var msg = client.Receive(new TimeSpan(0, 0, 5)); if (msg == null) { break; } var clone = Clone(msg); clone.RemoveProperties(GetPropertiesToRemove()); if (clone.Properties.ContainsKey("RequeuedFrom")) { clone.Properties["RequeuedFrom"] = clone.Properties["RequeuedFrom"] += "," + msg.MessageId; } else { clone.Properties.Add("RequeuedFrom", msg.MessageId); } sender.Send(clone); msg.Complete(); } }
private static SubscriptionClient GetSubscriptionClient(string topicName, string subscriptionName, NamespaceManager namespaceManager) { var mfs = new MessagingFactorySettings { TokenProvider = namespaceManager.Settings.TokenProvider }; MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, mfs); return(messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, ReceiveMode.ReceiveAndDelete)); }
private static void ReceiveFromSubscriptions(string topicPath) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Receiving from topic {0} subscriptions.", topicPath); // Loop through the subscriptions in a topic. foreach (SubscriptionDescription subDescription in NamespaceMgr.GetSubscriptions(topicPath)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" Receiving from subscription {0}...", subDescription.Name); // Create a SubscriptionClient SubscriptionClient subClient = Factory.CreateSubscriptionClient(topicPath, subDescription.Name); // Receive all the massages form the subscription. Console.ForegroundColor = ConsoleColor.Green; while (true) { // Recieve any message with a one second timeout. BrokeredMessage msg = subClient.Receive(TimeSpan.FromSeconds(1)); if (msg != null) { // Deserialize the message body to an order. Order order = msg.GetBody <Order>(); //Console.WriteLine(" Received {0}", order.Name); Console.WriteLine(" Name {0} {1} items {2} ${3} {4}", order.Name, order.Region, order.Items, order.Value, order.HasLoyltyCard ? "Loyal" : "Not loyal"); // Mark the message as complete. msg.Complete(); } else { Console.WriteLine(); break; } } // Close the SubscriptionClient. subClient.Close(); } Console.ResetColor(); }
public void PublishMessageOfStockItem() { //arrange var stockItem = new StockItem("ABC", 1, "FCLondon", "DHL"); var stockMessagerService = new StockMessagerService(sender); var topicClient = factory.CreateTopicClient("stocklevels"); var subscriptionClient = factory.CreateSubscriptionClient(topicClient.Path, "GBWarehouseStockLevels"); stockMessagerService.SendMessageAsync(stockItem).Wait(); var message = subscriptionClient.Receive(); var streamReader = new StreamReader(message.GetBody <Stream>()); var result = JsonConvert.DeserializeObject <StockItem>(streamReader.ReadToEnd()); //assert Assert.That(result.Sku.Equals("ABC")); }
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()); } }
internal static void ConfigureServiceHUB() { try { //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http; ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder(NebulusClient.App.ClientConfiguration.ServiceBUSConenctionString); MessagingFactory messageFactory = MessagingFactory.CreateFromConnectionString(connBuilder.ToString()); NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString()); var SubscriptionName = Environment.MachineName; if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 1) { SubscriptionName = Environment.UserName; } if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 2) { SubscriptionName = Environment.MachineName + "\\" + Environment.UserName; } if (NebulusClient.Properties.Settings.Default.SubscriptionNameLevel == 3) { try { SubscriptionName = Environment.GetEnvironmentVariable("CLIENTNAME"); } catch { } } if (namespaceManager.SubscriptionExists(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName)) { namespaceManager.DeleteSubscription(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName); } namespaceManager.CreateSubscription(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, SubscriptionName, new SqlFilter(BuildRules())); NSBQClient = messageFactory.CreateSubscriptionClient(NebulusClient.App.ClientConfiguration.ServiceBUSQueueName, Environment.MachineName, ReceiveMode.ReceiveAndDelete); } catch (Exception ex) { AppLogging.Instance.Error("Error: Connecting to ServiceBus ", ex); } }
protected override void NewItem(string path, string type, object newItemValue) { string[] pathChunks = Context.ChunkPath(this.PSDriveInfo, path); string name = pathChunks[pathChunks.Length - 1]; string parentPath = path.Substring(0, path.LastIndexOf('\\')); pathChunks = Context.ChunkPath(this.PSDriveInfo, parentPath); // Find the root resource specified in the path switch (pathChunks.Length) { case 1: if (string.Compare(pathChunks[0], "Queues", true) == 0) { this.ServiceBusNamespaceClient.CreateQueue(name); } else if (string.Compare(pathChunks[0], "Topics", true) == 0) { this.ServiceBusNamespaceClient.CreateTopic(name); } break; case 2: if (string.Compare(pathChunks[0], "Topics", true) == 0) { TopicDescription topic = (TopicDescription)this.GetItemAt(parentPath); this.ServiceBusNamespaceClient.CreateSubscription(topic.Path, name); } break; case 3: if (string.Compare(pathChunks[0], "Topics", true) == 0) { MessagingFactory factory = Context.GetMessagingFactory(this.SessionState); SubscriptionDescription subscription = (SubscriptionDescription)this.GetItemAt(parentPath); SubscriptionClient client = factory.CreateSubscriptionClient(subscription.TopicPath, subscription.Name); client.AddRule(name, new Messaging.TrueFilter()); } break; } Context.Cache.Remove(this.GetPathTillElement(path, pathChunks.Length)); }
static void ReceiveAllMessageFromSubscription(MessagingFactory messagingFactory, string subsName) { int receivedMessages = 0; // Create subscription client. SubscriptionClient subsClient = messagingFactory.CreateSubscriptionClient(Conts.TopicName, subsName, ReceiveMode.ReceiveAndDelete); // Create a receiver from the subscription client and receive all messages. Console.WriteLine("\nReceiving messages from subscription {0}.", subsName); while (true) { BrokeredMessage receivedMessage; receivedMessage = subsClient.Receive(TimeSpan.FromSeconds(1)); if (receivedMessage != null) { Console.WriteLine(); DateTime dob = ((DateTime)receivedMessage.Properties["DOB"]); Console.WriteLine("Id = {1} DOB = {0}", receivedMessage.MessageId, dob); receivedMessage.Dispose(); receivedMessages++; } else { // No more messages to receive. break; } } Console.WriteLine("Received {0} messages from subscription {1}.", receivedMessages, subsClient.Name); }
private static SubscriptionClient CreateTopicSubscriptionClient(Uri serviceUri, TokenProvider tokenProvider, string subscriptionName, ref MessagingFactory factory) { if (factory == null) factory = MessagingFactory.Create(serviceUri, tokenProvider); return factory.CreateSubscriptionClient(TopicName, subscriptionName); }
public SubscriptionClient Create(SubscriptionDescription description, MessagingFactory factory) { var subscriptionClient = factory.CreateSubscriptionClient(description.TopicPath, description.Name, ShouldRetry() ? ReceiveMode.PeekLock : ReceiveMode.ReceiveAndDelete); subscriptionClient.PrefetchCount = BatchSize; return subscriptionClient; }