private static void ReceiveMessages() { Console.WriteLine("\nReceiving message from Queue..."); BrokeredMessage message = null; var sessions = queueClient.GetMessageSessions(); foreach (var browser in sessions) { Console.WriteLine(string.Format("Session discovered: Id = {0}", browser.SessionId)); var session = queueClient.AcceptMessageSession(browser.SessionId); while (true) { try { message = session.Receive(TimeSpan.FromSeconds(5)); if (message != null) { Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>())); if (session.SessionId == SessionId2) { // if this is the second session then let's send to the dead letter for fun message.DeadLetter(); } else { // Further custom message processing could go here... message.Complete(); } } else { //no more messages in the queue break; } } catch (MessagingException e) { if (!e.IsTransient) { Console.WriteLine(e.Message); throw; } else { HandleTransientErrors(e); } } } } queueClient.Close(); }
public static void Main(string[] args) { QueueClient client = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbDestinationQueue); Console.Write("Composing message..."); var brokeredMessage = new BrokeredMessage("Message body goes here."); // You can set properties as key/value pairs brokeredMessage.Properties["_userId"] = _userId; Console.Write("done.\n\n"); string msgStatus; Console.Write("Sending message..."); try { client.Send(brokeredMessage); msgStatus = "sent"; } catch (MessagingEntityNotFoundException) { msgStatus = "failed: Messaging Entity Not Found"; } client.Close(); Console.WriteLine("{0}.\n\nPress enter to quit.\n", msgStatus); Console.ReadLine(); }
public override void OnStop() { // Fermez la connexion à la file d'attente Service Bus Client.Close(); CompletedEvent.Set(); base.OnStop(); }
void ConnectionBinding <AzureServiceBusConnection> .Unbind(AzureServiceBusConnection connection) { lock (_lock) { try { if (_topicClient != null && !_topicClient.IsClosed) { _topicClient.Close(); } if (_queueClient != null && !_queueClient.IsClosed) { _queueClient.Close(); } } catch (Exception ex) { _log.Error("Failed to close client", ex); } finally { _topicClient = null; _queueClient = null; } } }
public override void OnStop() { // Close the connection to Service Bus Queue IsStopped = true; Client.Close(); base.OnStop(); }
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)); }
private void CreateStartMessage(string serviceBusConnectionString) { string queueName = ResolveName(StartQueueName); if (!_namespaceManager.QueueExists(queueName)) { _namespaceManager.CreateQueue(queueName); } QueueClient queueClient = QueueClient.CreateFromConnectionString(serviceBusConnectionString, queueName); using (Stream stream = new MemoryStream()) using (TextWriter writer = new StreamWriter(stream)) { writer.Write("E2E"); writer.Flush(); stream.Position = 0; queueClient.Send(new BrokeredMessage(stream) { ContentType = "text/plain" }); } queueClient.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"); } }
private void BtnDeleteQueueClicked(object sender, RoutedEventArgs e) { var selectedQueue = this.CbQueues.SelectedItem as string; if (selectedQueue == null) { MessageBox.Show("Please chosse the queue to delete."); return; } if (_client != null && !_client.IsClosed) { _client.Close(); } this.GetNamespaceManager().DeleteQueue(selectedQueue); if (Queues.Contains(selectedQueue)) { Queues.Remove(selectedQueue); } Messages.Clear(); this.ShowPrompt("deleted", selectedQueue); }
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(); }
public override void OnStop() { Trace.WriteLine("Stopping Worker Instance"); if (_apiNode != null) { _apiNode.Dispose(); } if (_apiPostback != null) { _apiPostback.Dispose(); } // Close the connections to Service Bus foreach (var client in _nodeEventsQueues) { client.Close(); } if (_nodesUpdateTopic != null) { _nodesUpdateTopic.Close(); } if (_frontendNotificationsQueue != null) { _frontendNotificationsQueue.Close(); } // Release blocked thread _completedEvent.Set(); base.OnStop(); }
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 override void OnStop() { // Cerrar la conexión con la cola de Service Bus Client.Close(); CompletedEvent.Set(); base.OnStop(); }
public void Finalize() { // Close the connection to Service Bus Queue Client.Close(); //CompletedEvent.Set(); //base.OnStop(); }
public override void OnStop() { // 关闭与 Service Bus 队列的连接 Client.Close(); CompletedEvent.Set(); base.OnStop(); }
public override void OnStop() { // Close the connection to Service Bus Queue Client.Close(); CompletedEvent.Set(); base.OnStop(); }
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(); }
private void SendPdfDocument(object sender, EventArgs e) { QueueClient client = null; byte[] pdf = null; try { pdf = this.pdfCreator.GetPdf(this.outDir); this.ClearPdfCreatorFilePathes(); this.pdfCreator.Reset(); client = QueueClient.Create(DocQueueName); client.Send(new BrokeredMessage(pdf)); } catch (MessageSizeExceededException ex) { this.StartToProcessChunkDoc(pdf, client); Console.WriteLine(ex.Message); ////log } catch (Exception ex) { throw ex; } finally { client.Close(); } }
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()); } }
static void Main(string[] args) { try { //Creación del cliente QueueClient queueCliente = QueueClient.CreateFromConnectionString(ConnectionString, queueName); string json = @"{ ""Id"": ""1"", ""Tipo"": ""Demo"", ""Mensaje"": ""Esto es una demostracion"" }"; byte[] bytes = Encoding.UTF8.GetBytes(json); MemoryStream stream = new MemoryStream(bytes, writable: false); BrokeredMessage message = new BrokeredMessage(stream) { ContentType = "application/json" }; queueCliente.Send(message); queueCliente.Close(); } catch { throw; } }
// Put: api/ReportGenerate public void Put(ReportRequest req) { string queuePath = CloudConfigurationManager.GetSetting("queuePath"); string queueConnectionString = CloudConfigurationManager.GetSetting("queueConnectionString"); NamespaceManager nsm = NamespaceManager.CreateFromConnectionString(queueConnectionString); //create queue if it doesn't exist if (!nsm.QueueExists(queuePath)) { Trace.TraceInformation("Creating queue: {0}...", queuePath); QueueDescription qd = new QueueDescription(queuePath); qd.RequiresDuplicateDetection = true; //this can't be changed later qd = nsm.CreateQueue(qd); Trace.TraceInformation("Queue created."); } //insert the Path to the queue QueueClient queueClient = QueueClient.CreateFromConnectionString(queueConnectionString, queuePath); BrokeredMessage bm = new BrokeredMessage(); bm.Properties.Add("reportReq", req.Path); Trace.TraceInformation("Sending report gen request: {0}", req.Path); queueClient.Send(bm); Trace.TraceInformation("Request queued."); queueClient.Close(); }
private void button1_Click(object sender, EventArgs e) { lstMensagens.Items.Add("status: Recebendo mensagens..."); this.Refresh(); queueClient = QueueClient.Create(QueueName); BrokeredMessage message = null; while (true) { try { message = queueClient.Receive(TimeSpan.FromSeconds(2)); if (message != null) { lstResultado.Items.Add(string.Format("Id: {0}, Body: {1}", message.MessageId, message.GetBody<string>())); message.Complete(); } else break; } catch (MessagingException error) { if (!error.IsTransient) { lstMensagens.Items.Add("status: " + error.Message); } else ManipularExcecoes(error); } } queueClient.Close(); }
private void Stop() { if (_client != null && !_client.IsClosed) { _client.Close(); _client = null; } }
protected override void OnClosing(CancelEventArgs e) { topicSubscriber?.Dispose(); client.Close(); controller.ResetLight(0); controller.CloseDevices(numberOfDevices); base.OnClosing(e); }
public void CancelOperations() { SendServerStatus(SBServerStatuses.Stopped); _cancelTokenSource.Cancel(); _queueClient.Close(); _queueServerStatusClient.Close(); _queueClientStatusClient.Close(); }
public void Close() { if (_client != null) { _client.Close(); _client = null; } }
/// <summary> /// Stop listening for messages. /// </summary> public void Stop() { if (!_isStarted) throw new InvalidOperationException("AzureCommandBusListener is not running."); _isStarted = false; _queueClient.Close(); }
public override void OnStop() { _isStopped = true; _repository.Dispose(); _queueClient.Close(); _mediaServices.Dispose(); base.OnStop(); }
private static bool WriteToQueue(string message, string qname) { QueueClient qcCRM = QueueClient.CreateFromConnectionString(_azureConnStr, qname); BrokeredMessage msgCustNum = new BrokeredMessage(message + "@ " + DateTime.Now.ToString()); qcCRM.Send(msgCustNum); qcCRM.Close(); return(true); }
public override void OnStop() { _unityContainer.Dispose(); // Close the connection to Service Bus Queue _queueClient.Close(); _completedEvent.Set(); base.OnStop(); }
/// <summary> /// Subscribes the specified handler to the event bus. /// </summary> /// <param name="handler">The handler.</param> /// <param name="bus">The bus.</param> public IDisposable SubscribeToBus(object handler, IEventBus bus) { queueClient = CreateQueueClient(settings); return new CompositeDisposable { exceptionSubject.Subscribe(ex => bus.PublishErrorAsync(new EventHandlingError(ex, handler))), Disposable.Create(() => queueClient.Close()) }; }
/// <summary> /// Subscribes the specified handler to the event bus. /// </summary> /// <param name="handler">The handler.</param> /// <param name="bus">The bus.</param> public IDisposable SubscribeToBus(object handler, IEventBus bus) { queueClient = CreateQueueClient(settings); return(new CompositeDisposable { exceptionSubject.Subscribe(ex => bus.PublishErrorAsync(new EventHandlingError(ex, handler))), Disposable.Create(() => queueClient.Close()) }); }
static void Main(string[] args) { queueClient = QueueClient.Create(queueName); bool keepOn = true; while(keepOn) { Console.Out.WriteLine("Who do you want to send a message to?"); string name = Console.ReadLine(); Console.Out.WriteLine("What is your message to " + name + "?"); string message = Console.ReadLine(); SendMessage(name, message); Console.Out.WriteLine("Press [ENTER] to send another message or any other key to quit"); ConsoleKeyInfo ki = Console.ReadKey(); keepOn = (ki.Key == ConsoleKey.Enter); } queueClient.Close(); }
public override void Run() { try { var nsManager = NamespaceManager.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus); if (!nsManager.QueueExists(QueueName)) nsManager.CreateQueue(QueueName); _client = QueueClient.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus, QueueName); _client.PrefetchCount = 10; var eventDrivenMessagingOptions = new OnMessageOptions { AutoComplete = true, MaxConcurrentCalls = 10 }; eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived; Console.WriteLine(" > {0} - Sending {1} test messages", DateTime.Now, MsgsToSend); Stopwatch.Start(); SendMessages(); Stopwatch.Stop(); Console.WriteLine(" > {0} - {1} of {2} sent in {3} ms", DateTime.Now, MsgsToSend, MsgsToSend, Stopwatch.ElapsedMilliseconds); Thread.Sleep(2000); Console.WriteLine(" > {0} - Recieving {1} test messages", DateTime.Now, MsgsToSend); Stopwatch.Restart(); _client.OnMessage(OnMessageArrived, eventDrivenMessagingOptions); Console.WriteLine("Press any key to close connection"); } catch (Exception ex) { Console.WriteLine(" > Exception received: {0}", ex.Message); } finally { Console.ReadLine(); _client.Close(); } Console.WriteLine("Press any key to close application"); Console.ReadLine(); }
static void Main(string[] args) { CreateQueue(); queueClient = QueueClient.Create(queueName, ReceiveMode.PeekLock); Console.Out.WriteLine("Queue client receive mode is " + queueClient.Mode.ToString()); try { while (true) { long msgCount = nsMgr.GetQueue(queueName).MessageCountDetails.ActiveMessageCount; Console.Out.WriteLine("Ready for messages... "); if (msgCount > 0) { Console.Out.WriteLine("The queue has " + msgCount + " messages waiting"); } var msg = queueClient.Receive(new TimeSpan(1, 0, 0)); Console.Out.WriteLine("Received message with id {0}", msg.MessageId); Messages.Greeting greeting = msg.GetBody<Messages.Greeting>(); Console.Out.WriteLine("Message for: {0}", greeting.Name ); Console.Out.WriteLine("{0}\n", greeting.Message); if (queueClient.Mode == ReceiveMode.PeekLock) { try { Console.Out.WriteLine("Completing message with lock token {0}", msg.LockToken); queueClient.Complete(msg.LockToken); } catch (MessageLockLostException) { Console.Out.WriteLine("Oh noes! We lost the lock on the message. "); } } Console.Out.WriteLine(); } } finally { queueClient.Close(); } }
static void Main(string[] args) { try { //String serviceBusNamespace = "azuretest-ns"; //String keyname = "RootManageSharedAccessKey"; //String key = "3HzV1a5bcs/OOj0YS+Iec7XPA9ys2s9oqrUrg8pcILA="; //String connectionString = @"Endpoint=sb://" + // serviceBusNamespace + // @".servicebus.chinacloudapi.cn/;SharedAccessKeyName=" + // keyname + @";SharedSecretValue=" + key; String connectionString = @"Endpoint=sb://azuretest-ns.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=3HzV1a5bcs/OOj0YS+Iec7XPA9ys2s9oqrUrg8pcILA="; int numCities = 10; // Use as the default, if no value is specified // at the command line. if (args.Count() != 0) { if (args[0].ToLower().CompareTo("createqueue") == 0) { // No processing to occur other than creating the queue. namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); namespaceManager.CreateQueue(queueName); Console.WriteLine("Queue named {0} was created.", queueName); Environment.Exit(0); } if (args[0].ToLower().CompareTo("deletequeue") == 0) { // No processing to occur other than deleting the queue. namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); namespaceManager.DeleteQueue("TSPQueue"); Console.WriteLine("Queue named {0} was deleted.", queueName); Environment.Exit(0); } // Neither creating or deleting a queue. // Assume the value passed in is the number of cities to solve. numCities = Convert.ToInt32(args[0]); } Console.WriteLine("Running for {0} cities.", numCities); queueClient = QueueClient.CreateFromConnectionString(connectionString, "TSPQueue"); List<int> startCities = new List<int>(); List<int> restCities = new List<int>(); startCities.Add(0); for (int i = 1; i < numCities; i++) { restCities.Add(i); } distances = new double[numCities, numCities]; cityNames = new String[numCities]; BuildDistances(@"c:\tsp\cities.txt", numCities); minDistance = -1; bestOrder = new int[numCities]; permutation(startCities, 0, restCities); Console.WriteLine("Final solution found!"); queueClient.Send(new BrokeredMessage("Complete")); queueClient.Close(); Environment.Exit(0); } catch (ServerBusyException serverBusyException) { Console.WriteLine("ServerBusyException encountered"); Console.WriteLine(serverBusyException.Message); Console.WriteLine(serverBusyException.StackTrace); Environment.Exit(-1); } catch (ServerErrorException serverErrorException) { Console.WriteLine("ServerErrorException encountered"); Console.WriteLine(serverErrorException.Message); Console.WriteLine(serverErrorException.StackTrace); Environment.Exit(-1); } catch (Exception exception) { Console.WriteLine("Exception encountered"); Console.WriteLine(exception.Message); Console.WriteLine(exception.StackTrace); Environment.Exit(-1); } }
static void CloseQueueClient(QueueClient queueClientToClose) { try { queueClientToClose.Close(); } catch (Exception) { // ignored because we don't care! } }