static async Task MainAsync() { try { subscriptionClient = new SubscriptionClient(serviceBusConnectionString, topicName, subscriptionName); //var builder = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); ////subscriptionClient = new SubscriptionClient(serviceBusConnectionString, topicName, subscriptionClient); //subscriptionClient = new SubscriptionClient(builder, subscriptionName); //subscriptionClient = new SubscriptionClient() Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadKey(); await subscriptionClient.CloseAsync(); } catch (Exception ex) { int p = 90; } }
/// <summary> /// Registers the topic client for subscription /// </summary> private void RegisterMessageHandler(ISubscriptionClient subscriptionClient, ConstructorCreateMode constructorCreateMode) { var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 1, AutoComplete = false }; switch (constructorCreateMode) { case ConstructorCreateMode.SingleUse: subscriptionClient.RegisterMessageHandler(RegisterSubscription1, messageHandlerOptions); break; case ConstructorCreateMode.WithTopic: subscriptionClient.RegisterMessageHandler(RegisterSubscription2, messageHandlerOptions); break; case ConstructorCreateMode.OnlyConnectionString: subscriptionClient.RegisterMessageHandler(RegisterSubscription3, messageHandlerOptions); break; default: throw new InvalidOperationException("Invalid constructor mode"); } }
public async Task NoMessage_Should_Trigger_Timeout() { ISubscriptionClient subscriptionClient = _serviceBusResource.GetSubscriptionClient("foo", "test1"); await Assert.ThrowsAsync <TaskCanceledException>(() => subscriptionClient.AwaitMessageAsync(DeserializeAsync <UserCreated>, TimeSpan.FromSeconds(5))); }
public AlterationFinishedMessageHandler( ISubscriptionClient subscriptionClient, string serviceBusConnectionString, string subscriptionName, IApiClient apiClient) : base(subscriptionClient, serviceBusConnectionString, subscriptionName, apiClient) { }
public async Task SendEvent_Received() { // arrange var ev = new UserEvent() { Type = "USER_ADDED", UserId = "A1" }; ITopicClient topicClient = _serviceBusResource.GetTopicClient("userevents"); var broker = new UserEventBroker(topicClient); //act await broker.SendEventAsync(ev); //assert ISubscriptionClient subscriptionClient = _serviceBusResource.GetSubscriptionClient("userevents", "audit"); var completion = new TaskCompletionSource <UserEvent>(); subscriptionClient.RegisterMessageHandler((message, ct) => { var json = Encoding.UTF8.GetString(message.Body); UserEvent ev = JsonSerializer.Deserialize <UserEvent>(json); completion.SetResult(ev); return(Task.CompletedTask); }, new MessageHandlerOptions(ExceptionReceivedHandler)); UserEvent reveivedEvent = await completion.Task; reveivedEvent.Should().BeEquivalentTo(ev); }
static async Task MainAsync() { string ServiceBusConnectionString = "Endpoint=sb://licenseplatepublisher.servicebus.windows.net/;SharedAccessKeyName=ConsumeReads;SharedAccessKey=VNcJZVQAVMazTAfrssP6Irzlg/pKwbwfnOqMXqROtCQ="; string TopicName = "licenseplateread"; string SubscriptionName = "fbS8qDfztJHYbf2G"; subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); updateVoitures_Recherche(); ServiceBusConnectionString = "Endpoint=sb://licenseplatepublisher.servicebus.windows.net/;SharedAccessKeyName=listeneronly;SharedAccessKey=w+ifeMSBq1AQkedLCpMa8ut5c6bJzJxqHuX9Jx2XGOk="; TopicName = "wantedplatelistupdate"; SubscriptionName = "8wQLDabncqUFjdTk"; subscriptionClient_notif = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); //liste voitures recherches // Console.WriteLine($"Received message: UserInfo:{resp}"); // Register subscription message handler and receive messages in a loop. RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadKey(); await subscriptionClient.CloseAsync(); await subscriptionClient_notif.CloseAsync(); }
private static async Task MainAsync() { _subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); RegisterMessageHandler(); Console.ReadKey(); await _subscriptionClient.CloseAsync(); }
public OrderPaidMessageHandler( ISubscriptionClient subscriptionClient, string serviceBusConnectionString, string subscriptionName, IApiClient apiClient) : base(subscriptionClient, serviceBusConnectionString, subscriptionName, apiClient) { }
public ServiceBusConsumer(ILogger logger, IConfigurationSection config, MessageHandler handler) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _logger = logger; logger.LogInformation("Starting consumer"); var sboptions = new ServiceBusConsumerConfig(); config.Bind(sboptions); var connectionString = new ServiceBusConnectionStringBuilder(sboptions.EndpointAddress, sboptions.Topic, sboptions.AuthKeyName, sboptions.AuthKey); topicClient = new TopicClient(connectionString); var messageProcessorHostName = Guid.NewGuid().ToString(); var processor = new ServiceBusMessageProcessor(topicClient, logger, handler); var handlerOptpions = new MessageHandlerOptions(processor.LogException); handlerOptpions.AutoComplete = true; subscriptionClient = new SubscriptionClient(connectionString, sboptions.Subscription); subscriptionClient.RegisterMessageHandler(processor.Process, handlerOptpions); }
public async Task ReceiveMessagesAsync(string receiver, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(receiver)) { throw new ArgumentNullException(nameof(receiver), "Receiver cannot be null"); } try { this.subscriptionClient = new SubscriptionClient(this.connectionString, this.topicName, this.subscriptionName); this.logger.LogInformation("Subscription client for the {TopicName} topic has been created", this.topicName); await this.HandlerSubscriptionRules(receiver); this.RegisterOnMessageHandlerAndReceiveMessages(); await Task.Delay(-1, cancellationToken); await this.subscriptionClient.CloseAsync(); } catch (Exception exception) { this.logger.LogError("Error in queue client for the {TopicName} topic: {Exception}", this.topicName, exception.Message); throw; } }
/// <summary> /// Subscribe action to read queue messages /// </summary> /// <param name="topicClient">type to extend</param> /// <param name="onMessageReceived">Action invoked when message arrive</param> /// <param name="settingData">Setting infomrations</param> /// <param name="typeToDeserialize">Type used to deserialize message</param> #if NETCOREAPP3_1 || NET5_0 public static void SubscribeCompressor(this ISubscriptionClient topicClient, Action <MessageReceivedEventArgs> onMessageReceived, StorageSettingData settingData, Type typeToDeserialize) { ReaderExtender <ISubscriptionClient> topicMessageReader = new ReaderExtender <ISubscriptionClient>(topicClient, settingData, typeToDeserialize); topicMessageReader.Subscribe(onMessageReceived); }
public void RecieveMessage() { log.LogInformation("RecieveMessage called."); try { // ServiceBus Subscription if (subscriptionClient == null || subscriptionClient.IsClosedOrClosing) { subscriptionClient = new SubscriptionClient(serviceBusConnectionString, topicName, subscriptionName, ReceiveMode.PeekLock); } subscriptionClient.RegisterMessageHandler( async(message, token) => { var messageJson = Encoding.UTF8.GetString(message.Body); log.LogInformation($"Message was picked up by ChatHub.ReceiveMessage method. Body: {messageJson}"); // Send the ReceiveMessage event back to the browser client. await hubContext.Clients.All.SendAsync("ReceiveMessage", messageJson); await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); }, new MessageHandlerOptions(async args => Console.WriteLine(args.Exception)) { MaxConcurrentCalls = 1, AutoComplete = false }); } catch (Exception e) { log.LogError("Exception: " + e.Message); } }
public void Listen() { subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); RetryPolicy policy = new RetryExponential(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(29), 10); subscriptionClient.ServiceBusConnection.RetryPolicy = policy; var sessionOptions = new SessionHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false, MaxConcurrentSessions = _concurrentSessions, MaxAutoRenewDuration = TimeSpan.FromSeconds(20) //MessageWaitTimeout = TimeSpan.FromSeconds(30) }; subscriptionClient.PrefetchCount = 250; subscriptionClient.RegisterSessionHandler(OnMessage, sessionOptions); if (_autoTryReconnect) { while (true) { Task.Delay(10000).GetAwaiter().GetResult(); TryReconnect(); } } }
static void Main(string[] args) { string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMj/JGvVvUZ64U21IBI="; string sbTopic = "offers"; string sbSubscription = "akki5677"; try { subscriptionClient = new SubscriptionClient(sbConnectionString, sbTopic, sbSubscription); var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 1, AutoComplete = false }; subscriptionClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.ReadKey(); subscriptionClient.CloseAsync(); } }
public async void TryReconnect() { if (MessagesListedBySession.Count == 0 && _sessionsInitializedCount >= _concurrentSessions) { _sessionsInitializedCount = 0; try { await subscriptionClient.CloseAsync(); } catch (Exception ex) { if (!(logger is null)) { logger.LogWarning(ex.Message); } } subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); var sessionOptions = new SessionHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false, MaxConcurrentSessions = _concurrentSessions, MaxAutoRenewDuration = TimeSpan.FromSeconds(10) }; subscriptionClient.PrefetchCount = 250; subscriptionClient.RegisterSessionHandler(OnMessage, sessionOptions); } }
static async Task MainAsync() { topicClient = new TopicClient(ServiceBusConnectionString, TopicName); empCreateFilterSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, "EmployeeCreate"); empDeleteFilterSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, "EmployeeDelete"); // Receive messages from 'allMessagesSubscriptionName'. Should receive all 9 messages await ReceiveMsg(empCreateFilterSubscriptionClient); // Receive messages from 'sqlFilterOnlySubscriptionName'. Should receive all messages with Color = 'Red' i.e 3 messages await ReceiveMsg(empDeleteFilterSubscriptionClient); Console.WriteLine("========================================================="); Console.WriteLine("Completed Receiving all messages... Press any key to exit"); Console.WriteLine("========================================================="); Console.ReadKey(); await empCreateFilterSubscriptionClient.CloseAsync(); await empDeleteFilterSubscriptionClient.CloseAsync(); await topicClient.CloseAsync(); }
public InvitationReceieverService(ISubscriptionClient subscriptionClient , EmailHandler emailHandler, ILogger<InvitationReceieverService> logger) { _EmailHandler = emailHandler; _SubscriptionClient = subscriptionClient; _Logger = logger; }
static async Task MainAsync() { subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = 1, // Indicates whether MessagePump should automatically complete the messages after returning from User Callback. // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below. AutoComplete = false }; // Register the function that processes messages. subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); Console.ReadKey(); await subscriptionClient.CloseAsync(); }
/// <summary> /// Subscribe action to read queue messages /// </summary> /// <param name="topicClient">type to extend</param> /// <param name="topicName">Topic's name for the message</param> /// <param name="serviceBusConnectionStringName">Topic connection string name (must be present in sbcsettings.json file)</param> /// <param name="onMessageReceived">Action invoked when message arrive</param> /// <param name="messageDeserializer">Object used to deserialize message</param> /// <returns></returns> #if NETCOREAPP3_1 || NET5_0 public static void SubscribeCompressor(this ISubscriptionClient topicClient, Action <MessageReceivedEventArgs> onMessageReceived, IMessageDeserializer messageDeserializer) { ReaderExtender <ISubscriptionClient> topicMessageReader = new ReaderExtender <ISubscriptionClient>(topicClient, messageDeserializer); topicMessageReader.Subscribe(onMessageReceived); }
static void Main(string[] args) { try { //connect to subscription subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); //funcion que va a manejar la llegada de los mensajes var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = 1, // Indicates whether MessagePump should automatically complete the messages after returning from User Callback. // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below. AutoComplete = false }; // Register the function that will process messages subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); //TODO: should close the conection when the application ends //queueClient.CloseAsync().Wait(); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadKey(); }
public static async Task Main(string[] args) { const int numberOfMessages = 10; topicClient = new TopicClient(ServiceBusConnectionString, TopicName); subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); 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(); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadKey(); await subscriptionClient.CloseAsync(); }
public static Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { string connectionStringServiceBus = "Endpoint=sb://plenttdata.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=H04PgzviylO3hman4MOuXfSWPHgrCUDOKd5835UQYas="; string topicName = "pletopic"; string SubscriptionName = "plesubscription"; subscriptionClient = new SubscriptionClient(connectionStringServiceBus, topicName, SubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press any key to exit after receiving all the messages."); Console.WriteLine("======================================================"); var newRule = new RuleDescription("FilteredRule", new SqlFilter("From LIKE '%manhduc'")); subscriptionClient.AddRuleAsync(newRule); topicClient = new TopicClient(connectionStringServiceBus, topicName); RegisterMessageHandlerAndReceiveMessages(); Console.ReadKey(); topicClient.CloseAsync().Wait(); return(null); }
static async Task MainAsync() { const int numberOfMessages = 10; topicClient = new TopicClient(ServiceBusConnectionString, TopicName); subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); // Ensure default rule exists await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName); await subscriptionClient.AddRuleAsync(new RuleDescription(RuleDescription.DefaultRuleName, new TrueFilter())); Console.WriteLine("======================================================"); Console.WriteLine("Press any key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register Subscription's MessageHandler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); // Send Messages await SendMessagesAsync(numberOfMessages); Console.ReadKey(); await subscriptionClient.CloseAsync(); await topicClient.CloseAsync(); }
/// <summary> /// Subscribe to a Topic /// </summary> /// <param name="token">Cancellation Token</param> /// <returns></returns> public async Task Subscribe() { ManagementClient client = null; try { client = new ManagementClient(_serviceBusOptions.Value.ConnectionString); //Create Subscription if it doesn't exists if (!await client.SubscriptionExistsAsync(_serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription).ConfigureAwait(false)) { await client.CreateSubscriptionAsync(_serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription).ConfigureAwait(false); } // Log information _logger.LogInformation($"Subscribed to Topic : {_serviceBusOptions.Value.ProductUpdatedTopic} , Subscription Name : {_serviceBusOptions.Value.ProductUpdatedSubscription}"); //Create subscription client _subscriptionClient = new SubscriptionClient(_serviceBusOptions.Value.ConnectionString, _serviceBusOptions.Value.ProductUpdatedTopic, _serviceBusOptions.Value.ProductUpdatedSubscription); //Process Messages RegisterOnMessageHandlerAndReceiveMessage(); } catch (Exception ex) { _logger.LogError($"Error in receiving message from topic {_serviceBusOptions.Value.ProductUpdatedTopic}, , Subscription Name : { _serviceBusOptions.Value.ProductUpdatedSubscription} , ex - {ex}"); throw; } finally { await client.CloseAsync().ConfigureAwait(false); } }
public async Task Subscribe() { try { _subscriptionMesssage = GetSubscriptions(); if (_subscriptionMesssage != null) { _subscriptionClient = new SubscriptionClient(_subscriptionMesssage.PrimaryConnectionString , _subscriptionMesssage.TopicName, _subscriptionMesssage.SubscriptionName); // Console.WriteLine("======================================================"); // Console.WriteLine("Press ENTER key to exit after receiving all the messages."); // Console.WriteLine("======================================================"); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); } } catch (Exception ex) { _logger.LogError("Error - Subscription {Details}", ex); } finally { Console.ReadKey(); await _subscriptionClient.CloseAsync(); } }
static async Task MainAsync() { const int numberOfMessages = 10; topicClient = new TopicClient(ServiceBusConnectionString, TopicName); firstSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, FirstSubscriptionName); secondSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SecondSubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press any key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register Subscription's MessageHandler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); // Send Messages await SendMessagesAsync(numberOfMessages); Console.ReadKey(); await firstSubscriptionClient.CloseAsync(); await secondSubscriptionClient.CloseAsync(); await topicClient.CloseAsync(); }
static async Task Main(string[] args) { var builder = new ConfigurationBuilder(); // tell the builder to look for the appsettings.json file builder .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddUserSecrets <Program>(); Configuration = builder.Build(); // Create a Subscription Client here subscriptionClient = new SubscriptionClient(Configuration["ConnectionString"], TopicName, SubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register subscription message handler and receive messages in a loop RegisterMessageHandler(); Console.Read(); // Close the subscription here await subscriptionClient.CloseAsync(); }
public static async Task Main(string[] args) { topicClient = new TopicClient(ServiceBusConnectionString, TopicName); // Client to look out for status messages statusSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, StatusSubscription); // Create everything we need await ConfigureServiceBusAsync(); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after sending all the messages."); Console.WriteLine("======================================================"); // Send messages. await Task.WhenAll( SendMessagesAsync(Guid.NewGuid().ToString(), "Renderer"), SendMessagesAsync(Guid.NewGuid().ToString(), "Renderer"), SendMessagesAsync(Guid.NewGuid().ToString(), "Renderer"), SendMessagesAsync(Guid.NewGuid().ToString(), "Renderer") ); Console.ReadKey(); await topicClient.CloseAsync(); }
public NotificationService( ISubscriptionClient subscriptionClient, IServiceScopeFactory serviceScopeFactory) { _subscriptionClient = subscriptionClient; _serviceScopeFactory = serviceScopeFactory; }
async static Task Main(string[] args) { _logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); _logger.Information("Testando o consumo de mensagens com Azure Service Bus"); _logger.Information("Carregando configurações..."); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.json"); var configuration = builder.Build(); string nomeTopic = configuration["AzureServiceBus:Topic"]; string subscription = configuration["AzureServiceBus:Subscription"]; _subscriptionClient = new SubscriptionClient( configuration["AzureServiceBus:ConnectionString"], nomeTopic, subscription); _logger.Information($"Topic = {nomeTopic}"); _logger.Information($"Subscription = {nomeTopic}"); _conexaoRedis = ConnectionMultiplexer.Connect(configuration["BaseCotacoes"]); _logger.Information("Aguardando mensagens..."); _logger.Information("Pressione Enter para encerrar"); RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadLine(); await _subscriptionClient.CloseAsync(); _logger.Warning("Encerrando o processamento de mensagens!"); }
public SubscriptionController() { this._mollieClient = new MollieClient(AppSettings.MollieApiKey); }
/// <summary> /// Creates new SubscriptionsClient instance /// </summary> /// <param name="subscriptionClient">The subscription client instance</param> public SubscriptionsClient(ISubscriptionClient subscriptionClient) { this.SubscriptionClient = subscriptionClient; }