Ejemplo n.º 1
0
        public void OnMessageAsync(Func <IBrokeredMessage, Task> onMessageAsync)
        {
            var callback = CreateOnMessageAsyncCallback(onMessageAsync);

            var onMessageOptions = new OnMessageOptions();

            onMessageOptions.ExceptionReceived += OnMessageException;

            _client.OnMessageAsync(callback);
        }
Ejemplo n.º 2
0
        //public async Task Receive()
        //{
        //    string subscriptionName = Guid.NewGuid().ToString("N");
        //    MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);

        //    // Create subscription
        //    SubscriptionDescription description = new SubscriptionDescription(Helpers.BasicTopicName, subscriptionName)
        //    {
        //        AutoDeleteOnIdle = TimeSpan.FromMinutes(5)
        //    };

        //    NamespaceManager manager = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);

        //    SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(Helpers.BasicTopicName, subscriptionName);
        //    await manager.CreateSubscriptionAsync(description);

        //    // Receive message
        //    BrokeredMessage message = await subscriptionClient.ReceiveAsync();

        //    await Helpers.PrintMessageInfo(message);
        //}


        public async Task Receive()
        {
            string           subscriptionName = Guid.NewGuid().ToString("N");
            MessagingFactory factory          = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);

            // Create subscription
            SubscriptionDescription description = new SubscriptionDescription(Helpers.BasicTopicName, subscriptionName)
            {
                AutoDeleteOnIdle = TimeSpan.FromMinutes(25)
            };

            NamespaceManager manager = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);

            if (!manager.SubscriptionExists(Helpers.BasicTopicName, subscriptionName))
            {
                await manager.CreateSubscriptionAsync(description);
            }

            // Receive messagea.
            var tcs = new TaskCompletionSource <bool>();

            SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(Helpers.BasicTopicName, subscriptionName);

            subscriptionClient.OnMessageAsync(async message =>
            {
                await Helpers.PrintMessageInfo(message);
            });

            await Task.Delay(TimeSpan.FromMinutes(1));

            tcs.SetResult(true);
            await tcs.Task;
        }
        public override async Task SubscribeToQueueAsync <TMessage>(Func <TMessage, Task> messageHandler)
        {
            if (_subscrClient != null && !_subscrClient.IsClosed)
            {
                throw new InvalidOperationException("Already subscribed. Please unsubscribe first.");
            }

            var manager = GetNamespaceManager();

            if (!await manager.SubscriptionExistsAsync(Configuration.TopicName, Configuration.SubscriptionName))
            {
                var subscrDescr = new SubscriptionDescription(Configuration.TopicName, Configuration.SubscriptionName)
                {
                    DefaultMessageTimeToLive = new TimeSpan(0, 0, MessageTtl)
                };
                await manager.CreateSubscriptionAsync(subscrDescr);
            }

            _subscrClient = SubscriptionClient.CreateFromConnectionString(Configuration.ConnectionString, Configuration.TopicName, Configuration.SubscriptionName);
            _subscrClient.OnMessageAsync(x =>
            {
                var body        = x.GetBody <string>();
                var messageItem = JsonConvert.DeserializeObject <TMessage>(body);
                return(messageHandler(messageItem));
            });
        }
