public void WebsitesPeriodeCheck(object sender, WebsiteSettingsChangedEventArgs args) { if (Runner.Status == TaskStatus.Faulted) { Client.Close(); CompletedEvent.Set(); CompletedEvent = new ManualResetEvent(false); Runner = Task.Factory.StartNew(StartSubscriptionClient, TaskCreationOptions.LongRunning); } }
public override void OnStop() { // Close the connection to Service Bus Queue Client.Close(); CompletedEvent.Set(); base.OnStop(); }
// 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(); } }
public async Task Run(OnMessageOptions topicOptions) { while (true) { var message = _deadLetter.Receive(); if (message == null) { break; } var context = message.GetBody <RemoteExecutionContext>(CrmPluginBrokerRole.ExecutionContextSerializer); try { await PassContextToPlugins(context); } catch (Exception) { Trace.TraceError("Failing dead-letter message: {0}({1}) {2}", context.PrimaryEntityName, context.PrimaryEntityId, context.MessageName); throw; } } _deadLetter.Close(); _topic.OnMessageAsync(OnTopicMessageAsync, topicOptions); }
public void ConnectOrDisconnect(string username) { bool isConnecting = !IsConnected; IsConnected = !IsConnected; if (isConnecting) { //let´s create a new SenderID _senderId = Guid.NewGuid(); var subscription = _busClient.CreateSubscription(_topicName, _senderId.ToString()); //The subscription will delete itself when iddle more than 5 minutes! //That will be used case the application crashes subscription.AutoDeleteOnIdle = new TimeSpan(0, 5, 0); //Now we will use the subscription we just created and will create a Subscription Client //The idea is to print all messages that we receive! _currentSubscription = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicName, _senderId.ToString()); _currentSubscription.OnMessage(WhenMessageArrives); //Sending has joined message Send("**just joined**"); } else { //Close subscription Client _currentSubscription.Close(); //Then Remove it _busClient.DeleteSubscription(_topicName, _senderId.ToString()); } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { try { if (subscriptionClient != null) { log.Info("Closing subscription client"); subscriptionClient.Close(); } } catch (Exception e) { log.Warn("An exception occurred while closing the subscription client: {0}", e); } try { log.Info("Closing topic client"); topicClient.Close(); } catch (Exception e) { log.Warn("An exception occurred while closing the topic client: {0}", e); } } disposed = true; }
/// <summary> /// Creates <see cref="AzureBus{TAuthenticationToken}.NumberOfReceiversCount"/> <see cref="SubscriptionClient"/>. /// If flushing is required, any flushed <see cref="SubscriptionClient"/> has <see cref="ClientEntity.Close()"/> called on it first. /// </summary> /// <param name="namespaceManager">The <see cref="NamespaceManager"/>.</param> /// <param name="serviceBusReceivers">The receivers collection to place <see cref="SubscriptionClient"/> instances into.</param> /// <param name="topicName">The topic name.</param> /// <param name="topicSubscriptionName">The topic subscription name.</param> protected virtual void InstantiateReceiving(NamespaceManager namespaceManager, IDictionary <int, SubscriptionClient> serviceBusReceivers, string topicName, string topicSubscriptionName) { for (int i = 0; i < NumberOfReceiversCount; i++) { SubscriptionClient serviceBusReceiver = SubscriptionClient.CreateFromConnectionString(ConnectionString, topicName, topicSubscriptionName); if (serviceBusReceivers.ContainsKey(i)) { serviceBusReceivers[i] = serviceBusReceiver; } else { serviceBusReceivers.Add(i, serviceBusReceiver); } } // Remove any if the number has decreased for (int i = NumberOfReceiversCount; i < serviceBusReceivers.Count; i++) { SubscriptionClient serviceBusReceiver; if (serviceBusReceivers.TryGetValue(i, out serviceBusReceiver)) { serviceBusReceiver.Close(); } serviceBusReceivers.Remove(i); } }
public void getQueueValue(string strEndpoint, string strTopicName, string subscriptionName) { var connectionString = strEndpoint; var queueName = strTopicName; ViewBag.Endpoint = connectionString; ViewBag.QueueName = queueName; SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(strEndpoint, strTopicName, subscriptionName); var msg3 = ""; BrokeredMessage message = null; NamespaceManager namespaceManager = NamespaceManager.Create(); while (true) { try { //receive messages from Queue message = client.Receive(TimeSpan.FromSeconds(5)); ViewBag.Msg12 = "No active message is avilable in service bus queue."; if (message != null) { //Console.WriteLine(string.Format("Message received: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>())); var t = message.MessageId; if (msg3 == "") { msg3 = message.GetBody <string>(); } else { msg3 = msg3 + ", " + message.GetBody <string>(); } message.Complete(); ViewBag.Msg12 = ""; // break; } else { //msg3 = ""; break; } } catch (MessagingException e) { if (!e.IsTransient) { Console.WriteLine(e.Message); throw; } else { //HandleTransientErrors(e); } } } client.Close(); ViewBag.Qmsg4 = msg3; }
public void IsClosedCorrectlyReflectsStateOfObject() { var ip = "1.1.1.1"; var port = 1883; var eventData = "Test data"; string connectionKey = "123"; var moqSocket = new MoqSocket(); var protocol = new MqttClientProtocol(new LogCompositor(), moqSocket); var bldr = new MqttConnectMessageBuilder { ClientId = "UnitTest" }; protocol.ConnectAsync(bldr, ip, port, SocketEncryption.None, eventData); var subscriptionItem = new SubscriptionItem { TopicName = "a/b/+", QualityOfService = QualityOfService.AtMostOnce }; var subClient = new SubscriptionClient(protocol, subscriptionItem, connectionKey); Assert.IsTrue(subClient.IsClosed); subClient.OnMessage(msg => { Assert.IsNotNull(msg); Assert.IsTrue(msg.MessageType == MessageType.Publish); }); Assert.IsFalse(subClient.IsClosed); subClient.Close(); Assert.IsTrue(subClient.IsClosed); }
public override void OnStop() { // Close the connection to Service Bus Queue _isStopped = true; _subscriptionClient.Close(); base.OnStop(); }
public void Dispose() { if (!_client.IsClosed) { _client.Close(); } }
private void Stop() { if (_client != null && !_client.IsClosed) { _client.Close(); _client = null; } }
private void CloseClient() { if (_client != null && !_client.IsClosed) { _client.Close(); } _clientOpen = false; }
protected void Application_End() { if (_topicClient != null) { _topicClient.Close(); } _completedEvent.Set(); }
void DisconnectFromChatSession(string sessionId) { SayGoodBye(sessionId); //Delete the subscription and close the client namespaceManager.DeleteSubscription(chatTopicPath, chatSessionSubscriptionName); chatSessionClient.Close(); }
public override void Dispose() { if (_topicClient != null && !_topicClient.IsClosed) { _topicClient.Close(); } if (_subscriptionClient != null && !_subscriptionClient.IsClosed) { _subscriptionClient.Close(); } }
public static string GetCustomerDataFromSubscription(string topicName, string subscriptionName) { //NamespaceManager manager = NamespaceManager.CreateFromConnectionString(_azureConnStr); //var subscriptions = manager.GetSubscriptions(topicName); SubscriptionClient sbClient = SubscriptionClient.CreateFromConnectionString(_azureConnStr, topicName, subscriptionName); BrokeredMessage message = sbClient.Receive(); var custData = message.Properties["Customer"].ToString(); message.Complete(); sbClient.Close(); return(custData); }
private void ProcessTopic(string topic) { _activityLogger.Log($"[{topic}] - Processing topic ", 0, 1); // get subscriptions in source topic var subscriptions = _sourceNamespaceManager.GetSubscriptions(topic); _activityLogger.Log($"[{topic}] - {subscriptions.Count()} subscription(s) found"); // forward messages in each subscription to destination topic foreach (var subscription in subscriptions) { SubscriptionClient subscriptionClient = null; TopicClient destinationTopicClient = null; try { if (IsSubscriptionIgnored(subscription.Name)) { _activityLogger.Log($"Ignoring subscription: [{topic}].[{subscription.Name}]"); } else { subscriptionClient = SubscriptionClient.CreateFromConnectionString(_sourceConnectionString, topic, subscription.Name); destinationTopicClient = TopicClient.CreateFromConnectionString(_destinationConnectionString, topic); if (subscription.RequiresSession) { _subscriptionMessageForwarder.ProcessSessionSubscription(subscriptionClient, destinationTopicClient); } else { _subscriptionMessageForwarder.ProcessSubscription(subscriptionClient, destinationTopicClient); } } } catch (Exception e) { _activityLogger.Log($"! Exception processing [{topic}].[{subscription.Name}] subscription: {e.Message}\n\n", 0, 2); } finally { subscriptionClient?.Close(); destinationTopicClient?.Close(); } } _activityLogger.Log($"[{topic}] - Completed processing topic"); }
private void CloseClients() { if (_subscriptionClient != null) { _catchAllPolicy.Execute(() => { _subscriptionClient.Close(); }); } if (_topicClient != null) { _catchAllPolicy.Execute(() => { _topicClient.Close(); }); } _subscriptionClient = null; _topicClient = null; }
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(); }
private void UnsubscribetButton_OnClick(object sender, RoutedEventArgs e) { try { if (_subscriptions.ContainsKey(PublishTopic.Text)) { SubscriptionClient subClient = _subscriptions[PublishTopic.Text]; subClient.Close(); _subscriptions.Remove(PublishTopic.Text); } AppendLogMessage(MessageLevel.Info, "Successfully unsubscribed to topic."); } catch (Exception ex) { AppendLogMessage(MessageLevel.Error, "ERROR: Unsubscribe failed with error: " + ex.Message); } }
private void CloseSubscriptionClient() { if (_subscriptionClient == null) { return; } using (_lock.Lock()) { if (_subscriptionClient == null) { return; } _subscriptionClient?.Close(); _subscriptionClient = null; } }
private void CloseSubscriptionClients() { if (_controlClient != null) { _catchAllPolicy.Execute(() => { _controlClient.Close(); }); } if (_analyticsClient != null) { _catchAllPolicy.Execute(() => { _analyticsClient.Close(); }); } if (_eventClient != null) { _catchAllPolicy.Execute(() => { _eventClient.Close(); }); } _controlClient = _analyticsClient = _eventClient = null; }
//Receive message from Fascia Topic public static void ReceiveMessages() { string TopicName = CloudConfigurationManager.GetSetting("AlertTopicName"); string SubscriptionName = CloudConfigurationManager.GetSetting("SubscriptionName"); bool SMSAlert = Convert.ToBoolean(CloudConfigurationManager.GetSetting("SMSAlert")); bool PushNotification = Convert.ToBoolean(CloudConfigurationManager.GetSetting("PushNotification")); BrokeredMessage message = null; // For ReceiveAndDelete mode, where applications require "best effort" delivery of messages SubscriptionClient alertSubscriptionClient = SubscriptionClient.Create(TopicName, SubscriptionName, ReceiveMode.ReceiveAndDelete); while (true) { try { message = alertSubscriptionClient.Receive(TimeSpan.FromSeconds(5)); if (message != null) { string messageBody = message.GetBody <string>(); if (PushNotification) { PushGCMNotificationAsync(messageBody); } if (SMSAlert) { SendTwilioSMSNotification(messageBody); } } else { break; } } catch (MessagingException e) { Console.WriteLine(e.Message); } } alertSubscriptionClient.Close(); }
// Read the first published message from service bus subscription public string ReadFirstPublishedMessage(string ServiceBusConnectionString, string TopicName, string SubscriptionName, ref long messageCount) { // 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 messageCount = subscriptionDesc.MessageCount; // Skip reading 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 Peek function to keep the brokerd message in the subscription BrokeredMessage MessageReceived = mySubscriptionClient.Peek(); // Retrieve message body as a stream object Stream myMessage = MessageReceived.GetBody <Stream>(); // Convert the stream object into a byte array Byte[] ByteData = StreamToByteArray(myMessage); // Convert UTF8 encoded byte array into message text string strData = Encoding.UTF8.GetString(ByteData); // Clean up MessageReceived.Dispose(); mySubscriptionClient.Close(); return(strData); } return(""); }
public void OnMessageCallbackDoesNotGetCalledAfterClose() { var are = new AutoResetEvent(false); var ip = "1.1.1.1"; var port = 1883; var eventData = "Test data"; string connectionKey = "123"; var moqSocket = new MoqSocket(); var protocol = new MqttClientProtocol(new LogCompositor(), moqSocket); var bldr = new MqttConnectMessageBuilder { ClientId = "UnitTest" }; protocol.ConnectAsync(bldr, ip, port, SocketEncryption.None, eventData); var subscriptionItem = new SubscriptionItem { TopicName = "a/b/c", QualityOfService = QualityOfService.AtMostOnce }; var subClient = new SubscriptionClient(protocol, subscriptionItem, connectionKey); subClient.OnMessage(msg => { Assert.Fail("OnMessage callback was called after Close call."); are.Set(); }); subClient.Close(); moqSocket.ReceiveMessage(new MqttPublishMessageBuilder { TopicName = "a/b/c", Payload = new byte[] { 0x00, 0x01, 0x02 } }); are.WaitOne(3000); }
static void RecieveMessagesFromSubscriptions(string topic, string subscription) { List <HomeVehicle> homeAndVehiclemessages = new List <HomeVehicle>(); Console.WriteLine("Recieving messages for {0}", subscription); //create subscription client in peeklock mode SubscriptionClient homeandVehicleSubscriptionClient = factory.CreateSubscriptionClient(topic, subscription, ReceiveMode.PeekLock); Console.WriteLine("Recieving Messages"); BrokeredMessage message; while ((message = homeandVehicleSubscriptionClient.Receive(new TimeSpan(0, 0, 1))) != null) { var homeAndVehiclemessage = message.GetBody <HomeVehicle>(); Console.WriteLine(" Recieved: {0},{1},{2}", message.SequenceNumber, message.MessageId, homeAndVehiclemessage.ToString()); homeAndVehiclemessages.Add(homeAndVehiclemessage); message.Complete(); } Console.WriteLine(" Recieved {0} Messages", homeAndVehiclemessages.Count); homeandVehicleSubscriptionClient.Close(); }
public void Stop() { _exit = true; if (_subscriptionConsumeTask != null) { _replySubscriptionClient.Close(); if (!_subscriptionConsumeTask.Wait(1000)) { _logger.ErrorFormat("receiver can't be stopped!"); } } if (_sendCommandWorkTask != null) { _toBeSentCommandQueue.CompleteAdding(); if (_sendCommandWorkTask.Wait(2000)) { _sendCommandWorkTask.Dispose(); } else { _logger.ErrorFormat(" consumer can't be stopped!"); } } }
protected virtual void Dispose(bool disposing) { if (disposing && !_isDisposed) { Log.Debug($"Disposing channel {_identifier}."); _isDisposed = true; _masterShutdownTokenRegistration.Dispose(); if (_subscriptionClient != null) { _subscriptionClient.Close(); _subscriptionClient = null; } if (_topicClient != null) { _topicClient.Close(); _topicClient = null; } Log.Debug($"Channel {_identifier} disposed."); } }
protected override void OnNavigatedFrom(NavigationEventArgs e) { _subClient.Close(); base.OnNavigatedFrom(e); }