protected async void ReceiveMessages(Func <Message, CancellationToken, Task> handler) { var serviceBusConfiguration = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>(); var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, _topic, _subscriptionName); var rules = await subscriptionClient.GetRulesAsync(); if (rules.Any(x => x.Name == "$Default")) { await subscriptionClient.RemoveRuleAsync("$Default"); } if (!rules.Any(x => x.Name == "filter-store")) { await subscriptionClient.AddRuleAsync(new RuleDescription { Filter = new CorrelationFilter { Label = _storeId }, Name = "filter-store" }); } var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; subscriptionClient.RegisterMessageHandler(handler, mo); }
private bool CheckSubscriptionExists(string _SubscriptionName, ITopicClient _TopicClient, out Microsoft.Azure.ServiceBus.ISubscriptionClient _SubscriptionClient) { _SubscriptionClient = null; if (AzureNamespaceManager == null) { return(false); } try { using (var GetTopicTask = AzureNamespaceManager.Topics.GetByNameAsync(_SubscriptionName)) { GetTopicTask.Wait(); if (GetTopicTask.Result != null && GetTopicTask.Result.Name != null && GetTopicTask.Result.Name.Length > 0) { var TopicManager = GetTopicTask.Result; using (var GetSubscriptionTask = TopicManager.Subscriptions.GetByNameAsync(_SubscriptionName)) { GetSubscriptionTask.Wait(); if (GetSubscriptionTask.Result != null && GetSubscriptionTask.Result.Name != null && GetSubscriptionTask.Result.Name.Length > 0) { _SubscriptionClient = new Microsoft.Azure.ServiceBus.SubscriptionClient(ServiceBusNamespaceConnectionString, _TopicClient.Path, _SubscriptionName); return(true); } } } } } catch (Exception) { } return(false); }
private void ReceiveMessages() { _subscriptionClient = new SubscriptionClient(_serviceBusConfiguration.ConnectionString, _topicName, SubscriptionName); var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; _subscriptionClient.RegisterMessageHandler(Handle, mo); }
private static void ReceiveMessages() { var subscriptionClient = new SubscriptionClient(_serviceBusConfiguration.ConnectionString, TopicName, SubscriptionName); var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; subscriptionClient.RegisterMessageHandler(Handle, mo); Console.ReadLine(); }
public static void Main(string[] args) { var appConfig = GetAppConfig(); Console.WriteLine("==> Config: " + appConfig); var subConnectionString = new ServiceBusConnectionStringBuilder(appConfig.SubEndpoint); var subClient = new Microsoft.Azure.ServiceBus.SubscriptionClient(subConnectionString, appConfig.SubscriptionName); subClient.RegisterMessageHandler(HandleMessage, ErrorHandler); CreateHostBuilder(args).Build().Run(); }
private void ATestTopicAndATestSubscription() { testTopicClient = new TopicClient(ServiceBusConnectionString, TopicName); testSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); // create test subscription namespaceManager = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString); namespaceManager.CreateSubscription(TopicName, TEST_MESSAGE_SUB); options = new OnMessageOptions() { AutoComplete = false, AutoRenewTimeout = TimeSpan.FromMinutes(1), }; }
public bool CreateIfNotExistSubscriptionToPublishSubscribeChannel(string connectionstring, string path, string subscription, string origin, bool all) { var configuration = JsonConvert.DeserializeObject <ServiceBusConfiguration>(connectionstring); var serviceBusNamespace = GetServiceBusNamespace(configuration); if (serviceBusNamespace != null) { try { var topic = serviceBusNamespace.Topics.GetByName(path); try { topic.Subscriptions.GetByName(subscription); return(false); } catch (CloudException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { topic.Subscriptions.Define(subscription) .WithDefaultMessageTTL(TimeSpan.FromDays(14)) .WithMessageLockDurationInSeconds(300) .Create(); var subs = new Microsoft.Azure.ServiceBus.SubscriptionClient(configuration.ConnectionString, path, subscription); if (!all) { subs.RemoveRuleAsync("$Default").GetAwaiter().GetResult(); var ruledescriptor = new RuleDescription("$Default", new SqlFilter($"origin='{origin}'")); subs.AddRuleAsync(ruledescriptor).GetAwaiter().GetResult(); } return(true); } } } catch (Exception) { return(false); } } return(false); }
private bool EnsureSubscriptionExists(string _SubscriptionName, ITopicClient _TopicClient, out Microsoft.Azure.ServiceBus.ISubscriptionClient _SubscriptionClient, Action <string> _ErrorMessageAction) { bool bExists = CheckSubscriptionExists(_SubscriptionName, _TopicClient, out _SubscriptionClient); if (!bExists) { if (AzureNamespaceManager == null) { return(false); } try { using (var GetTopicTask = AzureNamespaceManager.Topics.GetByNameAsync(_SubscriptionName)) { GetTopicTask.Wait(); if (GetTopicTask.Result != null && GetTopicTask.Result.Name != null && GetTopicTask.Result.Name.Length > 0) { var TopicManager = GetTopicTask.Result; using (var CreateSubscriptionTask = TopicManager.Subscriptions.Define(_SubscriptionName).CreateAsync()) { CreateSubscriptionTask.Wait(); if (CreateSubscriptionTask.Result != null && CreateSubscriptionTask.Result.Name != null && CreateSubscriptionTask.Result.Name.Length > 0) { _SubscriptionClient = new Microsoft.Azure.ServiceBus.SubscriptionClient(ServiceBusNamespaceConnectionString, _TopicClient.Path, _SubscriptionName); bExists = true; } } } } } catch (Exception e) { bExists = false; _ErrorMessageAction?.Invoke("BPubSubServiceAzure->EnsureSubscriptionExists->Callback: " + e.Message + ", Trace: " + e.StackTrace); if (e.InnerException != null && e.InnerException != e) { _ErrorMessageAction?.Invoke("BPubSubServiceAzure->EnsureSubscriptionExists->Inner: " + e.InnerException.Message + ", Trace: " + e.InnerException.StackTrace); } } } return(bExists); }
private static async void ReceiveMessages() { var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, Topic, SubscriptionName); await subscriptionClient.RemoveRuleAsync("$Default"); await subscriptionClient.AddRuleAsync(new RuleDescription { Filter = new CorrelationFilter { Label = _storeId }, Name = "filter-store" }); var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; subscriptionClient.RegisterMessageHandler(Handle, mo); }
private async void ReceiveMessages() { var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, TopicProduction, SubscriptionName); //by default a 1=1 rule is added when subscription is created, so we need to remove it await subscriptionClient.RemoveRuleAsync("$Default"); await subscriptionClient.AddRuleAsync(new RuleDescription { Filter = new CorrelationFilter { Label = _storeId }, Name = "filter-store" }); var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; subscriptionClient.RegisterMessageHandler(Handle, mo); }
private async void GetOrder() { string connectionString = _configuration["serviceBus:connectionString"]; var subscriptionClient = new Microsoft.Azure.ServiceBus.SubscriptionClient(connectionString, "newOrder", "mySubscrition"); await subscriptionClient.RemoveRuleAsync("$Default"); await subscriptionClient.AddRuleAsync(new RuleDescription { Filter = new CorrelationFilter { Label = "LosAngeles" }, Name = "filter-store" }); var mo = new MessageHandlerOptions(ExceptionHandle) { AutoComplete = true }; subscriptionClient.RegisterMessageHandler(Handle, mo); }
internal static AzureInboundMessage <TContent> LoadFromBrokeredMessage(Microsoft.Azure.ServiceBus.Message inboundMessage, SubscriptionType subscriptioType, IMessageSerializer serializer, Microsoft.Azure.ServiceBus.SubscriptionClient subscription) { var content = serializer.Deserialize <TContent>(inboundMessage.Body); var msg = new AzureInboundMessage <TContent> { innerMessage = inboundMessage, azureSubscription = subscription, Content = content, subscriptionIsReceiveAndDelete = subscriptioType == SubscriptionType.ReceiveAndDelete, //This probably isnt necessary CorrelationId = inboundMessage.CorrelationId, ReceivedTime = DateTimeOffset.UtcNow, MessageId = inboundMessage.MessageId, }; return(msg); }
public static SubscriptionClient Create(ServiceBusEntityConnection topicConnection, string subscriptionName) { return(SubscriptionClient.Create(topicConnection, subscriptionName, ReceiveMode.PeekLock)); }
public static SubscriptionClient Create(ServiceBusNamespaceConnection namespaceConnection, string topicPath, string subscriptionName) { return(SubscriptionClient.Create(namespaceConnection, topicPath, subscriptionName, ReceiveMode.PeekLock)); }
public async Task Run(string connectionString) { // Start senders and receivers: Console.WriteLine("\nLaunching senders and receivers..."); var topicClient = new TopicClient(connectionString, TopicName); Console.WriteLine("Preparing to send messages to {0}...", topicClient.Path); // Send messages to queue: Console.WriteLine("Sending messages to topic {0}", topicClient.Path); var rand = new Random(); for (var i = 0; i < 100; ++i) { var msg = new Message() { TimeToLive = TimeSpan.FromMinutes(2), UserProperties = { { "Priority", rand.Next(1, 4) } } }; await topicClient.SendAsync(msg); this.OutputMessageInfo("Sent: ", msg); } Console.WriteLine(); // All messages sent Console.WriteLine("\nSender complete."); // start receive Console.WriteLine("Receiving messages by priority ..."); var subClient1 = new Microsoft.Azure.ServiceBus.SubscriptionClient(connectionString, TopicName, "Priority1Subscription", ReceiveMode.PeekLock); var subClient2 = new Microsoft.Azure.ServiceBus.SubscriptionClient(connectionString, TopicName, "Priority2Subscription", ReceiveMode.PeekLock); var subClient3 = new Microsoft.Azure.ServiceBus.SubscriptionClient(connectionString, TopicName, "PriorityGreaterThan2Subscription", ReceiveMode.PeekLock); Func <SubscriptionClient, Message, CancellationToken, Task> callback = (c, message, ct) => { this.OutputMessageInfo("Received: ", message); return(Task.CompletedTask); }; subClient1.RegisterMessageHandler((m, c) => callback(subClient1, m, c), new MessageHandlerOptions(LogMessageHandlerException) { MaxConcurrentCalls = 10, AutoComplete = true }); subClient2.RegisterMessageHandler((m, c) => callback(subClient1, m, c), new MessageHandlerOptions(LogMessageHandlerException) { MaxConcurrentCalls = 5, AutoComplete = true }); subClient3.RegisterMessageHandler((m, c) => callback(subClient1, m, c), new MessageHandlerOptions(LogMessageHandlerException) { MaxConcurrentCalls = 1, AutoComplete = true }); Task.WaitAny( Task.Run(() => Console.ReadKey()), Task.Delay(TimeSpan.FromSeconds(10))); await Task.WhenAll(subClient1.CloseAsync(), subClient2.CloseAsync(), subClient3.CloseAsync()); }
public static MessagingOptions UseServiceBusBroker( this MessagingOptions options, Action <IMessageBroker> brokerAction = null, string topicName = null, string subscriptionName = null, int?retries = null, TimeSpan?expiration = null, string section = "naos:messaging:serviceBus") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); subscriptionName ??= options.Context.Descriptor.Name.ToLower(); var configuration = options.Context.Configuration.GetSection(section).Get <ServiceBusConfiguration>(); if (configuration?.Enabled == true) { configuration.EntityPath = topicName ?? $"{Environment.GetEnvironmentVariable(EnvironmentKeys.Environment) ?? "Production"}-Naos.Messaging"; options.Context.Services.AddSingleton <IServiceBusProvider>(sp => { return(new ServiceBusProvider( sp.GetRequiredService <ILogger <ServiceBusProvider> >(), SdkContext.AzureCredentialsFactory.FromServicePrincipal(configuration.ClientId, configuration.ClientSecret, configuration.TenantId, AzureEnvironment.AzureGlobalCloud), configuration)); }); options.Context.Services.AddSingleton <Microsoft.Azure.ServiceBus.ISubscriptionClient>(sp => { var logger = sp.GetRequiredService <ILogger <ServiceBusMessageBroker> >(); var provider = sp.GetRequiredService <IServiceBusProvider>(); provider.EnsureTopicSubscription(provider.ConnectionStringBuilder.EntityPath, subscriptionName); var client = new Microsoft.Azure.ServiceBus.SubscriptionClient(provider.ConnectionStringBuilder, subscriptionName); try { client .RemoveRuleAsync(RuleDescription.DefaultRuleName) .GetAwaiter() .GetResult(); } catch (MessagingEntityNotFoundException) { // do nothing, default rule not found } client.RegisterMessageHandler( async(m, t) => { //this.logger.LogInformation("message received (id={MessageId}, name={MessageName})", message.MessageId, message.Label); if (await ServiceBusMessageBroker.ProcessMessage( logger, (ITracer)sp.CreateScope().ServiceProvider.GetService(typeof(ITracer)), sp.GetRequiredService <ISubscriptionMap>(), new ServiceProviderMessageHandlerFactory(sp), DefaultSerializer.Create, subscriptionName, (IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator)), m).AnyContext()) { // complete message so it is not received again await client.CompleteAsync(m.SystemProperties.LockToken).AnyContext(); } }, new MessageHandlerOptions(args => { var context = args.ExceptionReceivedContext; logger.LogWarning($"{{LogKey:l}} servicebus handler error: topic={context?.EntityPath}, action={context?.Action}, endpoint={context?.Endpoint}, {args.Exception?.Message}, {args.Exception?.StackTrace}", LogKeys.AppMessaging); return(Task.CompletedTask); }) { MaxConcurrentCalls = 10, AutoComplete = false, MaxAutoRenewDuration = new TimeSpan(0, 5, 0) }); return(client); }); options.Context.Services.AddScoped <IMessageBroker>(sp => // TODO: scoped with ITracer injected { var broker = new ServiceBusMessageBroker(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Tracer(sp.GetService <ITracer>()) .Mediator(sp.GetService <IMediator>()) .Provider(sp.GetRequiredService <IServiceBusProvider>()) // singleton .Client(sp.GetRequiredService <Microsoft.Azure.ServiceBus.ISubscriptionClient>()) // singleton .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp)) .Subscriptions(sp.GetRequiredService <ISubscriptionMap>()) // singleton .SubscriptionName(subscriptionName) //AppDomain.CurrentDomain.FriendlyName, // PRODUCT.CAPABILITY //.MessageScope(options.Context.Descriptor.Name) .Retries(retries) .Expiration(expiration) .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool() ? Environment.MachineName.Humanize().Dehumanize().ToLower() : string.Empty)); brokerAction?.Invoke(broker); return(broker); }); // scope the messagebus messages to the local machine, so local events are handled locally options.Context.Services.AddHealthChecks() .AddAzureServiceBusTopic(configuration.ConnectionString, configuration.EntityPath, "messaging-broker-servicebus"); options.Context.Messages.Add($"naos services builder: messaging added (broker={nameof(ServiceBusMessageBroker)})"); } else { throw new NaosException("no messaging servicebus is enabled"); } return(options); }