Ejemplo n.º 4
0
        public async Task Run(OnMessageOptions topicOptions)
        {
            while (true)
            {
                var message = _deadLetter.Receive();

                if (message == null)
                {
                    break;
                }

                var context = message.GetBody <RemoteExecutionContext>(CrmPluginBrokerRole.ExecutionContextSerializer);

                try
                {
                    await PassContextToPlugins(context);
                }
                catch (Exception)
                {
                    Trace.TraceError("Failing dead-letter message: {0}({1}) {2}",
                                     context.PrimaryEntityName,
                                     context.PrimaryEntityId,
                                     context.MessageName);

                    throw;
                }
            }

            _deadLetter.Close();
            _topic.OnMessageAsync(OnTopicMessageAsync, topicOptions);
        }
        private void StartSubscriptionClient()
        {
            string connectionString = CloudConfigurationManager.GetSetting("SInnovations.Servicebus.ConnectionString");

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            TopicDescription td = new TopicDescription(TopicName);

            td.MaxSizeInMegabytes       = 512;
            td.DefaultMessageTimeToLive = new TimeSpan(0, 5, 0);

            if (!namespaceManager.TopicExists(TopicName))
            {
                namespaceManager.CreateTopic(td);
            }
            if (!namespaceManager.SubscriptionExists(TopicName, AllMessages))
            {
                namespaceManager.CreateSubscription(TopicName, AllMessages);
            }


            Client = SubscriptionClient.CreateFromConnectionString
                         (connectionString, TopicName, AllMessages);
            var options = new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 10
            };

            options.ExceptionReceived += options_ExceptionReceived;

            Client.OnMessageAsync(OnMessageAsync, options);
            CompletedEvent.WaitOne();
        }
        public async Task StartListening(TriggerConfig triggerInput)
        {
            // Configure the callback options
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete       = false;
            options.MaxConcurrentCalls = 10;

            // create the relevant client and the onMessage listener
            if (triggerInput.QueueName != null && triggerInput.QueueName.Length > 1)
            {
                queueReceiver = messagingFactory.CreateQueueClient(triggerInput.QueueName, ReceiveMode.PeekLock);
                queueReceiver.OnMessageAsync(async message =>
                {
                    await processMessage(message, logMessageStub);
                }, options);
                isListening = true;
            }
            else
            {
                subscriptionReceiver = messagingFactory.CreateSubscriptionClient(triggerInput.TopicName, triggerInput.SubscriptionName, ReceiveMode.PeekLock);
                subscriptionReceiver.OnMessageAsync(async message =>
                {
                    await processMessage(message, logMessageStub);
                }, options);
                isListening = true;
            }
        }
Ejemplo n.º 7
0
        public void Receive(Action <IDeliveryContext> callback)
        {
            if (_configuration.DispatchOnly)
            {
                throw new InvalidOperationException("Receive is not valid on dispatch only channel.");
            }

            _subscriptionClient.OnMessageAsync(
                async(message) =>
            {
                try
                {
                    var result = await ReceiveAsync(message, callback)
                                 .ConfigureAwait(true);
                }
                catch (Exception e)
                {
                    Log.Warn($"Exception caught in Receive message loop - [{e.Message}]", e);
                }
            },
                new OnMessageOptions
            {
                AutoComplete       = false,
                MaxConcurrentCalls = 1
            });
        }
Ejemplo n.º 8
0
        public static void AzureServiceBusMessages()
        {
            string TopicName        = "Products";
            string subscriptionName = ConfigurationManager.AppSettings["SubscriptionName"];

            Console.Title = $"ASB Receiver of '{subscriptionName}'";

            Console.WriteLine("Subscription: {0}", subscriptionName);
            Console.WriteLine();
            SubscriptionClient productsTopicClient = SubscriptionClient.CreateFromConnectionString(ConfigurationManager.AppSettings["ServiceBusConnectionString"], TopicName, subscriptionName, ReceiveMode.PeekLock);

            productsTopicClient.OnMessageAsync(
                async message =>
            {
                try
                {
                    string messageReceived = message.GetBody <string>();
                    Console.WriteLine("Received Message '{0}'", messageReceived);
                    await message.CompleteAsync();
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine(exception);
                    await message.DeadLetterAsync();
                }
            }, new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 1
            });

            Console.ReadKey();
        }
 public void Run()
 {
     while (true)
     {
         // listen to messages from the aliq server
         ServerBroadcastListener.OnMessageAsync(serverMessage =>
         {
             Console.WriteLine(String.Format("Message body: {0}", serverMessage.GetBody <String>()));
             Console.WriteLine(String.Format("Message id: {0}", serverMessage.MessageId));
             if ((String)serverMessage.Properties["processingMode"] == "processLocalData")
             {
                 return(Task.Factory.StartNew(() => (new LocalDataProcessingHandler()).Run(serverMessage)));
             }
             if ((String)serverMessage.Properties["processingMode"] == "processExternalData")
             {
                 if ((String)serverMessage.Properties["processingNode"] == Environment.MachineName)
                 {
                     return(Task.Factory.StartNew(() => (new ExternalDataProcessingHandler()).Run(serverMessage)));
                 }
                 else
                 {
                     return(Task.Factory.StartNew(() => (new DataUploadHandler()).Run(serverMessage)));
                 }
             }
             return(Task.Factory.StartNew(() => {
                 // a do-nothing task to avoid runtime exceptions?
             }));
         });
     }
 }
