private async Task<TopicClient> GetTopicClient()
        {
            if (_topicClient != null) return _topicClient;

            _topicClient = await _queueManager.CreateTopicSender(_topicPath);
            return _topicClient;
        }
 public static void Initialize()
 {
     if (null == OrdersTopicClient)
     {
         try
         {
             string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBusTopics.ConnectionString");
             // string connectionString = RoleEnvironment.GetConfigurationSettingValue("Microsoft.ServiceBusTopics.ConnectionString");
             var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
             if (!namespaceManager.TopicExists("OrderTopic"))
             {
                 namespaceManager.CreateTopic("OrderTopic");
             }
             if (!namespaceManager.SubscriptionExists("OrderTopic", "OrderMessages"))
             {
                 namespaceManager.CreateSubscription("OrderTopic", "OrderMessages");
             }
             // Initialize the connection to Service Bus Topics
             OrdersTopicClient = TopicClient.CreateFromConnectionString(connectionString, "OrderTopic");
             SubClient = SubscriptionClient.CreateFromConnectionString(connectionString, "OrderTopic", "OrderMessages");
            
         }
         catch (Exception ex)
         {
             string str = ex.Message;
         }
     }
 }
 private void SendMessage(TopicClient client, int retries)
 {
     try
     {
         using (var scope = new TransactionScope())
         {
             var message = new BrokeredMessage();
             message.Properties.Add("Content", "Unknown");
             client.Send(message);
             scope.Complete();
         }
     }
     catch (OperationCanceledException)
     {
         retries++;
         if (retries < 3)
         {
             SendMessage(client, retries);
         }
         else
         {
             throw;
         }
     }
 }
