private void CloseTopicClient()
        {
            if (_topicClient == null)
            {
                return;
            }

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

                _topicClient?.CloseAsync();
                _topicClient = null;
            }
        }
示例#2
0
        public async void SendMessagesAsync()
        {
            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);
        }
示例#3
0
        public async Task SendUserWithLessOffer(dynamic userInfo)
        {
            try
            {
                await EnsureTopicIsCreated();

                var topicClient = new TopicClient(connectionString, "UserWithLessOffer");


                var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(userInfo)));

                await topicClient.SendAsync(message);

                await topicClient.CloseAsync();
            }
            catch (Exception)
            {
            }
        }
        public async void PublisherProductionAreaChanged()
        {
            if (_lastTask != null && !_lastTask.IsCompleted)
            {
                return;
            }

            var config      = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>();
            var topicClient = new TopicClient(config.ConnectionString, Topic);

            _lastTask = SendMessagesAsync(topicClient, GetMessage(this.ReturnProductionToGetAleatory()));

            await _lastTask;

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

            HandleException(closeTask);
        }
示例#5
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).

                    _topicClient.CloseAsync();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                Delete();

                _disposedValue = true;
            }
        }
示例#6
0
        async Task OnSessionTestAsync(string topicName, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicClient.TopicName,
                this.SubscriptionName,
                ReceiveMode.PeekLock);

            try
            {
                var sessionHandlerOptions =
                    new SessionHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentSessions = 5,
                    MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                    AutoComplete          = true
                };

                var testSessionHandler = new TestSessionHandler(
                    subscriptionClient.ReceiveMode,
                    sessionHandlerOptions,
                    topicClient.InnerSender,
                    subscriptionClient.SessionPumpHost);

                // Send messages to Session
                await testSessionHandler.SendSessionMessages();

                // Register handler
                testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

                // Verify messages were received.
                await testSessionHandler.VerifyRun();
            }
            finally
            {
                await subscriptionClient.CloseAsync();

                await topicClient.CloseAsync();
            }
        }
示例#7
0
        static async Task TopicSender()
        {
            var topicName        = "myfirsttopic";
            var subscriptionName = "myfirstsubscription";

            var sender = new TopicClient(NamespaceConnectionString, topicName);

            var text = Console.ReadLine();

            while (text != "q")
            {
                var message = new Message(Encoding.UTF8.GetBytes(text));
                message.UserProperties["Type"] = "No";
                await sender.SendAsync(message);

                text = Console.ReadLine();
            }

            await sender.CloseAsync();
        }
示例#8
0
        public async Task PublishAsync(object message)
        {
            var topicName        = MessageGroupHelper.GetMessageGroupName(message);
            var connectionString = GetConnectionString(message);

            TopicClient client = null;

            try
            {
                client = TopicClient.CreateFromConnectionString(connectionString, topicName);
                await client.SendAsync(new BrokeredMessage(message));
            }
            finally
            {
                if (client != null && !client.IsClosed)
                {
                    await client.CloseAsync();
                }
            }
        }
示例#9
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            ITopicClient topicClient = new TopicClient(Environment.GetEnvironmentVariable("ConnectionStringtopic002"), "topic002");

            Message message = new Message(Encoding.UTF8.GetBytes(requestBody));

            await topicClient.SendAsync(message);

            await topicClient.CloseAsync();

            List <Employee> employees = JsonConvert.DeserializeObject <List <Employee> >(requestBody);

            return(new OkObjectResult(employees));
        }
        static async void Main(string[] args)
        {
            string ServiceBusConnectionString = "Endpoint=sb://cjgaz204sbns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Zckr+9tQo59XSzwKSFy2lJEoTXvIUdbqYFDB0+zX6AI=";
            string TopicName = "drivers";

            const int numberOfMessages = 10;

            topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after sending all the messages.");
            Console.WriteLine("======================================================");

            // Send messages.
            await SendMessagesAsync(numberOfMessages);

            Console.ReadKey();

            await topicClient.CloseAsync();
        }
示例#11
0
        public async Task SendMessagesAsync(string message)
        {
            _messages.Add(GetMessage($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} -> {message}"));

            if (_lastTask != null && !_lastTask.IsCompleted)
            {
                return;
            }

            var topicClient = new TopicClient(_configuration["serviceBus:connectionString"], Topic);

            _lastTask = SendAsync(topicClient);

            await _lastTask;

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

            HandleException(closeTask);
        }
示例#12
0
        public async Task <bool> SendMessageAsync(List <Produto> produtos)
        {
            var config = _configuration.GetSection("serviceBus").Get <Model.ServiceBusConfiguration>();

            var topicClient = new TopicClient(config.ConnectionString, "LabelImageAdded");

            Message message = new Message();

            var json = JsonConvert.SerializeObject(produtos);

            message.Body = Encoding.UTF8.GetBytes(json);

            await topicClient.SendAsync(message);

            await _logServiceBus.SendMessagesAsync("mensagem enviada para a fila");

            await topicClient.CloseAsync();

            return(true);
        }
        public async void SendMessage()
        {
            try
            {
                ConnectToServiceBus();
                var message = new Message(Encoding.UTF8.GetBytes(_config.Message));

                Task result = _topicClient.SendAsync(message);
                result.Wait();
                await _topicClient.CloseAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: {0}", ex.Message);
                if (null != ex.InnerException)
                {
                    Console.WriteLine("error: {0}", ex.InnerException.Message);
                }
            }
        }
        public override async Task CloseAsync(string correlationId)
        {
            if (_topicClient != null && _topicClient.IsClosedOrClosing == false)
            {
                await _topicClient.CloseAsync();
            }

            if (_subscriptionClient != null && _subscriptionClient.IsClosedOrClosing == false)
            {
                await _subscriptionClient.CloseAsync();

                // Remove temporary subscriber
                if (_tempSubscriber == true)
                {
                    _namespaceManager?.DeleteSubscription(_topicName, _subscriptionName);
                }
            }

            _logger.Trace(correlationId, "Closed queue {0}", this);
        }
        public async void BroadcastNewBlock(Block block)
        {
            try
            {
                ITopicClient topicClient = new TopicClient(config.GetConnectionString("AzureServiceBus"), config["BlockchainNodeSettings:BlockchainTopicName"]);

                string messageBody = JsonConvert.SerializeObject(block);
                var    message     = new Message(Encoding.UTF8.GetBytes(messageBody));
                message.UserProperties["Sender"] = config["BlockchainNodeSettings:NodeName"];

                Console.WriteLine($"Sending message: {messageBody}");
                await topicClient.SendAsync(message);

                topicClient.CloseAsync();
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
        public async Task SendJobProfileMessage(JobProfileMessage jpData, string contentType, string actionType)
        {
            applicationLogger.Info($" CREATED service bus message for sitefinity event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and Jobprofile Id -- {jpData.JobProfileId.ToString()}");
            var connectionStringServiceBus = configurationProvider.GetConfig <string>("DFC.Digital.ServiceBus.ConnectionString");
            var topicName = configurationProvider.GetConfig <string>("DFC.Digital.ServiceBus.TopicName");

            if (actionType == "Draft")
            {
                topicName = configurationProvider.GetConfig <string>("DFC.Digital.ServiceBus.TopicName.Draft");
            }

            var topicClient = new TopicClient(connectionStringServiceBus, topicName);

            // Send Messages
            var jsonData = JsonConvert.SerializeObject(jpData);

            try
            {
                applicationLogger.Info($" SENDING service bus message for sitefinity event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and with Jobprofile Id -- {jpData.JobProfileId.ToString()} ");

                // Message that send to the queue
                var message = new Message(Encoding.UTF8.GetBytes(jsonData));
                message.ContentType = "application/json";
                message.Label       = jpData.Title;
                message.UserProperties.Add("Id", jpData.JobProfileId);
                message.UserProperties.Add("ActionType", actionType);
                message.UserProperties.Add("CType", contentType);
                message.CorrelationId = Guid.NewGuid().ToString();
                await topicClient.SendAsync(message);

                applicationLogger.Info($" SENT service bus message for sitefinity event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} with Jobprofile Id -- {jpData.JobProfileId.ToString()} and with Correlation Id -- {message.CorrelationId.ToString()}");
            }
            catch (Exception ex)
            {
                applicationLogger.Info($" FAILED service bus message for sitefinity event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and with Jobprofile Id -- {jpData.JobProfileId.ToString()} has an exception \n {ex.Message} ");
            }
            finally
            {
                await topicClient.CloseAsync();
            }
        }
示例#17
0
        static async Task MainAsync()
        {
            var program = new Program();

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

                await SendMessagesAsync(new Message(Guid.NewGuid(), message));

                Console.WriteLine("Successfully published.");

                var exit = Console.ReadKey();
                if (exit.Key == ConsoleKey.Escape)
                {
                    break;
                }
            }

            await client.CloseAsync();
        }
示例#18
0
        public void SendMessages(dynamic message)
        {
            try
            {
                ITopicClient _topicClient = new TopicClient(endPoint, topic);

                var msg = new Message(Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(message)))
                {
                    Label     = labelFilter,
                    MessageId = Guid.NewGuid().ToString(),
                };

                _topicClient.SendAsync(msg);

                _topicClient.CloseAsync();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        public async Task <bool> SendMessagesAsync <T>(T objResponse) where T : class
        {
            try
            {
                var _topicClient = new TopicClient(_serviceBusConfiguration.ConnectionString, TopicName);

                string  messageBody = JsonSerializer.Serialize(objResponse);
                Message message     = new Message(Encoding.UTF8.GetBytes(messageBody));

                await _topicClient.SendAsync(message);

                var   closeTask = _topicClient.CloseAsync();
                await closeTask;

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#20
0
        public async Task SendMessages()
        {
            try
            {
                TopicClient tc = new TopicClient(ServiceBusConnectionString, TopicName);

                var taskList = new List <Task>();
                for (int i = 0; i < Store.Length; i++)
                {
                    taskList.Add(SendItems(tc, Store[i]));
                }

                await Task.WhenAll(taskList);

                await tc.CloseAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("\nAll messages sent.\n");
        }
示例#21
0
        public async Task PublishEvent <T> (T @event, string connectionString, string topicName) where T : IIntegrationEvent
        {
            ITopicClient topicClient = null;

            try {
                //Create Topic Client
                topicClient = new TopicClient(connectionString, topicName);

                //Create msg from @event
                var msg = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@event)));

                //Publish msg to a Topic
                await topicClient.SendAsync(msg);
            } catch (Exception ex) {
                //Log - Error while publishing msg to Topic
                _logger.LogError($"Error in publishing event# {nameof(@event)} with id# {@event.Id} to Topic {topicName}, exception - {ex}");
                throw;
            } finally {
                //Close Topic Client
                await topicClient.CloseAsync();
            }
        }
示例#22
0
        static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                       .ConfigureAppConfiguration(configure =>
            {
                configure
                .AddJsonFile("appsettings.json")
                .AddUserSecrets("d81e497b-1130-4d4d-a03c-77656bc05ada")
                .AddCommandLine(args);
            })
                       .ConfigureLogging(configure => configure.AddConsole())
                       .Build();

            var logger = host.Services.GetService <ILogger <Program> >();
            var config = host.Services.GetService <IConfiguration>();

            logger.LogInformation("Sending a message to the Sales Messages queue...");
            try
            {
                var cs     = config.GetConnectionString(config["ServiceBus:ConnectionStringName"]);
                var name   = config["ServiceBus:TopicName"];
                var client = new TopicClient(cs, name);

                var messageBody = $"Total sales for Brazil in August: $13m.";
                var message     = new Message(Encoding.UTF8.GetBytes(messageBody));

                logger.LogInformation("Sending message: {@Message}", messageBody);

                await client.SendAsync(message);

                await client.CloseAsync();
            }
            catch (Exception error)
            {
                logger.LogError(error, error.Message);
                return;
            }
            logger.LogInformation("Sent message successfully.");
        }
示例#23
0
        public async void PublisherStartNewOrder(OrderChangedMessage order)
        {
            if (_lastTask != null && !_lastTask.IsCompleted)
            {
                return;
            }

            var config      = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>();
            var topicClient = new TopicClient(config.ConnectionString, Topic);

            _lastTask = SendMessagesAsync(topicClient, GetMessage(order));

            await _lastTask;

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

            if (HandleException(closeTask))
            {
                AddToMessageList(order);
            }
        }
示例#24
0
        public async Task SendMessagesAsync(OrderChanged orderChanged)
        {
            try
            {
                var config = Configuration
                             .GetSection("serviceBus")
                             .Get <ServiceBusConfiguration>();

                var json    = JsonSerializer.Serialize(orderChanged);
                var message = new Message(Encoding.UTF8.GetBytes(json));

                var topicClient = new TopicClient(config.ConnectionString, config.TopicName);
                await topicClient.SendAsync(message);

                var   closeTask = topicClient.CloseAsync();
                await closeTask;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#25
0
        async Task PeekLockTest(string topicName, int messageCount = 10)
        {
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicName,
                this.SubscriptionName);

            try
            {
                await this.PeekLockTestCase(
                    topicClient.InnerSender,
                    subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                    messageCount);
            }
            finally
            {
                await subscriptionClient.CloseAsync();

                await topicClient.CloseAsync();
            }
        }
示例#26
0
        static async Task Main()
        {
            ITopicClient topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

            var data = new SomeData()
            {
                Id   = Guid.NewGuid().ToString(),
                Data = "Hello world!"
            };
            var payload = JsonConvert.SerializeObject(data);

            var msg = new Message(Encoding.UTF8.GetBytes(payload));

            msg.UserProperties.Add("Type", "eventData");
            msg.MessageId = Guid.NewGuid().ToString();

            await topicClient.SendAsync(msg);

            await topicClient.CloseAsync();

            Console.WriteLine("Event emitted successfully.");
        }
        public async Task SendMessage(MessageBase message)
        {
            if (string.IsNullOrEmpty(_config.ServiceBusConnectionString))
            {
                throw new ArgumentException("No Service Bus Connection String is configured");
            }
            if (string.IsNullOrEmpty(_config.TopicName))
            {
                throw new ArgumentException("No Service Bus topic Name is configured");
            }

            var topicClient = new TopicClient(_config.ServiceBusConnectionString, _config.TopicName);
            var busMessage  = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)))
            {
                Label         = message.GetType().Name, // we use label to route messages by body type
                ContentType   = "application/json",
                CorrelationId = message.CorrelationId
            };
            await topicClient.SendAsync(busMessage);

            await topicClient.CloseAsync();
        }
示例#28
0
        public void SendMessageToTopic(T audit, string topicPath, string subscriptionName, string connectionString)
        {
            //Creating management client to manage artifacts
            var manager = new ManagementClient(connectionString);

            if (!manager.TopicExistsAsync(topicPath).Result)
            {
                manager.CreateTopicAsync(topicPath);
            }

            //Create a subscription
            var description = new SubscriptionDescription(topicPath, subscriptionName);

            //{
            //    AutoDeleteOnIdle = TimeSpan.FromMinutes(5)
            //};

            if (!manager.SubscriptionExistsAsync(topicPath, subscriptionName).Result)
            {
                manager.CreateSubscriptionAsync(description).Wait();
            }

            //create clients
            var topicClient = new TopicClient(connectionString, topicPath);

            //create and sending message to topic
            string  messageBody = JsonConvert.SerializeObject(audit);
            Message message     = new Message(Encoding.UTF8.GetBytes(messageBody))
            {
                Label       = "AuditLog",
                ContentType = "application/json",
            };

            topicClient.SendAsync(message).Wait();

            //close client
            topicClient.CloseAsync().Wait();
        }
        public async Task SendOtherRelatedTypeMessages(IEnumerable <RelatedContentItem> relatedContentItems, string contentType, string actionType)
        {
            applicationLogger.Info($" CREATED service bus message for sitefinity event {actionType.ToUpper()} on Item of Type -- {contentType.ToUpper()} with {relatedContentItems.Count().ToString()} message(s)");
            var connectionStringServiceBus = configurationProvider.GetConfig <string>("DFC.Digital.ServiceBus.ConnectionString");
            var topicName   = configurationProvider.GetConfig <string>("DFC.Digital.ServiceBus.TopicName");
            var topicClient = new TopicClient(connectionStringServiceBus, topicName);

            try
            {
                foreach (var relatedContentItem in relatedContentItems)
                {
                    applicationLogger.Info($" SENDING service bus message for sitefinity event {actionType.ToUpper()}  on Item -- {relatedContentItem.Title} of Type -- {contentType} with Id -- {relatedContentItem.Id.ToString()} linked to Job Profile {relatedContentItem.JobProfileTitle} -- {relatedContentItem.JobProfileId.ToString()}");

                    // Send Messages
                    var jsonData = JsonConvert.SerializeObject(relatedContentItem);

                    // Message that send to the queue
                    var message = new Message(Encoding.UTF8.GetBytes(jsonData));
                    message.ContentType = "application/json";
                    message.Label       = relatedContentItem.Title;
                    message.UserProperties.Add("Id", $"{relatedContentItem.JobProfileId}--{relatedContentItem.Id}");
                    message.UserProperties.Add("ActionType", actionType);
                    message.UserProperties.Add("CType", contentType);
                    message.CorrelationId = Guid.NewGuid().ToString();
                    await topicClient.SendAsync(message);

                    applicationLogger.Info($" SENT service bus message for sitefinity event {actionType.ToUpper()} on Item -- {relatedContentItem.Title} of Type -- {contentType} with Id -- {relatedContentItem.Id.ToString()} linked to Job Profile {relatedContentItem.JobProfileTitle} -- {relatedContentItem.JobProfileId.ToString()} with Correlation Id -- {message.CorrelationId.ToString()}");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.Info($" FAILED service bus message for sitefinity event {actionType.ToUpper()} on Item of Type -- {contentType} with {relatedContentItems.Count().ToString()} message(s) has an exception \n {ex.Message}");
            }
            finally
            {
                await topicClient.CloseAsync();
            }
        }
示例#30
0
        private async Task SendSubscriptionIsAliveMessage()
        {
            var message = new Message();

            message.UserProperties[SubscriptionPingPropertyName] = DateTime.UtcNow;
            message.UserProperties[ServiceBus.MessageConverter.SenderIdPropertyName] = _nodeId;
            TopicClient topicClient = null;

            try
            {
                topicClient = new TopicClient(_connectionString, _topicName);
                await topicClient.SendAsync(message);

                _logger?.LogDebug(Resources.AzureServiceBus_Debug_SubscriptionAliveSent, _nodeId);
            }
            finally
            {
                if (topicClient != null)
                {
                    await topicClient.CloseAsync();
                }
            }
        }