Ejemplo n.º 10
0
        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 void OnMessageAsync <T>(Func <T, Task> handler)
 {
     _subscriptionClient.OnMessageAsync(brokeredMessage =>
     {
         var message = GetMessage <T>(brokeredMessage);
         return(handler(message));
     });
 }
Ejemplo n.º 12
0
 public void OnUpdateMessageAsync(Func <BrokeredMessage, Task> callback)
 {
     _subscriptionClient.OnMessageAsync(callback, new OnMessageOptions
     {
         AutoComplete = false,
         //AutoRenewTimeout = TimeSpan.FromMinutes(1),
         MaxConcurrentCalls = 5
     });
 }
Ejemplo n.º 13
0
        public void RegisterReceiver(int eventConcurrency     = DEF_EVENT_CONCURRENT_CALLS,
                                     int analyticsConcurrency = DEF_ANALYTICS_CONCURRENT_CALLS,
                                     int controlConcurrency   = DEF_CONTROL_CONCURRENT_CALLS)
        {
            OnMessageOptions options;

            AssertThingsWorker();

            if (_eventClient != null || _analyticsClient != null || _controlClient != null)
            {
                throw new InvalidOperationException();
            }

            if (eventConcurrency < 1 || eventConcurrency > MAX_EVENT_CONCURRENT_CALLS)
            {
                throw new ArgumentOutOfRangeException("eventConcurrency");
            }

            if (analyticsConcurrency < 1 || analyticsConcurrency > MAX_ANALYTICS_CONCURRENT_CALLS)
            {
                throw new ArgumentOutOfRangeException("analyticsConcurrency");
            }

            if (controlConcurrency < 1 || controlConcurrency > MAX_CONTROL_CONCURRENT_CALLS)
            {
                throw new ArgumentOutOfRangeException("controlConcurrency");
            }

            try
            {
                CreateSubscriptionClients();

                options = new OnMessageOptions {
                    AutoComplete = true, MaxConcurrentCalls = eventConcurrency
                };
                options.ExceptionReceived += ExceptionHandler;
                _eventClient.OnMessageAsync(StorageWriter, options);

                options = new OnMessageOptions {
                    AutoComplete = false, MaxConcurrentCalls = analyticsConcurrency
                };
                options.ExceptionReceived += ExceptionHandler;
                _analyticsClient.OnMessage(Aggregator, options);

                options = new OnMessageOptions {
                    AutoComplete = true, MaxConcurrentCalls = controlConcurrency
                };
                options.ExceptionReceived += ExceptionHandler;
                _controlClient.OnMessageAsync(ControlSystem, options);
            }
            catch
            {
                CloseSubscriptionClients();
                throw;
            }
        }
Ejemplo n.º 14
0
        public ProductManager(StatefulServiceContext context)
            : base(context)
        {
            _products = new ConcurrentBag <Product>(CreateProducts());

            _subscriptionClient =
                SubscriptionClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], "productrequests", "dataRequestMessage");

            _subscriptionClient.OnMessageAsync(ReceiveMessageAsync);
        }
Ejemplo n.º 15
0
 protected MeetupConsumerBase(string connectionString, string topicName, string subscriptionName)
 {
     _client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName);
     _client.OnMessageAsync(async(message) =>
     {
         var meetupMessage = message.GetBody <MeetupMessage>();
         await OnMessageAsync(meetupMessage);
         message.Complete();
         Interlocked.Increment(ref _processedMessagesCount);
     });
 }