Esempio n. 4
0
 public WebsocketTopicClient(Uri uri, DelegateConnected connected, CompletionQueue completion_queue)
 {
     message_client = new WebsocketMessageClient(
         uri, WebsocketTopicServer.protocol, connected, MessageWaiting, completion_queue);
     topic_client = new TopicClient(message_client);
     this.completion_queue = completion_queue;
 }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class, 
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        protected TopicSender(MessagingSettings settings, string topic, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic = topic;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            try
            {
                new NamespaceManager(this.serviceUri, this.tokenProvider)
                    .CreateTopic(
                        new TopicDescription(topic)
                        {
                            RequiresDuplicateDetection = true,
                            DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(30)
                        });
            }
            catch (MessagingEntityAlreadyExistsException)
            { }

            // TODO: This could be injected.
            this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            this.retryPolicy.Retrying +=
                (s, e) =>
                {
                    Trace.TraceError("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount);
                };

            var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider);
            this.topicClient = factory.CreateTopicClient(this.topic);
        }
        public async void Init(MessageReceived messageReceivedHandler) {
            this.random = new Random();

            //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
            
            // Tcp mode does not work when I run in a VM (VirtualBox) and the host 
            // is using a wireless connection. Hard coding to Http.
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            this.factory = MessagingFactory.CreateFromConnectionString(connectionString);
            this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

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

            this.subscriptionName = Guid.NewGuid().ToString();

            // Not needed really, it's a GUID...
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName)) {
                namespaceManager.CreateSubscription(topicName, subscriptionName);
            }

            this.topicClient = factory.CreateTopicClient(topicName);

            this.subClient = factory.CreateSubscriptionClient(topicName, subscriptionName);

            while (true) {
                await ReceiveMessageTaskAsync(messageReceivedHandler);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class, 
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        protected TopicSender(ServiceBusSettings settings, string topic, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic = topic;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            // TODO: This could be injected.
            this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            this.retryPolicy.Retrying +=
                (s, e) =>
                {
                    var handler = this.Retrying;
                    if (handler != null)
                    {
                        handler(this, EventArgs.Empty);
                    }

                    Trace.TraceWarning("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount);
                };

            var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider);
            this.topicClient = factory.CreateTopicClient(this.topic);
        }
        private TopicClient GetTopicClient()
        {
            if (_topicClient != null) return _topicClient;

            _topicClient = _queueManager.CreateTopicSender(_topicPath).Result;
            return _topicClient;
        }
 public ReliableTopicClient(string sbNamespace, TokenProvider tokenProvider, string path, RetryPolicy<ServiceBusTransientErrorDetectionStrategy> policy)
     : base(sbNamespace, tokenProvider, path, policy)
 {
     //create the queue if it doesn't exist
     bool needsCreation = false;
     try
     {
         needsCreation = !mRetryPolicy.ExecuteAction<bool>(() => mNamespaceManager.TopicExists(path));
     }
     catch (MessagingEntityNotFoundException)
     {
         needsCreation = true;
     }
     if (needsCreation)
     {
         try
         {
             mRetryPolicy.ExecuteAction<TopicDescription>(() => mNamespaceManager.CreateTopic(path));
         }
         catch (MessagingEntityAlreadyExistsException)
         {
             //ignore this exception because queue already exists
         }
     }
     mRetryPolicy.ExecuteAction(() => mTopicClient = mMessagingFactory.CreateTopicClient(path));
 }
        // todo, factor out... to bad IMessageSender is internal
        private void Send(TransportMessage message, TopicClient sender)
        {
            var numRetries = 0;
            var sent = false;

            while (!sent)
            {
                try
                {
                    SendTo(message, sender);
                    sent = true;
                }
                // todo, outbox
                catch (MessagingEntityDisabledException)
                {
                    numRetries++;

                    if (numRetries >= MaxDeliveryCount) throw;

                    Thread.Sleep(TimeSpan.FromSeconds(numRetries * DefaultBackoffTimeInSeconds));
                }
                // back off when we're being throttled
                catch (ServerBusyException)
                {
                    numRetries++;

                    if (numRetries >= MaxDeliveryCount) throw;

                    Thread.Sleep(TimeSpan.FromSeconds(numRetries * DefaultBackoffTimeInSeconds));
                }
            }
        }
Esempio n. 11
0
 public HeaterCommunication()
 {
     var topicNameSend = "businessrulestofieldgateway";
     _topicNameReceive = "fieldgatewaytobusinessrules";
     _namespaceMgr = NamespaceManager.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
     _factory = MessagingFactory.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
     _client = _factory.CreateTopicClient(topicNameSend);
 }
Esempio n. 12
0
 public TcpTopicClientSAE(IPEndPoint ipEndPoint, DelegateConnected connected, 
     CompletionQueue completion_queue)
 {
     message_client = new TcpMessageClientSAE(
         ipEndPoint, connected, MessageWaiting, completion_queue);
     topic_client = new TopicClient(message_client);
     this.completion_queue = completion_queue;
 }
Esempio n. 13
0
        private static void SendMessage(TopicClient client, string eventType, int messageNumber)
        {
            BrokeredMessage message = new BrokeredMessage(string.Format("{0} #{1} {2} message", _runID, messageNumber, eventType));
            message.Properties["EventType"] = eventType;
            client.Send(message);

            Console.WriteLine("Sent {0} message to {1} topic (run {2})", eventType, _topicName, _runID);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="client">Topic Client</param>
        public BusTopicClient(TopicClient client)
        {
            if (null == client)
            {
                throw new ArgumentNullException("client");
            }

            this.client = client;
        }
		/// <summary>
		/// Sends a message to the ServiceFabric Service.
		/// </summary>
		/// <returns></returns>
		public void SendMessage(BrokeredMessage message)
		{
			if (_sendClient == null)
			{
				_sendClient = TopicClient.CreateFromConnectionString(_serviceUri, _topicName);
			}
			
			_sendClient.Send(message);
		}
 //Enviar uma lista de mensagens para o cliente topic e imprimir as mensagens enviadas na consola
 static void SendListOfMessages(List<BrokeredMessage> list, TopicClient myTopicClient)
 {
     foreach (var message in list)
     {
         Console.Write(string.Format("Sending message with id: {0}", message.MessageId));
         myTopicClient.Send(message);
         Console.WriteLine("...sent");
     }
 }
		/// <summary>
		/// Sends a message to the ServiceFabric Service.
		/// </summary>
		/// <returns></returns>
		public Task SendMessageAsync(BrokeredMessage message)
		{
			if (_sendClient == null)
			{
				_sendClient = TopicClient.CreateFromConnectionString(_serviceUri, _topicName);
			}

			return _sendClient.SendAsync(message);			
		}
Esempio n. 18
0
        public HorseNotification()
        {
            namespaceManager = NamespaceManager.Create();

            DeleteTopicsAndSubscriptions(namespaceManager);
            CreateTopicsAndSubscriptions(namespaceManager);

            MessagingFactory factory = MessagingFactory.Create();
            myTopicClient = factory.CreateTopicClient(topicDescription.Path);
        }
        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;
        }
Esempio n. 20
0
 private void SaveTopic(TopicClient topic)
 {
     var status = _topicDriver.Save(topic);
     if (status == OperationStatus.Success)
     {
         topic.AddSuccessNotification(MessageManager.GetMessage(status));
     }
     else
     {
         topic.AddErrorNotification(MessageManager.GetMessage(status));
     }
 }
		protected virtual IEnumerable<string> ProcessPost(TopicClient client)
		{
			var result = new List<string>();
			var watch = new Stopwatch();
			for (int i = 1; i < 11; i++)
			{
				watch.Restart();
				SendMessage(client, 0);
				watch.Stop();
				result.Add($"Azure Service Bus Topic Write {i} try: {watch.ElapsedMilliseconds}");
			}
			return result;
		}
Esempio n. 22
0
        public static TopicClient GetTopicClient()
        {
            if (client == null)
            {
                var connString = CloudConfigurationManager.
                    GetSetting("Microsoft.ServiceBus.ConnectionString");

                client = TopicClient.CreateFromConnectionString(
                    connString, WellKnown.TopicName);
            }

            return client;
        }
Esempio n. 23
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);
        }
Esempio n. 24
0
        public ServiceBusMessageBus(string connectionString, string topicName, ISerializer serializer = null) {
            _topicName = topicName;
            _serializer = serializer ?? new JsonNetSerializer();
            _subscriptionName = "MessageBus";
            _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            if (!_namespaceManager.TopicExists(_topicName))
                _namespaceManager.CreateTopic(_topicName);

            _topicClient = TopicClient.CreateFromConnectionString(connectionString, _topicName);
            if (!_namespaceManager.SubscriptionExists(_topicName, _subscriptionName))
                _namespaceManager.CreateSubscription(_topicName, _subscriptionName);

            _subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, _topicName, _subscriptionName, ReceiveMode.ReceiveAndDelete);
            _subscriptionClient.OnMessageAsync(OnMessageAsync, new OnMessageOptions { AutoComplete = true });
        }
Esempio n. 25
0
 static void Main(string[] args)
 {
     _topicClient =
         TopicClient.CreateFromConnectionString(
             "Endpoint=sb://relay-test.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=rO9gnnT2l6HFSUcQAX6Dio+2zUGri0J50x7R20CGKYA=",
             "tehtopic");
     var random = new Random();
     for (int i = 0; i < 100; i++)
     {
         var tehAmount = random.Next(0, 1000);
         var message = new BrokeredMessage("MESSAGE F**K YEAH!");
         message.Properties.Add("tehAmount", tehAmount);
         _topicClient.Send(message);
     }
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            ParseArgs(args);

            // Receive request messages from request queue
            Console.Title = "Server";
            TopicClient        topicClient   = CreateTopicClient(SampleManager.TopicPath);
            SubscriptionClient requestClient = CreateSubscriptionClient(
                SampleManager.TopicPath, SampleManager.RequestSubName);

            Console.WriteLine("Ready to receive messages from {0}/{1}...", requestClient.TopicPath, requestClient.Name);
            ReceiveMessages(topicClient, requestClient);

            Console.WriteLine("\nServer complete.");
            Console.ReadLine();
        }
Esempio n. 27
0
        public static void AddTopicClients(this IServiceCollection services, string serviceBusConnectionString, string topicNames)
        {
            var topics       = topicNames.Split(',');
            var pcsBusSender = new PcsBusSender();

            foreach (var topicName in topics)
            {
                if (!string.IsNullOrWhiteSpace(topicName))
                {
                    var topicClient = new TopicClient(serviceBusConnectionString, topicName);
                    pcsBusSender.Add(topicName, topicClient);
                }
            }

            services.AddSingleton <IPcsBusSender>(pcsBusSender);
        }
        void OnSessionHandlerShouldFailOnNonSessionFulQueue()
        {
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedTopicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicClient.TopicName,
                TestConstants.SubscriptionName,
                ReceiveMode.PeekLock);

            Assert.Throws <InvalidOperationException>(
                () => subscriptionClient.RegisterSessionHandler(
                    (session, message, token) =>
            {
                return(Task.CompletedTask);
            }));
        }
Esempio n. 29
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);
        }
