示例#1
0
        public EventTopicPublisher(string connectionString, TopicDescription topic, ITimeProvider timeProvider, ILogger logger)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.TopicExists(topic.Path))
            {
                namespaceManager.CreateTopic(topic);
            }

            _client       = TopicClient.CreateFromConnectionString(connectionString, topic.Path);
            _timeProvider = timeProvider;
            _logger       = logger;
        }
        public void Send(Message message)
        {
            EnsureTopicExists(message.Header.Topic);

            var brokeredMessage = BuildBrokeredMessage(message);

            TopicClient
            .CreateFromConnectionString(_connectionString, message.Header.Topic)
            .Send(brokeredMessage);

            _logger.Value.DebugFormat("Published message {0} to topic {1}.",
                                      message.Id, message.Header.Topic);
        }
示例#3
0
        static void TestSendCommand()
        {
            TopicClient commandClient = TopicClient.CreateFromConnectionString(serviceBusConnectionString, commandTopicPath);
            TopicSender sender        = new TopicSender(commandClient);
            //sender.Send( () => { return new BrokeredMessage( "Hello CQRS" ); } );
            ITextSerializer serializer = new JsonTextSerializer();
            CommandBus      bus        = new CommandBus(sender, serializer);

            bus.Send(new Envelope <ICommand>(new PlaceOrder()
            {
                ProductId = 1, Quantity = 10
            }));
        }
        TopicClient GetTopicClient(string topic)
        {
            return(_topicClients.GetOrAdd(topic, t =>
            {
                _log.Debug("Initializing new topic client for {0}", topic);

                var topicDescription = EnsureTopicExists(topic);

                var fromConnectionString = TopicClient.CreateFromConnectionString(_connectionString, topicDescription.Path);

                return fromConnectionString;
            }));
        }