Ejemplo n.º 16
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 });
        }
        public void Start(Func<BrokeredMessage, Task> callback)
        {
            lock (_mutex)
            {
                if (_subscriptionClient != null) throw new InvalidOperationException("Already started!");
                _subscriptionClient = _queueManager.CreateSubscriptionReceiver(_topicPath, _subscriptionName);

                _subscriptionClient.OnMessageAsync(callback,
                                                   new OnMessageOptions
                                                   {
                                                       AutoComplete = false,
                                                       MaxConcurrentCalls = _concurrentHandlerLimit,
                                                   });
            }
        }
        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 OpenAsync()
        {
            _client             = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicName, _subscriptionName, ReceiveMode.ReceiveAndDelete);
            _client.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(20), 5);
            _client.OnMessageAsync(async message =>
            {
                await Task.Run(() =>
                {
                    var messageBody    = message.GetBody <string>();
                    var serviceMessage = JsonConvert.DeserializeObject <ServiceMessage>(messageBody);
                    _callback?.Invoke(serviceMessage);
                });
            });

            await Task.Yield();
        }
Ejemplo n.º 20
0
        public void Listen(CancellationToken token)
        {
            SubscriptionClient subscriptionClient = _factory.CreateSubscriptionClient(_topicName, _subscriptionName);

            OnMessageOptions options = new OnMessageOptions
            {
                MaxConcurrentCalls = Environment.ProcessorCount,
                AutoComplete       = false
            };

            Console.WriteLine("Waiting for new orders... \n");

            subscriptionClient.OnMessageAsync(async message =>
            {
                // We only support JSON payloads. Anything else will be moved to the dead letter queue
                // to be handled by another process
                if (message.ContentType != "application/json")
                {
                    await message.DeadLetterAsync("Invalid Content Type", $"Unable to process a message with a Content Type of {message.ContentType}");
                    return;
                }

                Console.WriteLine($"--------------------");
                Console.WriteLine($"New Order Received!");
                Console.WriteLine($"--------------------");
                Console.WriteLine($"Label : {message.Label}");
                Console.WriteLine($"Content Type : {message.ContentType}");
                Console.WriteLine($"Time to Live : {message.TimeToLive.TotalMinutes} minutes\n");

                // Retrieve order from message body
                Stream messageBodyStream  = message.GetBody <Stream>();
                string messageBodyContent = await new StreamReader(messageBodyStream).ReadToEndAsync();
                Order newOrder            = JsonConvert.DeserializeObject <Order>(messageBodyContent);

                Console.WriteLine($"Customer Name: {newOrder.CustomerName}");
                Console.WriteLine($"Item : {newOrder.ItemName}");
                Console.WriteLine($"Unit Price: {newOrder.UnitPrice}");
                Console.WriteLine($"Quantity: {newOrder.Quantity}");
                Console.WriteLine($"----------------");

                // Mark message as comeplete so it can be removed from the subscription
                await message.CompleteAsync();
            }, options);

            token.Register(() => subscriptionClient.CloseAsync());
        }
Ejemplo n.º 21
0
        public async Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            var ns = NamespaceManager.CreateFromConnectionString(_connectionString);

            if (!await ns.SubscriptionExistsAsync(_topicName, _subscriptionName))
            {
                await ns.CreateSubscriptionAsync(_topicName, _subscriptionName);
            }

            var factory = MessagingFactory.CreateFromConnectionString(_connectionString);

            _client = factory.CreateSubscriptionClient(_topicName, _subscriptionName);
            _client.OnMessageAsync(async(message) => await _callback(message));

            // Return the uri - in this case, that's just our connection string
            return(_connectionString);
        }
        public Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            // register the OnMessageAsync callback
            _subscriptionClient.OnMessageAsync(
                async message =>
            {
                using (var messageLock = new MessageLock(message))
                {
                    _logger.StartContext(message.CorrelationId);
                    //make sure that the message is correct
                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //var body = message.GetBody<Stream>();

                        //dynamic messageBody = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd());

                        try
                        {
                            //callback for processing the message
                            await _callback(new ServiceBusSubscriptionListenerModel()
                            {
                                Message = message,
                                token   = cancellationToken
                            });
                        }
                        catch (Exception ex)
                        {
                            //log it here and throw this will move message into dead-letter queue for retry.
                            _logger.LogError("Error while processing Funding calc message", ex);
                            throw;
                        }
                    }

                    //complete the message after processing
                    await messageLock.CompleteAsync();
                }
            },
                new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 8
            });

            // Return the uri - in this case, that's just our connection string
            return(Task.FromResult(_serviceBusConnectionString));
        }
