Given the following topic trigger:
[FunctionName("eventhandler")]
public static Task Run([ServiceBusTrigger("domain.event", "domain.subscription", Connection = "QueueConnection")]
BrokeredMessage mySbMsg,
IBinder binder,
TraceWriter traceWriter,
CancellationToken cancellationToken)
How can i retrieve the full endpoint of the Service Bus Trigger without needing to add additional custom settings in application config? Is there any environment variables i can retrieve within the run function?
To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable.
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#environment-variables
Related
Standard Azure Storage Queue trigger line …
public async void ProcessQueueMessage([QueueTrigger("queue-abc")] string message, ILogger logger)
Question:
I would like to set the “QueueTrigger”-value (queue-abc) during the initial load of a Azure WebJob, based on a value in appsetting.json.
I am writing in .Net Core 3.1
Is this possible?
Added after Answer: https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#custom-binding-expressions
If you want to use a setting from appsettings.json (or from the Function App's Application Settings for that matter), you can use the name of the setting surrounded by percent signs in the trigger attribute.
For example:
appsettings.json
{
"Values": {
"QUEUENAME": "SomeQueueName"
}
}
Azure Function
[FunctionName("QueueTrigger")]
public static void Run(
[QueueTrigger("%QUEUENAME%")]string myQueueItem,
ILogger log)
{
log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}
I have an Azure Function which is using a ServiceBus trigger with topics. I recently added correlationId to the list of bindable inputs however the correlationId is not binding. I have confirmed that the correlationId is set corectly on the inbound message. All tooling/NuGets are on the latest bits (as of today).
The function also happens to be a durable function as is obvious in the following code snippet
[FunctionName("TopicHandler")]
public static void Run([ServiceBusTrigger("%TopicName%", "SubscriptionName", Connection = "ServiceBusConnection")]string messageBody,
string label,
string messageId,
string correlationId,
IDictionary<string, object> userProperties,
[OrchestrationClient] DurableOrchestrationClient starter,
ExecutionContext executionContext,
ILogger logger)
{
....
Documetnation seems to imply this should work:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus#trigger---message-metadata
However this is not completely explict as to whether it only works with queues or not.
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messages-payloads#message-routing-and-correlation
Any guidance would be appreciated before I create a custom property.
I just created a simple azure function using service bus trigger. I am using the default example provided. I can read the messageid in the code below
public static void Run(string mySbMsg, TraceWriter log)
{
log.Info($"C# ServiceBus topic trigger function processed message:
{mySbMsg}");
}
I`m struggling to find codes showing how to read the json message that was posted.
Thanks for you help
You can use the BrokeredMessage parameter to get the message body in Azure Function Service Bus Trigger.
This will return the message with the BrokeredMessage.GetBody() method.
Get more information here.
In Azure portal, add "project.json" in View Files. This the library which contains BrokeredMessage object.
The project.json should look like
{
"frameworks":
{
"net46":
{
"dependencies":
{
"WindowsAzure.ServiceBus": "4.1.2"
}
}
}
}
When you save, you can see the package gets restored.
Inside the Run method, add BrokeredMessage as parameter. The method should look like
public static void Run(BrokeredMessage message, TraceWriter log)
{
string messageBody = message.Properties["Message"].ToString();
string messageId = message.Properties["Id"].ToString();
log.Info($"message - " + messageBody + " Id " + messageId);
}
Don't forget to add Using Microsoft.ServiceBus.Messaging in "Run.csx" and change the name property to message in "Function.json"
I'm trying to create an Azure function that connects to a container that is not hard-coded, much like my connection.
public static void Run(
[BlobTrigger("Container-Name/ftp/{name}", Connection = "AzureWebJobsStorage")]Stream blobStream,
string name,
IDictionary<string, string> metaData,
TraceWriter log)
The connection property is able to get the connection value directly from local.settings.json. It does not appear that capability is an option for "container-name", or if so, not with the appended /ftp/{name}.
So, is there a way to set the container name based on settings for an Azure Function Blob Trigger?
You can define your function like this:
public static void Run(
[BlobTrigger("%mycontainername%/ftp/{name}", Connection = "AzureWebJobsStorage")]
Stream blobStream,
string name,
IDictionary<string, string> metaData,
TraceWriter log)
and then define an application setting called mycontainername to contain the actual container name.
I have the following WebJob Function...
public class Functions
{
[NoAutomaticTrigger]
public static void Emailer(IAppSettings appSettings, TextWriter log, CancellationToken cancellationToken)
{
// Start the emailer, it will stop on dispose
using (IEmailerEndpoint emailService = new EmailerEndpoint(appSettings))
{
// Check for a cancellation request every 3 seconds
while (!cancellationToken.IsCancellationRequested)
{
Thread.Sleep(3000);
}
log.WriteLine("Emailer: Canceled at " + DateTime.UtcNow);
}
}
}
I have been looking at how this gets instantiated which I can do with the simple call...
host.Call(typeof(Functions).GetMethod("MyMethod"), new { appSettings = settings })
However it's got me wondering how the TextWriter and CancellationToken are included in the instantiation. I have spotted that JobHostingConfiguration has methods for AddService and I have tried to inject my appSettings using this but it has failed with the error 'Exception binding parameter'.
So how does CancellationToken get included in the instantiation and what is JobHostingConfiguration AddService used for?
how does CancellationToken get included in the instantiation
You could use the WebJobsShutdownWatcher class because it has a Register function that is called when the cancellation token is canceled, in other words when the webjob is stopping.
static void Main()
{
var cancellationToken = new WebJobsShutdownWatcher().Token;
cancellationToken.Register(() =>
{
Console.Out.WriteLine("Do whatever you want before the webjob is stopped...");
});
var host = new JobHost();
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
what is JobHostingConfiguration AddService used for?
Add Services: Override default services via calls to AddService<>. Common services to override are the ITypeLocator and IJobActivator.
Here is a custom IJobActivator allows you to use DI, you could refer to it to support instance methods.