//code adapted from tutorial https://paolopatierno.wordpress.com/2015/11/02/azure-iot-hub-get-telemetry-data-using-amqp-stack-and-azure-sb-lite/ public static string GetMessage(string partitionId) { string result = null; ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString); builder.TransportType = TransportType.Amqp; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString); EventHubClient client = factory.CreateEventHubClient(eventHubEntity); EventHubConsumerGroup group = client.GetDefaultConsumerGroup(); var startingDateTimeUtc = DateTime.Now; EventHubReceiver receiver = group.CreateReceiver(partitionId, startingDateTimeUtc); EventData data = receiver.Receive(); receiver.Close(); client.Close(); factory.Close(); if (data != null) { result = Encoding.UTF8.GetString(data.GetBytes()); return(result); } else { return(null); } }
private static void CreateQueueToRead() { TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider; if (_namespaceManager.QueueExists("categoryqueue")) { MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider); QueueClient catsQueueClient = factory.CreateQueueClient("categoryqueue"); Console.WriteLine("Receiving the Messages from the Queue...."); BrokeredMessage message; int ctr = 1; while ((message = catsQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null) { Console.WriteLine($"Message Received, Sequance: {message.SequenceNumber}, MessageID: {message.MessageId},\nCat: {message.Properties[(ctr++).ToString()]}"); message.Complete(); Console.WriteLine("Processing Message (sleeping)....."); Thread.Sleep(1000); } factory.Close(); catsQueueClient.Close(); _namespaceManager.DeleteQueue("categoryqueue"); Console.WriteLine("Finished getting all the data from the queue, Press any key to exit"); } }
public static void Main() { // Setup: Sender.GetUserCredentials(); QueueDescription queueDescription = CreateQueue(); QueueClient queueClient = CreateQueueClient(queueDescription); // Send messages to queue: Console.WriteLine("Sending messages to queue..."); BrokeredMessage message1 = CreateOrderMessage("High"); queueClient.Send(message1); Console.WriteLine("Sent message {0} with high priority.", message1.MessageId); BrokeredMessage message2 = CreateOrderMessage("Low"); queueClient.Send(message2); Console.WriteLine("Sent message {0} with low priority.", message2.MessageId); BrokeredMessage message3 = CreateOrderMessage("High"); queueClient.Send(message3); Console.WriteLine("Sent message {0} with high priority.", message3.MessageId); Console.WriteLine(); Console.WriteLine("Press [Enter] to delete queue and exit."); Console.ReadLine(); // Cleanup: messagingFactory.Close(); namespaceManager.DeleteQueue(queueDescription.Path); }
/// <summary> /// Clean up any subscriptions that are not closed already /// </summary> static void Cleanup() { if (!(factory.IsClosed)) { factory.Close(); } }
public ActionResult Receive() { // create a messaging factory configured to use a ManagedServiceIdentityTokenProvider MessagingFactory messagingFactory = CreateMessagingFactoryWithMsiTokenProvider(); // create a queue client using the queue name supplied by the web.config QueueClient queueClient = messagingFactory.CreateQueueClient(ServiceBusQueue); // request a readily available message (with a very short wait) BrokeredMessage msg = queueClient.Receive(TimeSpan.FromSeconds(1)); var messageInfo = new ServiceBusMessageInfo(); if (msg != null) { messageInfo.MessageReceived = $"Seq#:{msg.SequenceNumber} data:{Encoding.UTF8.GetString(msg.GetBody<byte[]>())}{Environment.NewLine}"; } else { messageInfo.MessageReceived = "<no messages in queue>"; } queueClient.Close(); messagingFactory.Close(); return(View("Index", messageInfo)); }
static void Main(string[] args) { // *************************************************************************************** // 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. // *************************************************************************************** // Get ServiceBus namespace and credentials from the user. Program.GetNamespaceAndCredentials(); // Create messaging factory and ServiceBus namespace client. MessagingFactory messagingFactory = Program.CreateMessagingFactory(); NamespaceManager namespaceManager = Program.CreateNamespaceManager(); // Delete the topic from last run. Program.DeleteTopicsAndSubscriptions(namespaceManager); // Create topic and subscriptions that'll be using through the sample. Program.CreateTopicsAndSubscriptions(namespaceManager); // Send sample messages. Program.SendMessagesToTopic(messagingFactory); // Receive messages from subscriptions. Program.ReceiveAllMessagesFromSubscripions(messagingFactory); messagingFactory.Close(); Console.WriteLine("Press [Enter] to quit..."); Console.ReadLine(); }
public void Scenario10_QueueRequestResponse(string queue, string replyTo) { WorkerThread receiverThread = new WorkerThread(this.Scenario11_QueueReceiver); receiverThread.Start(queue); ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString); builder.TransportType = TransportType.Amqp; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString); MessageSender sender = factory.CreateMessageSender(queue); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("Request")); BrokeredMessage message = new BrokeredMessage(stream); message.MessageId = Guid.NewGuid().ToString(); message.ReplyTo = replyTo; message.Properties["time"] = DateTime.UtcNow; sender.Send(message); MessageReceiver receiver = factory.CreateMessageReceiver(replyTo); BrokeredMessage response = receiver.Receive(); response.Complete(); sender.Close(); receiver.Close(); factory.Close(); }
public void Scenario4_EventHubSendToPublisherWithToken(string sbnamespace, string eventHubEntity, string publisher, string sharedAccessKeyName, string sharedAccessKey) { string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature( new Uri(sbnamespace), eventHubEntity, publisher, sharedAccessKeyName, sharedAccessKey, new TimeSpan(0, 20, 0)); string connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature( new Uri(sbnamespace), eventHubEntity, publisher, token); MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString); EventHubClient client = factory.CreateEventHubClient(eventHubEntity); EventHubSender sender = client.CreateSender(publisher); EventData data = new EventData(Encoding.UTF8.GetBytes("Body")); data.Properties["time"] = DateTime.UtcNow; sender.Send(data); sender.Close(); client.Close(); factory.Close(); }
public void Scenario12_TopicSend(string topic, string subscription1, string subscription2) { WorkerThread sub1Thread = new WorkerThread(this.Scenario13_SubscriptionReceiver); sub1Thread.Start(new Scenarios.TopicSub() { Topic = topic, Sub = subscription1 }); WorkerThread sub2Thread = new WorkerThread(this.Scenario13_SubscriptionReceiver); sub2Thread.Start(new Scenarios.TopicSub() { Topic = topic, Sub = subscription2 }); ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString); builder.TransportType = TransportType.Amqp; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString); TopicClient client = factory.CreateTopicClient(topic); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("Body")); BrokeredMessage message = new BrokeredMessage(stream); message.Properties["time"] = DateTime.UtcNow; client.Send(message); client.Close(); factory.Close(); }
private static void CreateQueueToRead() { TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider; if (_namespaceManager.QueueExists("categoryqueue")) { //Creating the queues with details //QueueDescription mnQueue = namespaceManagerClient.CreateQueue("categoryqueue"); MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider); //ReceiveAndDelete chances of not clearing the data if it crash before //PeekLock, it locks the second message in line and only by calling Complete it moves to the next only then it deletes it of this is default mode QueueClient catsQueueClient = factory.CreateQueueClient("categoryqueue"); Console.WriteLine("Receiving the Messages from the Queue...."); BrokeredMessage message; int ctr = 1; while ((message = catsQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null) { //Console.WriteLine("Message Received, Sequence: {0}, Cat: {1} and MessageID: {2}", message.SequenceNumber, message.Properties[(ctr++).ToString()], message.MessageId); Console.WriteLine($"Message Received, Sequence: {message.SequenceNumber}, MessageID: {message.MessageId},\nCat: {message.Properties[(ctr++).ToString()]}"); message.Complete(); Console.WriteLine("Processing Message (sleeping)....."); Thread.Sleep(2000); } factory.Close(); catsQueueClient.Close(); _namespaceManager.DeleteQueue("categoryqueue"); Console.WriteLine("Finished getting all the data from the queue, Press any key to exit"); } }
public string Get() { try { // create a parameter object for the messaging factory that configures // the MSI token provider for Service Bus and use of the AMQP protocol: MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings { TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience), TransportType = TransportType.Amqp }; // create the messaging factory using the namespace endpoint name supplied by the user MessagingFactory messagingFactory = MessagingFactory.Create($"sb://gordsbus.servicebus.windows.net/", messagingFactorySettings); // create a queue client using the queue name supplied by the user QueueClient queueClient = messagingFactory.CreateQueueClient("fabrictraffic"); queueClient.Send(new BrokeredMessage(Encoding.UTF8.GetBytes("Api hit"))); queueClient.Close(); messagingFactory.Close(); return("All good"); } catch (Exception ex) { return(ex.ToString()); } }
public async Task ReceiveDataFromCloud() { startingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromHours(24); factory = MessagingFactory.CreateFromConnectionString(ConnectionString); client = factory.CreateEventHubClient(eventHubEntity); group = client.GetDefaultConsumerGroup(); receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc); try { while (true) { EventData data = receiver.Receive(); if (data != null) { var receiveddata = Encoding.UTF8.GetString(data.GetBytes()); Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), receiveddata); } } } catch (Exception ex) { Debug.WriteLine("Exception {0}", ex); } receiver.Close(); client.Close(); factory.Close(); }
public void Stop() { if (_messageFactory != null) { _messageFactory.Close(); } }
protected void btnReceive_Click(object sender, EventArgs e) { // create a parameter object for the messaging factory that configures // the MSI token provider for Service Bus and use of the AMQP protocol: MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings { TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience), TransportType = TransportType.Amqp }; // TODO - Remove after backend is patched with the AuthComponent open fix // https://github.com/Azure/azure-service-bus/issues/136 messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false; // create the messaging factory using the namespace endpoint name supplied by the user MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}/", messagingFactorySettings); // create a queue client using the queue name supplied by the user QueueClient queueClient = messagingFactory.CreateQueueClient(txtQueueName.Text, ReceiveMode.ReceiveAndDelete); // request a readily available message (with a very short wait) BrokeredMessage msg = queueClient.Receive(TimeSpan.FromSeconds(1)); if (msg != null) { // if we got a message, show its contents. txtReceivedData.Text += $"Seq#:{msg.SequenceNumber} data:{Encoding.UTF8.GetString(msg.GetBody<byte[]>())}{Environment.NewLine}"; } queueClient.Close(); messagingFactory.Close(); }
static void ReceiveMessage() { TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider; if (_namespaceManager.TopicExists("DataCollectionTopic")) { MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider); //MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory"); MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard"); BrokeredMessage receivedMessage = null; try { while ((receivedMessage = receiver.Receive()) != null) { ProcessMessage(receivedMessage); receivedMessage.Complete(); } factory.Close(); _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory"); // _namespaceManager.DeleteTopic("DataCollectionTopic"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); receivedMessage.Abandon(); } } }
protected void btnSend_Click(object sender, EventArgs e) { // create a parameter object for the messaging factory that configures // the MSI token provider for Service Bus and use of the AMQP protocol: MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings { TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience), TransportType = TransportType.Amqp }; // TODO - Remove after backend is patched with the AuthComponent open fix // https://github.com/Azure/azure-service-bus/issues/136 messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false; // create the messaging factory using the namespace endpoint name supplied by the user MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}/", messagingFactorySettings); // create a queue client using the queue name supplied by the user QueueClient queueClient = messagingFactory.CreateQueueClient(txtQueueName.Text); // send a message using the input text queueClient.Send(new BrokeredMessage(Encoding.UTF8.GetBytes(txtData.Text))); queueClient.Close(); messagingFactory.Close(); }
private static void ReceiveMessage() { TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;; if (_namespaceManager.TopicExists("DataCollectionTopic")) { MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider); //Same as Queue ReceiveMode.PeekLock is default MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory"); MessageReceiver receiver1 = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard"); BrokeredMessage receivedMessage = null; try { Console.WriteLine($"From Inventory"); while ((receivedMessage = receiver.Receive()) != null) { ProcessMessage(receivedMessage); receivedMessage.Complete(); } Console.WriteLine($"From Dashboard"); while ((receivedMessage = receiver1.Receive()) != null) { ProcessMessage(receivedMessage); receivedMessage.Complete(); } factory.Close(); _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory"); _namespaceManager.DeleteSubscription("DataCollectionTopic", "Dashboard"); _namespaceManager.DeleteTopic("DataCollectionTopic"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); receivedMessage.Abandon(); } #region With Collection //IEnumerable<BrokeredMessage> receivedMessageList = receiver.ReceiveBatch(2); //try //{ // foreach (var item in receivedMessageList) // { // ProcessMessage(item); // item.Complete(); // } // factory.Close(); // _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory"); // //_namespaceManager.DeleteSubscription("DataCollectionTopic", "Dashboard"); // //_namespaceManager.DeleteTopic("DataCollectionTopic"); //} //catch (Exception ex) //{ // Console.WriteLine(ex.ToString()); //} #endregion } }
protected override void Dispose(bool disposing) { if (disposing) { _eventHubClient.Close(); _messsagingFactory.Close(); } }
// public async MessageSession AcceptMessageSession(TimeSpan timeout) // { // // } public void Close() { foreach (var qc in this.clients) { qc.Close(); } factory.Close(); }
public void Dispose() { foreach (var client in _queueClient.Values) { client.Close(); } _factory.Close(); }
public static void Stop() { cts.Cancel(); receiverList.ForEach(r => r.Close()); client.Close(); factory.Close(); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (!factory.IsClosed) { factory.Close(); } } }
internal static void Dispose(this MessagingFactory messagingFactory) { try { messagingFactory.Close(); } catch { // we don't care. It's already borked. We just want it to go away and release its connection. } }
public void Dispose() { if (_queueClient != null) { _queueClient.Close(); } if (_factory != null) { _factory.Close(); } }
public void Disconnect() { _log.DebugFormat("disconnecting '{0}'", _endpointAddress); if (_messagingFactory != null) { _messagingFactory.Close(); } _messagingFactory = null; }
// ReSharper restore FunctionNeverReturns public override void OnStop() { base.OnStop(); _factory.Close(); _inputQueueClient.Close(); _errorQueueClient.Close(); _factory = null; _inputQueueClient = null; _errorQueueClient = null; }
public bool Stop(HostControl hostControl) { watcher.EnableRaisingEvents = false; tokenSource.Cancel(); messagingFactory.Close(); imageSender.Close(); configReciver.Close(); return(true); }
public void Disconnect() { if (_factory != null) { _log.DebugFormat("disconnecting '{0}'", _address); _factory.Close(); _factory = null; } _manager = null; }
public virtual void Dispose() { if (!_busReceiver.IsClosed) { _busReceiver.Abort(); _busReceiver.Close(); } if (!_messagingFactory.IsClosed) { _messagingFactory.Close(); } }
/// <summary> /// Start the demo code. /// </summary> /// <param name="args"></param> static void Main(string[] args) { GetUserCredentials(); TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerKey); Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty); //***************************************************************************************************** // Management Operations //***************************************************************************************************** NamespaceManager namespaceManager = new NamespaceManager(serviceUri, tokenProvider); // Create a topic Console.WriteLine("\nCreating Topic 'IssueTrackingTopic'..."); // Delete if exists if (namespaceManager.TopicExists(Program.IssueTrackingTopic)) { namespaceManager.DeleteTopic(Program.IssueTrackingTopic); } TopicDescription myTopic = namespaceManager.CreateTopic(Program.IssueTrackingTopic); // Create a subscription Console.WriteLine("Creating Subscriptions 'AuditSubscription' and 'AgentSubscription'..."); SubscriptionDescription myAuditSubscription = namespaceManager.CreateSubscription(Program.IssueTrackingTopic, Program.AuditSubscription); SubscriptionDescription myAgentSubscription = namespaceManager.CreateSubscription(Program.IssueTrackingTopic, Program.AgentSubscription); //***************************************************************************************************** // Runtime Operations //***************************************************************************************************** MessagingFactory factory = MessagingFactory.Create(serviceUri, tokenProvider); try { Program.Send(factory); Program.Receive(factory); } finally { factory.Close(); } Console.WriteLine("\nEnd of scenario, press ENTER to clean up and exit."); Console.ReadLine(); namespaceManager.DeleteTopic(Program.IssueTrackingTopic); }