Ejemplo n.º 23
0
        public ServiceBusMessageBus(string connectionString, string topicName)
        {
            _topicName        = topicName;
            _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(OnMessage);
        }
Ejemplo n.º 24
0
        protected override async Task EnsureTopicSubscriptionAsync(CancellationToken cancellationToken)
        {
            if (_subscriptionClient != null)
            {
                return;
            }

            if (!TopicIsCreated)
            {
                await EnsureTopicCreatedAsync(cancellationToken).AnyContext();
            }

            using (await _lock.LockAsync().AnyContext()) {
                if (_subscriptionClient != null)
                {
                    return;
                }

                var sw = Stopwatch.StartNew();
                try {
                    await _namespaceManager.CreateSubscriptionAsync(CreateSubscriptionDescription()).AnyContext();
                } catch (MessagingEntityAlreadyExistsException) { }

                // Look into message factory with multiple recievers so more than one connection is made and managed....
                _subscriptionClient = SubscriptionClient.CreateFromConnectionString(_options.ConnectionString, _options.Topic, _subscriptionName, ReceiveMode.ReceiveAndDelete);
                _subscriptionClient.OnMessageAsync(OnMessageAsync, new OnMessageOptions { /* AutoComplete = true, // Don't run with recieve and delete */
                    MaxConcurrentCalls = 6                                                /* calculate this based on the the thread count. */
                });
                if (_options.SubscriptionRetryPolicy != null)
                {
                    _subscriptionClient.RetryPolicy = _options.SubscriptionRetryPolicy;
                }
                if (_options.PrefetchCount.HasValue)
                {
                    _subscriptionClient.PrefetchCount = _options.PrefetchCount.Value;
                }

                sw.Stop();
                _logger.LogTrace("Ensure topic subscription exists took {0}ms.", sw.ElapsedMilliseconds);
            }
        }
        public override void Run()
        {
            Trace.WriteLine("Starting processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            Client.OnMessageAsync((receivedMessage) =>
            {
                try
                {
                    // Process the message
                    Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
                }
                catch
                {
                    // Handle any message processing specific exceptions here
                }
                return(receivedMessage.CompleteAsync());
            }, new OnMessageOptions());

            CompletedEvent.WaitOne();
        }
Ejemplo n.º 26
0
        private async Task InitializeSubscriptionAsync(string subscriptionName, string correlationId, string defaultFilter, Action <BrokeredMessage> callback)
        {
            TopicDescription topic = await NamespaceManager.GetTopicAsync(TopicName);

            if (await NamespaceManager.SubscriptionExistsAsync(topic.Path, subscriptionName))
            {
                return;
            }

            if (!_subscriptionClient.ContainsKey(subscriptionName))
            {
                RuleDescription defaultRuleDescription = new RuleDescription()
                {
                    Filter = new SqlFilter(string.Concat(string.Format(SUBSCRIPTION_CORRELATION_FILTER, correlationId), " AND ", defaultFilter)),
                    Name   = RuleDescription.DefaultRuleName
                };
                SubscriptionDescription subscriptionDescription = new SubscriptionDescription(topic.Path, subscriptionName)
                {
                    AutoDeleteOnIdle         = ServiceBusConfiguration.AutoDeleteOnIdle,
                    DefaultMessageTimeToLive = ServiceBusConfiguration.DefaultMessageTimeToLive,
                    EnableBatchedOperations  = true,
                    EnableDeadLetteringOnFilterEvaluationExceptions = true,
                    EnableDeadLetteringOnMessageExpiration          = false,
                    LockDuration     = ServiceBusConfiguration.LockDuration,
                    MaxDeliveryCount = ServiceBusConfiguration.MaxDeliveryCount,
                    Name             = subscriptionName
                };
                subscriptionDescription = await NamespaceManager.CreateSubscriptionAsync(subscriptionDescription, defaultRuleDescription);

                _logger.WriteInfo(new LogMessage($"Subscription {subscriptionName} in topic {TopicName} has been created"), LogCategories);

                if (callback != null)
                {
                    SubscriptionClient client = SubscriptionClient.Create(TopicName, subscriptionName, ReceiveMode.PeekLock);
                    client.OnMessageAsync(async(message) => await EvaluateMessageAsync(message, callback), _messageOptions);
                    _logger.WriteInfo(new LogMessage($"Subscription {subscriptionName} has been activated"), LogCategories);
                    _subscriptionClient.Add(subscriptionName, client);
                }
            }
        }
