private async Task SendMessage(ISenderClient queue, object obj) { var serialized = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var message = new Message(Encoding.UTF8.GetBytes(serialized)); try { await queue.SendAsync(message); } catch (Exception) { var key = $"{queue.Path}_cache"; var messages = _cache.Get <List <Message> >(key); messages ??= new List <Message>(); messages.Add(message); _cache.Set(key, messages, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12) }); } }
public void Start(ISenderCallback callback) { _callback = callback; // The variance here should be in constructing the sending & buffer blocks if (_endpoint.TopicName.IsEmpty()) { _sender = _transport.TokenProvider != null ? new MessageSender(_transport.ConnectionString, _endpoint.QueueName, _transport.TokenProvider, _transport.TransportType, _transport.RetryPolicy) : new MessageSender(_transport.ConnectionString, _endpoint.QueueName, _transport.RetryPolicy); _sending = new ActionBlock <Envelope>(sendBySession, new ExecutionDataflowBlockOptions { CancellationToken = _cancellation }); } else { _sender = _transport.TokenProvider != null ? new TopicClient(_transport.ConnectionString, _endpoint.TopicName, _transport.TokenProvider, _transport.TransportType, _transport.RetryPolicy) : new TopicClient(_transport.ConnectionString, _endpoint.TopicName, _transport.RetryPolicy); _sending = new ActionBlock <Envelope>(sendBySession, new ExecutionDataflowBlockOptions { CancellationToken = _cancellation }); } }
private T GetClient <T>(string asbNsConnectionString, string entityName) where T : class, ISenderClient { ISenderClient result = null; string key = $"{asbNsConnectionString};EntityPath={entityName}"; if (this.Clients.ContainsKey(key)) { result = this.Clients[key]; } else { if (typeof(T).Equals(typeof(QueueClient))) { result = new QueueClient(asbNsConnectionString, entityName); } else if (typeof(T).Equals(typeof(TopicClient))) { result = new TopicClient(asbNsConnectionString, entityName); } if (result != null) { this.Clients.Add(key, result); } } return(result as T); }
public async Task SendAsync(string channelName, IEnumerable <QueueMessage> messages, CancellationToken cancellationToken = default) { ISenderClient client = CreateOrGetSenderClient(channelName); IList <Message> sbmsg = messages.Select(Converter.ToMessage).ToList(); await client.SendAsync(sbmsg).ConfigureAwait(false); }
static async Task Write(ISenderClient client, Message message) { Type clientType = client.GetType(); if (client.GetType() == typeof(SubscriptionClient)) { Console.WriteLine("Cannot write message to subscription only topic or queue, please remove subscription Id"); return; } try { await client.SendAsync(message); } catch (Exception e) { Console.WriteLine($"Ooops, sending messsage failed: {e}"); return; } if (Verbose) { Console.WriteLine($"Sent message: {message}"); } }
public Resender(string connectionString, ResenderArguments a) : base(connectionString, EntityNameHelper.FormatDeadLetterPath(a.Type == BusType.Queue ? a.TopicQueueName : EntityNameHelper.FormatSubscriptionPath(a.TopicQueueName, a.Name))) { Sender = a.Type == BusType.Queue ? (ISenderClient) new QueueClient(connectionString, a.TopicQueueName) : new TopicClient(connectionString, a.TopicQueueName); }
private async Task sendBySession(Envelope envelope, ISenderClient senderClient) { try { var message = _protocol.WriteFromEnvelope(envelope); message.SessionId = Guid.NewGuid().ToString(); if (envelope.IsDelayed(DateTime.UtcNow)) { await senderClient.ScheduleMessageAsync(message, envelope.ExecutionTime.Value); } else { await senderClient.SendAsync(message); } await _callback.Successful(envelope); } catch (Exception e) { try { await _callback.ProcessingFailure(envelope, e); } catch (Exception exception) { _logger.LogException(exception); } } }
private void InitializeClients(ChannelType channelType) { var channelName = _configuration.GetServiceBusChannelName(channelType, _channel); var retryPolicy = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), 10); var connectionString = _configuration.GetServiceBusConnectionString(); switch (channelType) { case ChannelType.PublishSubscribe: _receiverClient = new SubscriptionClient(connectionString, channelName, _subscriptionName, retryPolicy: retryPolicy); _senderClient = new TopicClient(connectionString, channelName, retryPolicy); break; case ChannelType.PointToPoint: var queueClient = new QueueClient(connectionString, channelName, ReceiveMode.PeekLock, retryPolicy); _receiverClient = queueClient; _senderClient = queueClient; break; default: throw new Exception($"Unkown channel type {channelType}"); } string deadPath = EntityNameHelper.FormatDeadLetterPath(_receiverClient.Path); _deadLetterQueue = new MessageReceiver(connectionString, deadPath, ReceiveMode.PeekLock); }
private async Task HandleReceivedMessage(IReceiverClient receiverClient, ISenderClient senderClient, Message message, CancellationToken token) { var eventName = message.Label; var messageData = Encoding.UTF8.GetString(message.Body); await ProcessEvent(eventName, messageData); // Complete the message so that it is not received again. await receiverClient.CompleteAsync(message.SystemProperties.LockToken); var eventType = _subscriptionsManager.GetEventTypeByName(eventName); if (eventType != null && eventType != typeof(CompletedEvent)) { var eventData = JObject.Parse(messageData); if (Guid.TryParse((string)eventData["Id"], out var eventId)) { var publisherId = (string)eventData["PublisherId"]; var completedEvent = new CompletedEvent(eventId, publisherId); await PublishEventAsync(completedEvent, senderClient); } } }
private async Task SendAsync(ISenderClient topicClient) { int tries = 0; Message message; try { while (true) { if (_messages.Count <= 0) { break; } lock (_messages) { message = _messages.FirstOrDefault(); } var sendTask = topicClient.SendAsync(message); await sendTask; var success = HandleException(sendTask); if (!success) { Thread.Sleep(10000 * (tries < 60 ? tries++ : tries)); } else { _messages.Remove(message); } } } catch (Exception) { throw; } }
static async Task Write(ISenderClient client, string message) { Type clientType = client.GetType(); if (client.GetType() == typeof(SubscriptionClient)) { Console.WriteLine("Cannot write message to subscription only topic or queue, please remove subscription Id"); return; } if (string.IsNullOrEmpty(message)) { Console.WriteLine("Message required to write to service bus"); } try { await client.SendAsync(new Message(Encoding.UTF8.GetBytes(message))); } catch (Exception e) { Console.WriteLine($"Ooops, sending messsage failed: {e}"); return; } if (Verbose) { Console.WriteLine($"Sent message: {message}"); } }
public static async Task PublishAsync <TMessage>(this ISenderClient client, TMessage payload, string sessionId = null, string deduplicationIdentifier = null, string correlationId = null, IDictionary <string, object> userProperties = null) { var serialized = payload.Serialized(); var message = new Message(serialized) { SessionId = sessionId, CorrelationId = correlationId, UserProperties = { ["MessageType"] = payload.GetType().FullName, ["Culture"] = CultureInfo.CurrentCulture.Name } }; if (userProperties != null) { foreach (var userPropertiesKey in userProperties.Keys) { message.UserProperties[userPropertiesKey] = userProperties[userPropertiesKey]; } } if (deduplicationIdentifier != null) { message.MessageId = deduplicationIdentifier; } await client.SendAsync(message); }
private async Task SendMessage(Order order, ISenderClient topicClient) { var message = new Message(order.Serialize()); await topicClient.SendAsync(message); Console.WriteLine($"Order placed. {order.ProductName}:{order.Amount} "); }
public async Task SendAsync(ISenderClient senderClient, T message) { var serialisedMessage = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await senderClient.SendAsync(new Message(serialisedMessage)); _logger.LogInformation($"Message sent on : {senderClient.Path}, message: {serialisedMessage}"); }
private static async Task SendMessage <T>(T messageToSend, ISenderClient sender) where T : IBaseMessage { var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageToSend))) { Label = messageToSend.Label }; await sender.SendAsync(message); }
private static async Task Broadcast <T>(ISenderClient client, T instance) { var body = JsonConvert.SerializeObject(instance); var message = new Message(Encoding.UTF8.GetBytes(body)); await client.SendAsync(message); await client.CloseAsync(); }
public VerifyEmailModel( UserManager <User> userManager, ISenderClient senderClient, ILogger <ExternalLoginModel> logger) { _userManager = userManager; _senderClient = senderClient; _logger = logger; }
internal BaseCommunicationSender( ICommunicationConfiguration configuration, IMessageSerializer serializer, ISenderClient senderClient) { this.Configuration = configuration; this.serializer = serializer; this.Sender = senderClient; }
public MessagePublisher( IConfiguration configuration, ILogger <MessagePublisher <TMessage> > logger) : base(configuration) { _logger = logger; _senderClient = new QueueClient( _configuration.GetConnectionString("ServiceBus"), !String.IsNullOrWhiteSpace(QueueName) ? QueueName : typeof(TMessage).Name.ToLowerInvariant()); }
public async Task Disconnect() { await _senderClient.CloseAsync(); IsConnected = false; _senderClient = null; _consoleLoggerService.Log(value: _translationsService.GetString("ServiceBusDisconnected"), logType: ConsoleLogTypes.ServiceBus); }
public RequestReplySender(ISenderClient sender, IReceiverClient receiver) { _sender = sender; _receiver = receiver; _receiver.RegisterMessageHandler(OnMessageReceived, new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false }); }
public void Connect(string connectionString, string queuePath, string topicPath) { if (!string.IsNullOrEmpty(queuePath) || topicPath == null) { _client = new QueueClient(connectionString, queuePath); } else { _client = new TopicClient(connectionString, topicPath); } }
/// <summary> /// Publishes <paramref name="message"/> to registered subscribers using <paramref name="client"/>. /// </summary> /// <returns></returns> private async Task ProcessMessageForClient(ISenderClient client, SampleMessage message) { //Close the PrimaryClient object to see an exception that causes fail-over (PrimaryClient.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult(); in watch) message.Sender = client == PrimaryClient ? "PrimaryClient" : "SecondaryClient"; string json = JsonConvert.SerializeObject(message); var brokeredMessage = new Message(Encoding.UTF8.GetBytes(json)); brokeredMessage.UserProperties.Add("Type", message.GetType().Name); await client.SendAsync(brokeredMessage).ConfigureAwait(false); }
public ExternalLoginModel( SignInManager <User> signInManager, UserManager <User> userManager, ISenderClient senderClient, ILogger <ExternalLoginModel> logger) { _signInManager = signInManager; _userManager = userManager; _senderClient = senderClient; _logger = logger; }
private async Task SendAsync(ISenderClient client, IList <Message> messages, int retryCount) { try { await client.SendAsync(messages).ConfigureAwait(false); } catch (ServiceBusCommunicationException) when(retryCount > 0) { await Task.Delay(GetRetryDelay(retryCount)).ConfigureAwait(false); await SendAsync(client, messages, retryCount - 1).ConfigureAwait(false); } }
private async Task PublishEventAsync(ISenderClient client, Message message, int retryCount) { try { await client.SendAsync(message).ConfigureAwait(false); } catch (ServiceBusCommunicationException) when(retryCount > 0) { await Task.Delay(GetRetryDelay(retryCount)).ConfigureAwait(false); await PublishEventAsync(client, message, retryCount - 1).ConfigureAwait(false); } }
public void Start(ISenderCallback callback) { _callback = callback; _serialization = new ActionBlock <Envelope>(e => { try { e.EnsureData(); _sending.Post(e); } catch (Exception exception) { _logger.LogException(exception, e.Id, "Serialization Failure!"); } }); // The variance here should be in constructing the sending & buffer blocks if (_endpoint.Uri.TopicName.IsEmpty()) { _sender = _endpoint.TokenProvider != null ? new MessageSender(_endpoint.ConnectionString, _endpoint.Uri.QueueName, _endpoint.TokenProvider, _endpoint.TransportType, _endpoint.RetryPolicy) : new MessageSender(_endpoint.ConnectionString, _endpoint.Uri.QueueName, _endpoint.RetryPolicy); _sending = new ActionBlock <Envelope>(sendBySession, new ExecutionDataflowBlockOptions { CancellationToken = _cancellation }); } else if (_endpoint.Uri.IsMessageSpecificTopic()) { _sending = new ActionBlock <Envelope>(sendByMessageTopicAndSession, new ExecutionDataflowBlockOptions { CancellationToken = _cancellation }); } else { _sender = _endpoint.TokenProvider != null ? new TopicClient(_endpoint.ConnectionString, _endpoint.Uri.TopicName, _endpoint.TokenProvider, _endpoint.TransportType, _endpoint.RetryPolicy) : new TopicClient(_endpoint.ConnectionString, _endpoint.Uri.TopicName, _endpoint.RetryPolicy); _sending = new ActionBlock <Envelope>(sendBySession, new ExecutionDataflowBlockOptions { CancellationToken = _cancellation }); } }
public ServiceBusTopicMessageSender(string connectionString, string topicName) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } if (string.IsNullOrEmpty(topicName)) { throw new ArgumentNullException(nameof(topicName)); } _senderClient = new TopicClient(connectionString, topicName); }
private static Task PushMessage(ISenderClient client, DeadLetterQueueMessage model) { var eventName = model.EventName; var body = Encoding.UTF8.GetBytes(model.JsonResponse); var message = new Message { MessageId = model.Id, Body = body, Label = eventName }; return(client.SendAsync(message)); }
private async Task InitializeInternalAsync(AzureServiceBusConfiguration configuration, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _config = configuration; var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_config.KeyName, _config.SharedAccessSignature, TimeSpan.FromDays(1)); _managementClient = new ManagementClient(_config.Endpoint, tokenProvider); if (!await _managementClient.QueueExistsAsync(_config.QueueName, cancellationToken)) { await _managementClient.CreateQueueAsync(_config.QueueName, cancellationToken); } if (!await _managementClient.TopicExistsAsync(_config.TopicName, cancellationToken)) { await _managementClient.CreateTopicAsync(_config.TopicName, cancellationToken); } if (!await _managementClient.SubscriptionExistsAsync(_config.TopicName, _config.TopicName, cancellationToken)) { await _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_config.TopicName, _config.TopicName) { ForwardTo = _config.QueueName }, cancellationToken); } var queueConnection = new ServiceBusConnection(_config.Endpoint, TransportType.Amqp, RetryPolicy.Default) { TokenProvider = tokenProvider }; _messageReceiver = AzureServiceBusReceiver.Create(_config, ReceiveMessageAsync, HandleErrorAsync); var topicConnection = new ServiceBusConnection(_config.Endpoint, TransportType.Amqp, RetryPolicy.Default) { TokenProvider = tokenProvider }; _messageSender = new TopicClient(topicConnection, _config.TopicName, RetryPolicy.Default); _messageSendTimer = new System.Timers.Timer(_config.PublishInterval); _messageSendTimer.Elapsed += SendMessageAsync; _messageSendTimer.Start(); }