示例#5
0
        static void Main(string[] args)
        {
            string           connectionStr = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            NamespaceManager nsm           = NamespaceManager.CreateFromConnectionString(connectionStr);
            string           topicName     = "yolitopic";
            TopicDescription topic         = null;

            if (!nsm.TopicExists(topicName))
            {
                nsm.CreateTopic(new TopicDescription(topicName)
                {
                    EnablePartitioning = false
                });
            }

            topic = nsm.GetTopic(topicName);

            if (topic.SubscriptionCount == 0)
            {
                SqlFilter filter1 = new SqlFilter("(index % 2) = 0");
                nsm.CreateSubscription(topic.Path, "YoliSubscription1", filter1);
                SqlFilter filter2 = new SqlFilter("(index % 2) > 0");
                nsm.CreateSubscription(topic.Path, "YoliSubscription2", filter2);
            }
            //
            //sadfsdf

            foreach (var s in nsm.GetSubscriptions(topicName))
            {
                Console.WriteLine(s.Name);
                foreach (var r in nsm.GetRules(topic.Path, s.Name))
                {
                    Console.WriteLine("{0}-{1}", r.Name, r.Filter.ToString());
                }
            }

            Console.WriteLine("Sending message to topic");

            TopicClient topicClient = TopicClient.CreateFromConnectionString(connectionStr, topicName);

            for (int i = 0; i < 5000; i++)
            {
                BrokeredMessage message = new BrokeredMessage();
                message.Properties["index"] = i;
                message.Properties["value"] = (i * 10 + 5) % 11;
                topicClient.Send(message);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        public void SendWithDelay(Message message, int delayMilliseconds = 0)
        {
            EnsureTopicExists(message.Header.Topic);

            var brokeredMessage      = BuildBrokeredMessage(message);
            var scheduledEnqueueTime = DateTime.UtcNow.AddMilliseconds(delayMilliseconds);

            TopicClient
            .CreateFromConnectionString(_connectionString, message.Header.Topic)
            .ScheduleMessageAsync(brokeredMessage, scheduledEnqueueTime);

            _logger.Value.DebugFormat("Published message {0} with delay of {1} ms to topic {2}.",
                                      message.Id, delayMilliseconds, message.Header.Topic);
        }
示例#7
0
        public static void Init(IEnumerable <string> nodes, ref List <QueueClient> queueClients, out TopicClient topicClient, out QueueClient frontendClient)
        {
            // Node Events Queues
            foreach (var connectionString in nodes.Select(CloudConfigurationManager.GetSetting))
            {
                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    throw new NotImplementedException("Connection String can not be blank");
                }

                var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                if (!namespaceManager.QueueExists(ServiceBusPathNames.ServiceBusEventQueue))
                {
                    namespaceManager.CreateQueue(ServiceBusPathNames.ServiceBusEventQueue);
                }

                queueClients.Add(QueueClient.CreateFromConnectionString(connectionString, ServiceBusPathNames.ServiceBusEventQueue));
            }

            var workerConn      = CloudConfigurationManager.GetSetting(ServiceBusConnectionStrings.WorkerServiceBusConnection);
            var workerNamespace = NamespaceManager.CreateFromConnectionString(workerConn);

            if (string.IsNullOrWhiteSpace(workerConn))
            {
                throw new NotImplementedException("Connection String can not be blank");
            }

            // Update Node Topic
            if (!workerNamespace.TopicExists(ServiceBusPathNames.ServiceBusUpdateTopic))
            {
                var td = new TopicDescription(ServiceBusPathNames.ServiceBusUpdateTopic)
                {
                    DefaultMessageTimeToLive = new TimeSpan(0, 1, 0) // TTL 1 minute
                };

                workerNamespace.CreateTopic(td);
            }

            topicClient = TopicClient.CreateFromConnectionString(workerConn, ServiceBusPathNames.ServiceBusUpdateTopic);

            // Frontend Notification Queue
            var nm = NamespaceManager.CreateFromConnectionString(workerConn);

            if (!nm.QueueExists(ServiceBusPathNames.ServiceBusUpdateQueue))
            {
                nm.CreateQueue(ServiceBusPathNames.ServiceBusUpdateQueue);
            }

            frontendClient = QueueClient.CreateFromConnectionString(workerConn, ServiceBusPathNames.ServiceBusUpdateQueue);
        }
示例#8
0
        /// <summary>
        /// This method read data from message and send to subscription
        /// </summary>
        /// <param name="message">Input parameter IMessage</param>
        //public void SendMessage(IMessage message)
        public void SendMessage(object message)
        {
            try
            {
                var client = TopicClient.CreateFromConnectionString(ConnectionString, TopicName);

                BrokeredMessage brokeredmessage = new BrokeredMessage(message);

                client.Send(brokeredmessage);
            }
            catch (Exception)
            {
            }
        }
        public static void OutputToTopic(this ProcessorWrapper queueProcessor, string connectionString, string queueName)
        {
            var destTopic = TopicClient.CreateFromConnectionString(connectionString, queueName);
            var sender    = new TopicOutput(destTopic);

            var processor = queueProcessor.QueueProcessor;

            queueProcessor.QueueSource.StartMessagePump(message =>
            {
                processor.ProcessMessages(new List <BrokeredMessage> {
                    message
                }, sender);
            });
        }
示例#10
0
        public void SendJson(string rawJson, RoomConfig config)
        {
            if (!namespaceManager.TopicExists(config.ServiceBusTopic))
            {
                namespaceManager.CreateTopic(config.ServiceBusTopic);
            }

            TopicClient     Client  = TopicClient.CreateFromConnectionString(connectionString, config.ServiceBusTopic);
            BrokeredMessage message = new BrokeredMessage(rawJson);

            message.Properties.Add("Location", config.Location);
            // message.TimeToLive = TimeSpan.FromMinutes(5);
            Client.Send(message);
        }
        public JobHostServiceBus(string connectionString, string commandsForAutoScalerTopicName, string commandsForJobHostTopicName)
        {
            _connectionString = connectionString;
            _commandsForAutoScalerTopicName = commandsForAutoScalerTopicName;
            _commandsForJobHostTopicName    = commandsForJobHostTopicName;

            _commandsForJobHostTopicClient = TopicClient.CreateFromConnectionString(_connectionString,
                                                                                    _commandsForAutoScalerTopicName);
            _commandsForJobHostTopicClient.RetryPolicy = RetryPolicy.Default;

            _commandsForAutoScalerTopicClient = TopicClient.CreateFromConnectionString(_connectionString,
                                                                                       _commandsForAutoScalerTopicName);
            _commandsForAutoScalerTopicClient.RetryPolicy = RetryPolicy.Default;
        }
        public TopicClient CreateTopicClient()
        {
            var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            try
            {
                return(TopicClient.CreateFromConnectionString(connectionString, Constants.TopicName));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
示例#13
0
        static void TestSendEvent()
        {
            TopicClient     eventClient = TopicClient.CreateFromConnectionString(serviceBusConnectionString, orderEventTopicPath);
            TopicSender     sender      = new TopicSender(eventClient);
            ITextSerializer serializer  = new JsonTextSerializer();

            EventBus eventBus = new EventBus(sender, serializer);

            eventBus.Publish(new Envelope <IEvent>(new OrderPlaced()
            {
                ProductId = 1,
                Quantity  = 2,
                SourceId  = Guid.NewGuid()
            }));
        }
示例#14
0
        /// <summary>
        ///     Creates a topic client, as well as the target topic if it does not already exist.
        /// </summary>
        public static TopicClient CreateTopicClient(
            this ServiceBusSettings settings,
            string topicName,
            Action <TopicDescription> configure = null)
        {
            topicName = topicName.PrefixedIfConfigured(settings);
            var topicDescription = new TopicDescription(topicName);

            if (configure != null)
            {
                configure(topicDescription);
            }
            settings.CreateTopicIfDoesNotAlreadyExist(topicDescription);
            return(TopicClient.CreateFromConnectionString(settings.ConnectionString, topicName));
        }
示例#15
0
        private static TopicClient CreateTopicClient(string connectionString, string topic)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            // get the topic or create if it doesn't already exist
            var topicDescription = !namespaceManager.TopicExists(topic) ?
                                   namespaceManager.CreateTopic(topic) :
                                   namespaceManager.GetTopic(topic);

            // set the default TTL
            topicDescription.DefaultMessageTimeToLive = TimeSpan.FromHours(2);
            namespaceManager.UpdateTopic(topicDescription);

            return(TopicClient.CreateFromConnectionString(connectionString, topic));
        }
示例#16
0
        private async Task Execute(CustomerEntity customer)
        {
            // Map the Customer entity in the e-commerce application (source) to Customer record in the partner application (destination)
            CustomerRecord customerRecord = PrepareCustomerRecord(customer);

            // Create a connection to an Azure Service Bus Topic
            // Serialize the customer record and send the message to the Topic
            var client  = TopicClient.CreateFromConnectionString(connectionString, topicName);
            var message = new BrokeredMessage(JsonConvert.SerializeObject(customerRecord));

            // Register the customer record with the Correlation Service and obtain a Correlation ID
            message.Properties["CorrelationId}"] = new CorrelationService().RegisterCustomer(customerRecord, subscriptionName);

            await client.SendAsync(message);
        }
示例#17
0
        public async Task PushAsync(Event message)
        {
            var queueName = new QueueName(message.QueueName);

            if (queueName.IsSimpleQueue)
            {
                var client = QueueClient.CreateFromConnectionString(_connectionString, queueName.TopicName);
                await client.SendAsync(message.ToMessage());
            }
            else
            {
                var client = TopicClient.CreateFromConnectionString(_connectionString, queueName.TopicName);
                await client.SendAsync(message.ToMessage());
            }
        }
        public static void SendCancellationMessage(string jobId, string connectionString, string topicName)
        {
            // Senders should not create the topic to remain settings with which the topic is created, consistent
            // --old -- InitializeTopic();
            var topicClient = TopicClient.CreateFromConnectionString(connectionString, topicName);

            // Create and send the message
            var msg = new BrokeredMessage();

            msg.Properties[GlobalConstants.SERVICEBUS_MESSAGE_PROP_JOBID] = jobId;

            // Send the message to the (existing) topic
            topicClient.RetryPolicy = RetryPolicy.Default;
            topicClient.Send(msg);
        }
        public void DoNotForwardMessageWhenSubscriptionIsInIgnoredList()
        {
            var topicName           = $"_sbmf-{DateTime.UtcNow:yyyyMMddHHmmss}-{new Random().Next(10000, 99999)}";
            var subscriptionName    = "subscription1";
            var ignoreTopics        = "";
            var ignoreSubscriptions = "";

            var sourceClient = TopicClient.CreateFromConnectionString(_sourceConnectionString, topicName);

            "Given a topic exists on the destination bus with 1 subscription".x(() =>
            {
                _destinationNamespaceManager.CreateTopic(topicName);
                _destinationNamespaceManager.CreateSubscription(topicName, subscriptionName);
            });
            "And the source topic has 1 subscription".x(() =>
            {
                _sourceNamespaceManager.CreateTopic(topicName);
                _sourceNamespaceManager.CreateSubscription(topicName, subscriptionName);
            });
            "And the subscription is in the ignored topics list".x(() =>
            {
                ignoreSubscriptions = subscriptionName;
            });
            "And a message is sent to the source topic".x(() =>
            {
                sourceClient.Send(new BrokeredMessage(_testMessage));
            });
            "When the service has run".x(() =>
            {
                new ServiceBusMessageForwarder(_logger, null, _sourceConnectionString, _destinationConnectionString, _ignoreQueues, ignoreTopics, ignoreSubscriptions).Run();
            });
            "Then the message is not forwarded to the destination topic".x(() =>
            {
                var destinationSubscriptionClient = SubscriptionClient.CreateFromConnectionString(_destinationConnectionString, topicName, subscriptionName);
                var messages = destinationSubscriptionClient.PeekBatch(10);

                messages.Count().Should().Be(0);
            });
            "And the message still exists in the source topic's subscription".x(() =>
            {
                var sourceSubscriptionClient = SubscriptionClient.CreateFromConnectionString(_sourceConnectionString, topicName, subscriptionName);
                var messages = sourceSubscriptionClient.PeekBatch(10);
                messages.Count().Should().Be(1);
                messages.First().GetBody <Message>().Id.Should().Be(_testMessage.Id);
            });

            CleanupTopics(topicName);
        }
示例#20
0
        public AzureServiceBusMessageQueue(string connectionString, string inputQueue)
        {
            try
            {
                log.Info("Initializing Azure Service Bus transport with logical input queue '{0}'", inputQueue);

                namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

                InputQueue = inputQueue;

                log.Info("Ensuring that topic '{0}' exists", TopicName);
                if (!namespaceManager.TopicExists(TopicName))
                {
                    try
                    {
                        namespaceManager.CreateTopic(TopicName);
                    }
                    catch
                    {
                        // just assume the call failed because the topic already exists - if GetTopic below
                        // fails, then something must be wrong, and then we just want to fail immediately
                    }
                }

                topicDescription = namespaceManager.GetTopic(TopicName);

                log.Info("Creating topic client");
                topicClient = TopicClient.CreateFromConnectionString(connectionString, topicDescription.Path);

                // if we're in one-way mode, just quit here
                if (inputQueue == null)
                {
                    return;
                }

                GetOrCreateSubscription(InputQueue);

                log.Info("Creating subscription client");
                subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, TopicName, InputQueue, ReceiveMode.PeekLock);
            }
            catch (Exception e)
            {
                throw new ApplicationException(
                          string.Format(
                              "An error occurred while initializing Azure Service Bus with logical input queue '{0}'",
                              inputQueue), e);
            }
        }
        async Task SessionTest(string topicName)
        {
            var entityConnectionString = TestUtility.GetEntityConnectionString(topicName);
            var topicClient            = TopicClient.CreateFromConnectionString(entityConnectionString);
            var subscriptionClient     = SubscriptionClient.CreateFromConnectionString(entityConnectionString, this.SubscriptionName);

            try
            {
                var messageId1 = "test-message1";
                var sessionId1 = "sessionId1";
                await topicClient.SendAsync(new BrokeredMessage()
                {
                    MessageId = messageId1, SessionId = sessionId1
                });

                TestUtility.Log($"Sent Message: {messageId1} to Session: {sessionId1}");

                var messageId2 = "test-message2";
                var sessionId2 = "sessionId2";
                await topicClient.SendAsync(new BrokeredMessage()
                {
                    MessageId = messageId2, SessionId = sessionId2
                });

                TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}");

                // Receive Message, Complete and Close with SessionId - sessionId 1
                await this.AcceptAndCompleteSessionsAsync(subscriptionClient, sessionId1, messageId1);

                // Receive Message, Complete and Close with SessionId - sessionId 2
                await this.AcceptAndCompleteSessionsAsync(subscriptionClient, sessionId2, messageId2);

                // Receive Message, Complete and Close - With Null SessionId specified
                var messageId3 = "test-message3";
                var sessionId3 = "sessionId3";
                await topicClient.SendAsync(new BrokeredMessage()
                {
                    MessageId = messageId3, SessionId = sessionId3
                });

                await this.AcceptAndCompleteSessionsAsync(subscriptionClient, null, messageId3);
            }
            finally
            {
                subscriptionClient.Close();
                topicClient.Close();
            }
        }