Ejemplo n.º 27
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
            });
        }
 private async Task ListenForTopicMessages(SubscriptionClient client, OnMessageOptions options)
 {
     try
     {
         client.OnMessageAsync(async(message) =>
         {
             try
             {
                 await processMessage(message);
             }
             catch (Exception e)
             {
                 Debug.WriteLine("**** Error ListenForTopicMessages.processMessage " + e.ToString() + " ****");
             }
         });
     }
     catch (Exception e)
     {
         Debug.WriteLine("**** Error ListenForTopicMessages " + e.ToString() + " ****");
         throw;
     }
 }
Ejemplo n.º 29
0
        void InitializeReceiver(SubscriptionClient receiver, ConsoleColor color)
        {
            // register the OnMessageAsync callback
            receiver.OnMessageAsync(
                async message =>
            {
                if (message.Label != null &&
                    message.ContentType != null &&
                    message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) &&
                    message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    var body = message.GetBody <Stream>();

                    dynamic scientist = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd());

                    lock (Console.Out)
                    {
                        Console.ForegroundColor = color;
                        Console.WriteLine(
                            "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," +
                            "\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4},  \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]",
                            message.MessageId,
                            message.SequenceNumber,
                            message.EnqueuedTimeUtc,
                            message.ContentType,
                            message.Size,
                            message.ExpiresAtUtc,
                            scientist.firstName,
                            scientist.name);
                        Console.ResetColor();
                    }
                }
                await message.CompleteAsync();
            },
                new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 1
            });
        }
Ejemplo n.º 30
0
        public void OnMessageAsync(Func <IBrokeredMessage, Task> onMessageAsync)
        {
            var callback = CreateOnMessageAsyncCallback(onMessageAsync);

            _client.OnMessageAsync(callback);
        }
Ejemplo n.º 31
0
 public void OnMessageAsync(Func <BrokeredMessage, Task> callback, EventHandler <ExceptionReceivedEventArgs> exceptionHandler)
 {
     _client.OnMessageAsync(callback, _settings.GetOnMessageOptions(exceptionHandler));
 }
