示例#1
0
        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();
        }
示例#2
0
        public void SendMessage(string body, IDictionary <string, object> responseProperties = null)
        {
            var SBconnectionString = ConnectionStrings.GetConnectionString(ConnectionStrings.Key.ServiceBusConnectionString);

            topicClient = TopicClient.CreateFromConnectionString(SBconnectionString, TopicName);
            //topicClient = TopicClient.Create(TopicName);
            BrokeredMessage message = CreateMessage(body, responseProperties);

            try
            {
                topicClient.Send(message);
            }
            catch (MessagingException e)
            {
                if (!e.IsTransient)
                {
                    Console.WriteLine(e.Message);
                    throw;
                }
                else
                {
                    HandleTransientErrors(e);
                }
            }
            Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>()));
            topicClient.Close();
        }
示例#3
0
        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;
        }
示例#4
0
        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 string SendTopicMessage(string id)
        {
            //Service Bus接続文字列
            string connectionString = CloudConfigurationManager.GetSetting("ServiceBusConnectionString");
            //Topic名
            string TopicName = CloudConfigurationManager.GetSetting("CommitTopic");
            //Subscription名
            string APISubscriptionName     = CloudConfigurationManager.GetSetting("APISubscription");
            string TriggerSubscriptionName = CloudConfigurationManager.GetSetting("TriggerSubscription");
            //NamespaceManagerの生成
            NamespaceManager nsMan = NamespaceManager.CreateFromConnectionString(connectionString);

            //TopicおよびSubscriptionの存在をチェックし、存在しない場合は新規作成
            if (nsMan.TopicExists(TopicName) == false)
            {
                nsMan.CreateTopic(TopicName);
            }
            if (nsMan.SubscriptionExists(TopicName, APISubscriptionName) == false)
            {
                nsMan.CreateSubscription(TopicName, APISubscriptionName);
            }
            if (nsMan.SubscriptionExists(TopicName, TriggerSubscriptionName) == false)
            {
                nsMan.CreateSubscription(TopicName, TriggerSubscriptionName);
            }
            //Topicクライアントの作成
            TopicClient TClient = TopicClient.CreateFromConnectionString(connectionString, TopicName);

            //Topicにメッセージを送信
            TClient.Send(new BrokeredMessage(id));
            //TopicClientをClose
            TClient.Close();
            return(id);
        }
示例#6
0
        private async Task ForwardCommandMessageToThing(BrokeredMessage bm, Thing thing)
        {
            TopicClient forwardClient    = null;
            var         partition        = thing.Partition;
            var         topicName        = string.Format(PARTITION_COMMAND_TOPIC, thing.RelativeId);
            var         connectionString = ServiceBusConnection.FromIssuer(partition.Namespace, partition.Owner, partition.OwnerSecret);
            var         controlMessage   = bm.GetBody <ControlMessage>();
            var         commandMessage   = new CommandMessage {
                Command = controlMessage.Command, Parameters = controlMessage.Parameters
            };

            try
            {
                forwardClient = TopicClient.CreateFromConnectionString(connectionString, topicName);

                using (var forwardMessage = new BrokeredMessage(commandMessage)
                {
                    ContentType = CommandMessage.CONTENT_TYPE
                })
                {
                    forwardMessage.To      = bm.To;
                    forwardMessage.ReplyTo = bm.ReplyTo;

                    await _messagingPolicy.ExecuteAsync(() => forwardClient.SendAsync(forwardMessage));
                }
            }
            finally
            {
                if (forwardClient != null)
                {
                    _catchAllPolicy.Execute(() => { forwardClient.Close(); });
                }
            }
        }
示例#7
0
        private async Task BroadcastCommandMessageToPartition(BrokeredMessage bm, Partition partition, int[] relativeIds)
        {
            TopicClient forwardClient    = null;
            var         connectionString = ServiceBusConnection.FromIssuer(partition.Namespace, partition.Owner, partition.OwnerSecret);
            var         controlMessage   = bm.GetBody <ControlMessage>();
            var         commandMessage   = new CommandMessage {
                Command = controlMessage.Command, Parameters = controlMessage.Parameters
            };

            foreach (var topicName in relativeIds.Select(id => string.Format(PARTITION_COMMAND_TOPIC, id)))
            {
                try
                {
                    forwardClient = TopicClient.CreateFromConnectionString(connectionString, topicName);

                    using (var forwardMessage = new BrokeredMessage(commandMessage)
                    {
                        ContentType = CommandMessage.CONTENT_TYPE
                    })
                    {
                        forwardMessage.Properties[MessageProperty.BROADCAST] = 0;
                        forwardMessage.ReplyTo = bm.ReplyTo;

                        await _messagingPolicy.ExecuteAsync(() => forwardClient.SendAsync(forwardMessage));
                    }
                }
                finally
                {
                    if (forwardClient != null)
                    {
                        _catchAllPolicy.Execute(() => { forwardClient.Close(); });
                    }
                }
            }
        }
示例#8
0
        void RequestChatSession(string requestToUsername)
        {
            //  Generate a new session ID
            sessionId = Guid.NewGuid().ToString();

            // Provide the client the dynamic session id
            var ack = new
            {
                type      = "ack",
                sessionId = sessionId
            };

            SendText(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(ack)), true);

            // Send a one on one chat request message to the user
            TopicClient     topicClient        = TopicClient.CreateFromConnectionString(serviceBusConnectionString, chatRequestTopicPath);
            BrokeredMessage chatRequestMessage = new BrokeredMessage();

            chatRequestMessage.Properties.Add("RequestTo", requestToUsername);
            chatRequestMessage.Properties.Add("RequestFrom", username);
            chatRequestMessage.Properties.Add("JoinSessionId", sessionId);
            topicClient.Send(chatRequestMessage);
            topicClient.Close();

            JoinChatSession(sessionId);
        }
        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;
                }
            }
        }
示例#10
0
 public void Close()
 {
     if (IsTopicCanUse)
     {
         TopicClient.Close();
         Log.Debug("事件总线已断开连接");
     }
 }
示例#11
0
        public static bool PublishCustomerDataToTopic(string propertyName, string datajson, string topicname)
        {
            TopicClient custTopic = TopicClient.CreateFromConnectionString(_azureConnStr, topicname);
            var         topicMsg  = new BrokeredMessage();

            topicMsg.Properties.Add(propertyName, datajson);
            custTopic.Send(topicMsg);
            custTopic.Close();
            return(true);
        }
 public override void Dispose()
 {
     if (_topicClient != null && !_topicClient.IsClosed)
     {
         _topicClient.Close();
     }
     if (_subscriptionClient != null && !_subscriptionClient.IsClosed)
     {
         _subscriptionClient.Close();
     }
 }
示例#13
0
        public override void OnStop()
        {
            Trace.TraceInformation("Sunrise/Sunset worker stopping...");

            // Close the topic connection
            _topicClientProd.Close();
            _topicClientDev.Close();
            _completedEvent.Set();

            base.OnStop();
        }
        protected new virtual void Dispose(bool disposing)
        {
            if (disposing && !_disposed)
            {
                if (_topicClient != null)
                {
                    _topicClient.Close();
                }

                if (_subscriptionClient != null)
                {
                    foreach (KeyValuePair <string, SubscriptionClient> subscriptionClient in _subscriptionClient)
                    {
                        _logger.WriteInfo(new LogMessage(string.Concat("Subscription ", subscriptionClient.Key, " has been deactivated")), LogCategories);
                        subscriptionClient.Value.Close();
                    }
                    _subscriptionClient.Clear();
                }
                _disposed = true;
            }
        }
示例#15
0
        public void Dispose()
        {
            foreach (var subscriberType in SubscriberClients)
            {
                Unsubscribe(subscriberType.Key);
            }

            if (_topicClient != null)
            {
                _topicClient.Close();
            }
        }
示例#16
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _topicClient.Close();
                }

                disposedValue = true;
            }
        }
示例#17
0
        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");
        }
示例#18
0
        private void CloseClients()
        {
            if (_subscriptionClient != null)
            {
                _catchAllPolicy.Execute(() => { _subscriptionClient.Close(); });
            }

            if (_topicClient != null)
            {
                _catchAllPolicy.Execute(() => { _topicClient.Close(); });
            }

            _subscriptionClient = null;
            _topicClient        = null;
        }
示例#19
0
 public void Stop()
 {
     if (_WorkTask != null)
     {
         MessageQueue.CompleteAdding();
         if (_WorkTask.Wait(2000))
         {
             _topicClient.Close();
             _WorkTask.Dispose();
         }
         else
         {
             _logger.ErrorFormat("consumer can't be stopped!");
         }
     }
 }
示例#20
0
        public override void OnStop()
        {
            _onStopCalled = true;
            while (_returnedFromRunMethod == false)
            {
                Thread.Sleep(1000);
            }

            _topicClient.Close();
            _stockQuantityAggregateStore.Dispose();

            _telemetryClient.Flush();

            Thread.Sleep(1000);
            base.OnStop();
        }
示例#21
0
        private void CloseTopicClient()
        {
            if (_topicClient == null)
            {
                return;
            }

            using (_lock.Lock()) {
                if (_topicClient == null)
                {
                    return;
                }

                _topicClient?.Close();
                _topicClient = null;
            }
        }
示例#22
0
        /// <summary>
        /// Triggers settings checking on the provided <paramref name="serviceBusPublisher"/> and <paramref name="serviceBusReceivers"/>,
        /// then calls <see cref="InstantiateReceiving()"/>.
        /// </summary>
        protected virtual void TriggerSettingsChecking(TopicClient serviceBusPublisher, IDictionary <int, IMessageReceiver> serviceBusReceivers)
        {
            // Let's wrap up using this message bus and start the switch
            if (serviceBusPublisher != null)
            {
#if NET452
                serviceBusPublisher.Close();
#endif
#if NETSTANDARD2_0
                serviceBusPublisher.CloseAsync().Wait(1500);
#endif
                Logger.LogDebug("Publishing service bus closed.");
            }
            foreach (IMessageReceiver serviceBusReceiver in serviceBusReceivers.Values)
            {
                // Let's wrap up using this message bus and start the switch
                if (serviceBusReceiver != null)
                {
#if NET452
                    serviceBusReceiver.Close();
#endif
#if NETSTANDARD2_0
                    serviceBusReceiver.CloseAsync().Wait(1500);
#endif
                    Logger.LogDebug("Receiving service bus closed.");
                }
                // Restart configuration, we order this intentionally with the receiver first as if this triggers the cancellation we know this isn't a publisher as well
                if (serviceBusReceiver != null)
                {
                    Logger.LogDebug("Recursively calling into InstantiateReceiving.");
                    InstantiateReceiving();

                    // This will be the case of a connection setting change re-connection
                    if (ReceiverMessageHandler != null && ReceiverMessageHandlerOptions != null)
                    {
                        // Callback to handle received messages
                        Logger.LogDebug("Re-registering onMessage handler.");
                        ApplyReceiverMessageHandler();
                    }
                    else
                    {
                        Logger.LogWarning("No onMessage handler was found to re-bind.");
                    }
                }
            }
        }
        /// <summary>
        /// Send message to the topic
        /// </summary>
        /// <param name="topicClient"></param>
        private static void SendMessage(MessagingFactory factory, TopicClient topicClient)
        {
            // Send a message saying the user has just entered the chat application
            var message = new BrokeredMessage($" {Username} has entered the room...")
            {
                Label = Username
            };

            topicClient.Send(message);

            while (true)
            {
                var text = Console.ReadLine();

                if (text.Equals("exit"))
                {
                    break;
                }
                else
                {
                    message = new BrokeredMessage(text)
                    {
                        Label = Username
                    };

                    topicClient.Send(message);
                }
            }

            // Send a message saying the user has just entered the chat application
            message = new BrokeredMessage($" {Username} has left the room...")
            {
                Label = Username
            };

            topicClient.Send(message);

            // Close the factory and all the clients it created
            factory.Close();

            // Close and release the topic client
            topicClient.Close();

            //topicClient.MessagingFactory.Close();
        }
        /// <summary>
        /// Sends a message to service bus.
        /// </summary>
        /// <param name="message">The message to send.</param>
        public void SendMessage(NodeMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var brokeredMessage = this.MessageConverter.ConvertToBrokeredMessage(message);

            bool            firstTry = true;
            Action <object> retrySendMessageAction = null;
            var             sendMessageAction      = new Action <object>(
                bm =>
            {
                TopicClient topicClient = null;
                try
                {
                    topicClient = TopicClient.CreateFromConnectionString(this.connectionString, topicName);
                    topicClient.Send((BrokeredMessage)bm);
                }
                catch (Exception)
                {
                    if (firstTry)
                    {
                        Task.Factory.StartNew(retrySendMessageAction, bm);
                    }
                    else
                    {
                        firstTry = false;
                    }
                }
                finally
                {
                    if (topicClient != null)
                    {
                        topicClient.Close();
                    }
                }
            });

            retrySendMessageAction = sendMessageAction;
            Task.Factory.StartNew(sendMessageAction, brokeredMessage);
        }
示例#25
0
        private static void SendMessages()
        {
            topicClient = TopicClient.Create(TopicName);

            List <BrokeredMessage> messageList = new List <BrokeredMessage>();

            messageList.Add(CreateSampleMessage("1", "First message information"));
            messageList.Add(CreateSampleMessage("2", "Second message information"));
            messageList.Add(CreateSampleMessage("3", "Third message information"));
            messageList.Add(CreateSampleMessage("4", "Fourth message information"));
            messageList.Add(CreateSampleMessage("5", "Fifth message information"));

            Console.WriteLine("\nSending messages to topic...");


            foreach (BrokeredMessage message in messageList)
            {
                while (true)
                {
                    try
                    {
                        topicClient.Send(message);
                    }
                    catch (MessagingException e)
                    {
                        if (!e.IsTransient)
                        {
                            Console.WriteLine(e.Message);
                            throw;
                        }
                        else
                        {
                            HandleTransientErrors(e);
                        }
                    }
                    Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>()));
                    break;
                }
            }

            topicClient.Close();
        }
示例#26
0
        static void Main(string[] args)
        {
            string sbConnectionString =
                "YOURSERVICEBUSCONNECTIONSTRING";

            string topicName = "SimpleTopic";

            var namespaceManager = NamespaceManager.CreateFromConnectionString(sbConnectionString);


            TopicDescription topicDescription = null;

            if (!namespaceManager.TopicExists(topicName))
            {
                topicDescription = namespaceManager.CreateTopic(topicName);
            }
            else
            {
                topicDescription = namespaceManager.GetTopic(topicName);
            }

            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(sbConnectionString);
            TopicClient      topicClient = factory.CreateTopicClient(topicDescription.Path);

            CreateSubscription(namespaceManager, factory, topicName, "Subscription1");
            CreateSubscription(namespaceManager, factory, topicName, "Subscription2");
            //CreateSubscription(namespaceManager, factory, topicName, "Subscription2");

            Console.WriteLine("Message à envoyer : ");
            string message = Console.ReadLine();

            while (message != "exit")
            {
                topicClient.Send(new BrokeredMessage(message));

                Console.WriteLine("Message à envoyer : ");
                message = Console.ReadLine();
            }

            topicClient.Close();
        }
        private void SendSubscriptionIsAliveMessage()
        {
            var message = new BrokeredMessage();

            message.Properties[SubscriptionPingPropertyName] = DateTime.UtcNow;
            message.Properties[ServiceBus.MessageConverter.SenderIdPropertyName] = this.nodeId;
            TopicClient topicClient = null;

            try
            {
                topicClient = TopicClient.CreateFromConnectionString(this.connectionString, this.topicName);
                topicClient.Send(message);
            }
            finally
            {
                if (topicClient != null)
                {
                    topicClient.Close();
                }
            }
        }
示例#28
0
        private void SendMessageToTopic(BrokeredMessage msg)
        {
            bool done = false;

            for (int retryCount = 1; !done; retryCount++)
            {
                done = true;
                try
                {
                    outputTopic = TopicClient.CreateFromConnectionString(cloudConfig.ServiceBusConnectionString.value, CloudConstants.ResultsTopicName);
                    outputTopic.Send(msg);
                    outputTopic.Close();
                }
                catch (Exception)
                {
                    if (retryCount == CloudConstants.MaxRetries)
                    {
                        throw;
                    }
                    done = false;
                    System.Threading.Thread.Sleep(CloudConstants.RetryBackoffInterval);
                }
            }
        }
示例#29
0
        public override void OnStop()
        {
            // Close the connection to Service Bus Queue
            _cancellationTokenSource.Cancel();

            Thread.Sleep(1000 * _maximumConcurrency);

            _cancellationTokenSource.Dispose();

            _completeManualResetEvent.Set();

            //_subscriptionClient.Close();
            _warehouseAvailableStockChangedReceiver.Dispose();

            _topicClient.Close();

            _stockQuantityAggregateStore.Dispose();

            _telemetryClient.Flush();

            Thread.Sleep(1000);

            base.OnStop();
        }
示例#30
0
        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.");
            }
        }
示例#31
0
        private static void SendMessages()
        {
            topicClient = TopicClient.Create(TopicName);

            List<BrokeredMessage> messageList = new List<BrokeredMessage>();
            messageList.Add(CreateSampleMessage("1", "First message information"));
            messageList.Add(CreateSampleMessage("2", "Second message information"));
            messageList.Add(CreateSampleMessage("3", "Third message information"));
            messageList.Add(CreateSampleMessage("4", "Fourth message information"));
            messageList.Add(CreateSampleMessage("5", "Fifth message information"));

            Console.WriteLine("\nSending messages to topic...");

            foreach (BrokeredMessage message in messageList)
            {
                while (true)
                {
                    try
                    {
                        topicClient.Send(message);
                    }
                    catch (MessagingException e)
                    {
                        if (!e.IsTransient)
                        {
                            Console.WriteLine(e.Message);
                            throw;
                        }
                        else
                        {
                            HandleTransientErrors(e);
                        }
                    }
                    Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
                    break;
                }
            }

            topicClient.Close();
        }