示例#22
0
 public static void SendToAll(MyEntitySample itm)
 {
     try
     {
         TopicClient Client = TopicClient.CreateFromConnectionString(
             Settings.Default.SERVICEBUS_URI
             , "mytopic");
         var msg = new BrokeredMessage(
             JsonConvert.SerializeObject(itm, Formatting.Indented));
         msg.Properties.Add("Category", itm.Name);
         Client.Send(msg);
     }
     catch (Exception ex)
     {
     }
 }
 public static void SendToAll(ToDo itm)
 {
     try
     {
         TopicClient Client = TopicClient.CreateFromConnectionString(
             ConfigurationManager.AppSettings["SERVICEBUS_URI"]
             , "todotopic");
         var msg = new BrokeredMessage(
             JsonConvert.SerializeObject(itm, Formatting.Indented));
         msg.Properties.Add("Category", itm.Category);
         Client.Send(msg);
     }
     catch (Exception ex)
     {
     }
 }
示例#24
0
        public Sender(string connectionString, string topicName, TableProvider <StatusTableEntity> statusTableProvider)
        {
            _statusTableProvider = statusTableProvider;
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (namespaceManager.TopicExists(topicName))
            {
                _topicClient = TopicClient.CreateFromConnectionString(connectionString, topicName);
            }
            else
            {
                var topicDescription = new TopicDescription(topicName);
                namespaceManager.CreateTopic(topicDescription);
                _topicClient = TopicClient.CreateFromConnectionString(connectionString, topicName);
            }
        }
        private ClientEntity GetClient(string[] parameters)
        {
            if (parameters.Length != 4)
            {
                throw new ArgumentException("Wrong Parameters Count");
            }

            string cs = parameters[0], topic = parameters[1], queue = parameters[2];

            if (string.IsNullOrEmpty(topic))
            {
                return(QueueClient.CreateFromConnectionString(cs, queue));
            }

            return(TopicClient.CreateFromConnectionString(cs, topic));
        }
        public ActionResult Delete(string id)
        {
            //add message to delete subscription on topic
            var topicClient =
                TopicClient.CreateFromConnectionString(ConfigurationManager.AppSettings["ServiceBusConnection"], "process");
            var msg = new BrokeredMessage
            {
                Label = id
            };

            msg.Properties.Add("Action", 1);
            topicClient.Send(msg);

            Thread.Sleep(2000);
            return(RedirectToAction("Manage"));
        }
        private void CreateClient()
        {
            if (_sendClient != null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(_topicName))
            {
                _sendClient = TopicClient.CreateFromConnectionString(_serviceUri);
            }
            else
            {
                _sendClient = TopicClient.CreateFromConnectionString(_serviceUri, _topicName);
            }
        }
示例#28
0
        /// <summary>
        /// <see cref="MyCompany.Common.EventBus.IEventBus"/>
        /// </summary>
        public void Publish <TEvent>(TEvent @event, string contentType)
        {
            if (@event == null)
            {
                throw new ArgumentNullException("@event");
            }


            var topicClient     = TopicClient.CreateFromConnectionString(_connectionString, _topicName);
            var brokeredMessage = new BrokeredMessage(@event)
            {
                ContentType = contentType
            };

            topicClient.Send(brokeredMessage);
        }
示例#29
0
        public void Send()
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(Global._sfServiceBusConnectionString);

            if (!namespaceManager.TopicExists(Global._sfProcessCommandTopic))
            {
                namespaceManager.CreateTopic(Global._sfProcessCommandTopic);
            }
            TopicClient     Client  = TopicClient.CreateFromConnectionString(Global._sfServiceBusConnectionString, Global._sfProcessCommandTopic);
            BrokeredMessage message = new BrokeredMessage(GetJsonContent());

            message.Properties["process"]     = "iothubeventprocessor";
            message.Properties["iothubalias"] = parameters;

            Client.Send(message);
        }
示例#30
0
        public EventBus()
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(BusConnectionString);

            if (!namespaceManager.TopicExists(BusTopicName))
            {
                namespaceManager.CreateTopic(BusTopicName);
            }

            if (!namespaceManager.SubscriptionExists(BusTopicName, "AllMessages"))
            {
                namespaceManager.CreateSubscription(BusTopicName, "AllMessages");
            }

            _client = TopicClient.CreateFromConnectionString(BusConnectionString, BusTopicName);
        }