Ejemplo n.º 32
0
 public void OnMessageAsync(Func <BrokeredMessage, Task> callback, OnMessageOptions options)
 {
     _client.OnMessageAsync(callback, options);
 }
        void InitializeReceiver(SubscriptionClient receiver, ConsoleColor color)
        {
            // register the OnMessageAsync callback
            receiver.OnMessageAsync(
                async message =>
                {
                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = message.GetBody<Stream>();

                        dynamic scientist = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd());

                        lock (Console.Out)
                        {
                            Console.ForegroundColor = color;
                            Console.WriteLine(
                                "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," +
                                "\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4},  \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]",
                                message.MessageId,
                                message.SequenceNumber,
                                message.EnqueuedTimeUtc,
                                message.ContentType,
                                message.Size,
                                message.ExpiresAtUtc,
                                scientist.firstName,
                                scientist.name);
                            Console.ResetColor();
                        }
                    }
                    await message.CompleteAsync();
                },
                new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 1 });
        }
 public void OnMessage(Action <IBrokeredMessage> callback, OnMessageOptions onMessageOptions)
 {
     _subscriptionClient.OnMessageAsync(async brokeredMessage => await Task.Run(() =>
                                                                                callback(new BrokeredMessageWrapper(brokeredMessage))),
                                        onMessageOptions);
 }
        private async void btnStart_Click(object sender, EventArgs e)
        {
            if (string.Compare(btnStart.Text, Start, StringComparison.OrdinalIgnoreCase) == 0)
            {
                receiverBrokeredMessageInspector = cboReceiverInspector.SelectedIndex > 0
                                           ? Activator.CreateInstance(serviceBusHelper.BrokeredMessageInspectors[cboReceiverInspector.Text]) as IBrokeredMessageInspector
                                           : null;

                cancellationTokenSource = new CancellationTokenSource();
                btnStart.Text = Stop;
                blockingCollection = new BlockingCollection<Tuple<long, long, long>>();
                timer = new System.Timers.Timer
                {
                    AutoReset = true,
                    Enabled = true,
                    Interval = 1000 * txtRefreshInformation.IntegerValue
                };
                if (startLog != null && checkBoxLogging.Checked)
                {
                    startLog();
                }
                timer.Elapsed += timer_Elapsed;
                autoComplete = checkBoxAutoComplete.Checked;
                logging = checkBoxLogging.Checked;
                verbose = checkBoxVerbose.Checked;
                tracking = checkBoxTrackMessages.Checked;
                try
                {
                    receiveMode = cboReceivedMode.SelectedIndex == 1 ? ReceiveMode.PeekLock : ReceiveMode.ReceiveAndDelete;

                    if (entityDescription is QueueDescription)
                    {
                        var currentQueue = entityDescription as QueueDescription;
                        queueClient = serviceBusHelper.MessagingFactory.CreateQueueClient(currentQueue.Path, receiveMode);
                        queueClient.PrefetchCount = txtPrefetchCount.IntegerValue;
                        if (currentQueue.RequiresSession)
                        {
                           await queueClient.RegisterSessionHandlerFactoryAsync(
                                    new CustomMessageSessionAsyncHandlerFactory(new CustomMessageSessionAsyncHandlerConfiguration
                                    {
                                        Logging = logging,
                                        Tracking = tracking,
                                        AutoComplete = autoComplete,
                                        MessageEncoder = encoder,
                                        ReceiveMode = receiveMode,
                                        GetElapsedTime = GetElapsedTime,
                                        UpdateStatistics = UpdateStatistics,
                                        WriteToLog = writeToLog,
                                        MessageInspector = receiverBrokeredMessageInspector,
                                        ServiceBusHelper = serviceBusHelper,
                                        TrackMessage = bm => Invoke(new Action<BrokeredMessage>(m => messageCollection.Add(m)), bm)
                                    }), GetSessionHandlerOptions());
                        }
                        else
                        {
                            #pragma warning disable 4014
                            Task.Run(() => queueClient.OnMessageAsync(OnMessageAsync, GetOnMessageOptions())); 
                            #pragma warning restore 4014
                        }
                    }

                    if (entityDescription is SubscriptionDescription)
                    {
                        var currentSubscription = entityDescription as SubscriptionDescription;
                        subscriptionClient = serviceBusHelper.MessagingFactory.CreateSubscriptionClient(currentSubscription.TopicPath,
                                                                                                        currentSubscription.Name,
                                                                                                        receiveMode);
                        subscriptionClient.PrefetchCount = txtPrefetchCount.IntegerValue;
                        if (currentSubscription.RequiresSession)
                        {
                            await subscriptionClient.RegisterSessionHandlerFactoryAsync(
                                    new CustomMessageSessionAsyncHandlerFactory(new CustomMessageSessionAsyncHandlerConfiguration
                                    {
                                        Logging = logging,
                                        Tracking = tracking,
                                        AutoComplete = autoComplete,
                                        MessageEncoder = encoder,
                                        ReceiveMode = receiveMode,
                                        GetElapsedTime = GetElapsedTime,
                                        UpdateStatistics = UpdateStatistics,
                                        WriteToLog = writeToLog,
                                        ServiceBusHelper = serviceBusHelper,
                                        TrackMessage = bm => Invoke(new Action<BrokeredMessage>(m => messageCollection.Add(m)), bm)
                                    }), GetSessionHandlerOptions());
                        }
                        else
                        {
                            #pragma warning disable 4014
                            Task.Run(() => subscriptionClient.OnMessageAsync(OnMessageAsync, GetOnMessageOptions())); 
                            #pragma warning restore 4014
                        }
                    }
                    #pragma warning disable 4014
                    Task.Run(new Action(RefreshGraph));          
                    #pragma warning restore 4014
                    GetElapsedTime();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    StopListener().Wait();
                    btnStart.Text = Start;
                }
            }
            else
            {
                try
                {
                    await StopListener();
                    btnStart.Text = Start;
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }