using Azure.Messaging.ServiceBus;
using Elsa.Common.Contracts;
using Elsa.Common.Services;
using Elsa.Extensions;
using Elsa.Workflows.Core.Attributes;
using Elsa.Workflows.Core.Models;
using JetBrains.Annotations;
namespace Elsa.AzureServiceBus.Activities;
///
///
///
[Activity("Elsa.AzureServiceBus.Send", "Azure Service Bus", "Send a message to a queue or topic")]
[PublicAPI]
public class SendMessage : CodeActivity
{
///
/// The contents of the message to send.
///
[Input(Description = "The contents of the message to send.")]
public Input MessageBody { get; set; } = default!;
///
/// The queue or topic to send the message to.
///
public Input QueueOrTopic { get; set; } = default!;
///
/// The content type of the message.
///
public Input? ContentType { get; set; }
///
/// The subject of the message.
///
public Input? Subject { get; set; }
///
/// The correlation ID of the message.
///
public Input? CorrelationId { get; set; }
///
/// The formatter to use when serializing the message body.
///
public Input FormatterType { get; set; } = default!;
///
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
{
var queueOrTopic = context.Get(QueueOrTopic);
var messageBody = context.Get(MessageBody);
var cancellationToken = context.CancellationToken;
var serializedMessageBody = await SerializeMessageBodyAsync(context, messageBody!, cancellationToken);
var message = new ServiceBusMessage(serializedMessageBody)
{
ContentType = context.Get(ContentType),
Subject = context.Get(Subject),
CorrelationId = context.Get(CorrelationId)
// TODO: Maybe expose additional members?
};
var client = context.GetRequiredService();
await using var sender = client.CreateSender(queueOrTopic);
await sender.SendMessageAsync(message, cancellationToken);
}
private async ValueTask SerializeMessageBodyAsync(ActivityExecutionContext context, object value, CancellationToken cancellationToken)
{
if (value is string s) return BinaryData.FromString(s);
var formatterType = FormatterType.TryGet(context) ?? typeof(JsonFormatter);
var formatter = context.GetServices().First(x => x.GetType() == formatterType);
var data = await formatter.ToStringAsync(value, cancellationToken);
return BinaryData.FromString(data);
}
}