Esempio n. 30
0
        static async Task SendTopicsAsync(int numberOfTopics, string topic)
        {
            ITopicClient topicClient = new TopicClient(ServiceBusConnectionString, topic);

            for (var i = 0; i < numberOfTopics; i++)
            {
                string messageBody = $"Topic {i}";
                var    message     = new Message(Encoding.UTF8.GetBytes(messageBody));

                Console.WriteLine($"Sending message to topic '{topic}': {messageBody}");

                await topicClient.SendAsync(message);
            }

            await topicClient.CloseAsync();
        }
        public AzureServiceBusMessageBus(string connectionString, string topicName, ISerializer serializer = null, ILoggerFactory loggerFactory = null) : base(loggerFactory) {
            _serializer = serializer ?? new JsonNetSerializer();

            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            if (!namespaceManager.TopicExists(topicName))
                namespaceManager.CreateTopic(topicName);

            _topicClient = TopicClient.CreateFromConnectionString(connectionString, topicName);

            const string subscriptionName = "MessageBus";
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName))
                namespaceManager.CreateSubscription(topicName, subscriptionName);

            _subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete);
            _subscriptionClient.OnMessageAsync(OnMessageAsync, new OnMessageOptions { AutoComplete = true });
        }
        public async Task Send()
        {
            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);
            TopicClient      topicClient = factory.CreateTopicClient(Helpers.BasicTopicName);

            byte[] messageData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Helpers.GetModels()));

            BrokeredMessage message = new BrokeredMessage(new MemoryStream(messageData), true)
            {
                ContentType = "application/json",
                Label       = "dynamic topic data",
                TimeToLive  = TimeSpan.FromMinutes(20)
            };

            await topicClient.SendAsync(message);
        }
        public async Task SendMessagesAsync(string message)
        {
            if (_lastTask != null && !_lastTask.IsCompleted)
            {
                return;
            }
            var config      = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>();
            var topicClient = new TopicClient(config.ConnectionString, _topic);

            _lastTask = SendAsync(topicClient);
            await _lastTask;
            var   closeTask = topicClient.CloseAsync();
            await closeTask;

            HandleException(closeTask);
        }
        public static ITopicClient GetTopicClient(string connectionString, string topicName = null)
        {
            var builder    = new ServiceBusConnectionStringBuilder(connectionString, topicName, null);
            var entityInfo = _getEntityNameAndUniqueKey(builder);

            if (!Clients.ContainsKey(entityInfo.Item2))
            {
                var topicClient = new TopicClient(builder);
                Clients.TryAdd(entityInfo.Item2, topicClient);
                return(topicClient);
            }
            else
            {
                return((ITopicClient)Clients[entityInfo.Item2]);
            }
        }
Esempio n. 35
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);
        }
        private void CreateClient()
        {
            if (sendClient != null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(TopicName))
            {
                sendClient = new TopicClient(new ServiceBusConnectionStringBuilder(ServiceUri));
            }
            else
            {
                sendClient = new TopicClient(ServiceUri, TopicName);
            }
        }
Esempio n. 37
0
        public async Task SendMessageAsync(string topicName, string subscriptionName, string message, Dictionary <string, object> properties = null)
        {
            ValidateTopicAndSubscriptionSettings(ConstructorCreateMode.OnlyConnectionString);
            var topicClient        = new TopicClient(ServiceBusConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, EntityName, subscriptionName);
            var messageBody        = new Message(Encoding.UTF8.GetBytes(message));

            if (properties != null)
            {
                foreach (var prop in properties)
                {
                    messageBody.UserProperties.Add(prop);
                }
            }
            await topicClient.SendAsync(messageBody);
        }
        /// <summary>
        /// Create a message topic sender
        /// </summary>
        /// <param name="connectionString">The connection string</param>
        /// <param name="topicName">The name of the topic</param>
        /// <param name="transportType">The transport type e.g. AMQP, AMQP WebSockets</param>
        /// <param name="retryPolicy">The retry policy</param>
        /// <param name="canCreateTopic">A boolean denoting if topic should be created if it does not exist. NOTE: Manage rights required</param>
        /// <returns>A service bus sender</returns>
        public async Task <ISender <T> > CreateTopicSenderAsync <T>(string connectionString, string topicName, TransportType transportType, RetryPolicy retryPolicy = null, bool canCreateTopic = false) where T : class
        {
            var builder = new ServiceBusConnectionStringBuilder(connectionString)
            {
                EntityPath = topicName
            };
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                builder.SasKeyName,
                builder.SasKey);

            await ConfigureTopicAsync(builder, canCreateTopic).ConfigureAwait(false);

            var topicClient = new TopicClient(builder.Endpoint, topicName, tokenProvider, transportType);

            return(new Sender <T>(topicClient));
        }
Esempio n. 39
0
        public async Task SendMessagesAsync(CancellationToken token)
        {
            _client = CreateClient(_options.ConnectionString, _options.TopicName);
            await CreateTopic();

            Helper.WriteLine("Started sending messages.", ConsoleColor.Magenta);
            while (!token.IsCancellationRequested)
            {
                Priority priority = Program.GetPriority();
                Message  message  = CreateMessage(priority);
                await _client.SendAsync(message);

                Helper.WriteLine($"Message sent: Id = {message.MessageId}, Priority = {priority}", ConsoleColor.Yellow);
                await Task.Delay(_options.ProcessTime);
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class,
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        public TopicSender(ServiceBusSettings settings, string topic, ILogger <TopicSender> logger)
        {
            this.settings = settings;
            this.topic    = topic;
            this.logger   = logger;

            //TODO: verify how does it work. Was changed to newest version of ServiceBus library
            retryPolicy = Policy.Handle <Exception>(e => {
                logger.LogWarning(
                    "An error occurred while sending message to the topic {1}: {0}",
                    e.Message, topic);
                return(true);
            })
                          .WaitAndRetryAsync(4, retry => TimeSpan.FromSeconds(Math.Pow(2, retry)));
            topicClient = new TopicClient(settings.ConnectionString, topic);
        }
        private static async Task QueueOrders(int requestedAmount)
        {
            var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(ConnectionString);

            var topicClient = new TopicClient(serviceBusConnectionStringBuilder.GetNamespaceConnectionString(), serviceBusConnectionStringBuilder.EntityPath);

            for (int currentOrderAmount = 0; currentOrderAmount < requestedAmount; currentOrderAmount++)
            {
                var order        = GenerateOrder();
                var rawOrder     = JsonConvert.SerializeObject(order);
                var orderMessage = new Message(Encoding.UTF8.GetBytes(rawOrder));

                Console.WriteLine($"Queuing order {order.Id} - A {order.ArticleNumber} for {order.Customer.FirstName} {order.Customer.LastName}");
                await topicClient.SendAsync(orderMessage);
            }
        }
Esempio n. 42
0
        private void SubmitJob(Job job)
        {
            // Create a TopicClient for Job Topic.
            JobTopicClient = Factory.CreateTopicClient(TopicPath);

            var message = new BrokeredMessage(job);

            // Promote properties.
            message.Properties.Add("JobType", job.JobType.ToString());

            // Set the CorrelationId to the region.
            message.CorrelationId = job.JobType.ToString();

            // Send the message.
            JobTopicClient.Send(message);
        }
Esempio n. 43
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Publisher Sample", Version = "v1"
                });
            });
            string publisherserviceBusconnection = Configuration["AppSettings:PublisherServiceBusconnection"];
            string publisherTopicName            = Configuration["AppSettings:PublisherTopicName"];
            var    topicClient = new TopicClient(publisherserviceBusconnection, publisherTopicName, RetryPolicy.Default);

            services.AddSingleton <IMessagingClient>(new AzureTopicClient(topicClient));
            services.AddTransient <IUsersCommandService, UsersCommandService>();
        }
Esempio n. 44
0
        public Task SendMessageAsync(MessageType messageType, Sale sale, UpdatedSale updatedSale = null)
        {
            _messageConnectionString = Configuration["MessageConnectionString"];
            var messageToSend = _factory.Create(messageType, sale, updatedSale);

            var serviceBusClient = new TopicClient(_messageConnectionString, "sale-send");

            var message = new Message(messageToSend.ToJsonBytes());

            message.ContentType = "application/json";
            message.UserProperties.Add("CorrelationId", Guid.NewGuid().ToString());

            serviceBusClient.SendAsync(message);

            return(Task.CompletedTask);
        }
        private void CreateClient()
        {
            if (_sendClient != null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(_topicName))
            {
                _sendClient = TopicClient.CreateFromConnectionString(_serviceUri);
            }
            else
            {
                _sendClient = TopicClient.CreateFromConnectionString(_serviceUri, _topicName);
            }
        }
Esempio n. 46
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);
        }
        private bool ChangeOrderStatus(OrderStatusChangeCommand command)
        {
            try
            {
                var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)));

                TopicClient topicClient = new TopicClient(config.GetSection("QueueConfig").GetSection("ServiceBusConnectionString").Value, config.GetSection("QueueConfig").GetSection("OrderQueueName").Value);
                topicClient.SendAsync(message).Wait();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 public async Task Send()
 {
     try
     {
         var productRating = new ProductRatingUpdateMessage {
             ProductId = 123, RatingSum = 23
         };
         var message     = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(productRating)));
         var topicClient = new TopicClient(ServiceBusConnectionString, "productRatingUpdates");
         await topicClient.SendAsync(message);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
        public async Task SendMessagesAsync <T>(T obj)
        {
            ITopicClient topicClient;

            topicClient = new TopicClient(ServiceBusConnectionString, TopicName);
            try
            {
                string  messageBody = JsonConvert.SerializeObject(obj);
                Message message     = new Message(Encoding.UTF8.GetBytes(messageBody));
                await topicClient.SendAsync(message);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
Esempio n. 50
0
        public void Publish <T_message>(T_message message)
        {
            var messageType = typeof(T_message);
            var metadata    = _configuration.MessageDefinitions.FirstOrDefault(md => md.MessageType == messageType && md.MessageAction == Core.MessageAction.Event);

            if (metadata != null)
            {
                //CreateTopic(metadata.QueueName);
                var             body            = _serialiser.Serialise(message);
                BrokeredMessage brokeredMessage = new BrokeredMessage(body);

                var         destination = GetDestinationName(metadata.QueueName, true);
                TopicClient topicClient = _messageFactory.CreateTopicClient(destination);
                topicClient.Send(brokeredMessage);
            }
        }
Esempio n. 51
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)
     {
     }
 }
        public static IHealthBuilder AddAzureServiceBusTopicConnectivityCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString,
            string topicName,
            TimeSpan cacheDuration)
        {
            var topicClient = new TopicClient(connectionString, topicName)
            {
                OperationTimeout = DefaultTimeout
            };

            builder.AddCachedCheck(name, CheckServiceBusTopicConnectivity(name, topicClient), cacheDuration);

            return(builder.Builder);
        }
        private TopicClient GetTopic()
        {
            if (_topicClient == null)
            {
                lock (_lock)
                {
                    if (_topicClient == null)
                    {
                        _logger.Info(null, "Connecting topic {0} to Topic={1};{2}", Name, _topicName, _connectionString);

                        _topicClient = new TopicClient(_connectionString, _topicName);
                    }
                }
            }
            return(_topicClient);
        }
        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"));
        }
Esempio n. 57
0
        private void DiscardTopicClient()
        {
            var topicClient = _topicClient;
            _topicClient = null;

            if (topicClient == null) return;
            if (topicClient.IsClosed) return;

            try
            {
                topicClient.Close();
            }
            catch (Exception exc)
            {
                _logger.Error(exc, "Failed to close TopicClient instance before discarding it.");
            }
        }
Esempio n. 58
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);
            }
        }
        private void DiscardTopicClient()
        {
            var topicClient = _topicClient;
            _topicClient = null;

            if (topicClient == null) return;
            if (topicClient.IsClosed) return;

            try
            {
                _logger.Debug("Discarding message sender for {TopicPath}", _topicPath);
                topicClient.Close();
            }
            catch (Exception exc)
            {
                _logger.Error(exc, "Failed to close TopicClient instance before discarding it.");
            }
        }
        // todo, factor out... to bad IMessageSender is internal
        private void SendTo(TransportMessage message, TopicClient sender)
        {
            using (var brokeredMessage = message.Body != null ? new BrokeredMessage(message.Body) : new BrokeredMessage())
            {
                if (!string.IsNullOrWhiteSpace(message.CorrelationId)) brokeredMessage.CorrelationId = message.CorrelationId;
                if (message.TimeToBeReceived < TimeSpan.MaxValue) brokeredMessage.TimeToLive = message.TimeToBeReceived;

                foreach (var header in message.Headers)
                {
                    brokeredMessage.Properties[header.Key] = header.Value;
                }

                brokeredMessage.Properties[Headers.MessageIntent] = message.MessageIntent.ToString();
                brokeredMessage.MessageId = message.Id;
                brokeredMessage.ReplyTo = message.ReplyToAddress.ToString();

                sender.Send(brokeredMessage);
            }
        }