Setup configuration and run azure queue trigger function locally - c#

I am trying to run an azure queue trigger function locally. I installed Azure Storage Emulator and ran the command "AzureStorageEmulator.exe init" to create "AzureStorageEmulatorDb59" database on the "(localdb)\MSSQLLocalDB" server.
In my azure functions project which has the queue trigger function, I have a local.settings.json file. What settings should be added in that file and what exactly should be the connection string and where should I add it? My queue trigger function is mentioned below. What should be added in place of "my-queue" mentioned after "QueueTrigger" attribute? Please help me with this
[FunctionName("TestQTFunction")]
public static void Run([QueueTrigger("my-queue", Connection = "AzureQueueConnectionString")]string myQueueItem, ILogger log)
{
// Do something
}

Update:
In local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
In my code:
[FunctionName("Function1")]
public static void Run([QueueTrigger("myqueue", Connection = "AzureWebJobsStorage")]string myQueueItem, ILogger log)
{
log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}
"my-queue" is the name of the queue the one you want to trigger, when a message is put into the queue. So change it to the queue name which you want to trigger.
The connection string in local.settings.json should be in this format:
"AzureWebJobsStorage":"DefaultEndpointsProtocol=https;AccountName=[name];AccountKey=[key]"
also make sure right click the local.settings.json file -> property -> set "copy to output directry" to "copy if newer".
then in the Run method, change connection="AzureQueueConnectionString" to Connection = "AzureWebJobsStorage".

Related

How to read config values either using .ENV file or user secrets in Azure Functions

I created an Azure function with .Net Core 3.1, that is triggered when a new messages to the Service Bus Queue is added. This function works well by hardcoding the connection string directly to the local.settings.json file.
Now, I want to go one step further I avoid hardcoding this value by putting it either in an .ENV file or user secrets. I tried those two but is not working so far.
The local.host.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"MyServiceBusConnString": "${MY_CONNECTIONSTRING}"
}
}
This is the Startup.cs I created
using System;
using System.Reflection;
using DemoFunction;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
// register the assembly
[assembly: FunctionsStartup(typeof(Startup))]
namespace DemoFunction
{
// inherit
public class Startup : FunctionsStartup
{
private IConfiguration configuration;
// override
public override void Configure(IFunctionsHostBuilder builder)
{
// In other examples the registration of services goes here
}
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
// local dev no Key Vault
builder.ConfigurationBuilder
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("local.settings.json", true)
.AddUserSecrets(Assembly.GetExecutingAssembly(), true)
.AddEnvironmentVariables()
.Build();
}
}
}
This Startup code is the last one I tried but I have seem different approaches how to do it. Already tried them without any luck. Here are the links:
AZURE FUNCTIONS CONFIGURATION AND SECRETS MANAGEMENT
Using JSON and User Secrets configuration with Azure Functions
And this part of my function:
public class MyFunction
{
private ILogger _logger;
[FunctionName("MyFunction")]
public string Run([ServiceBusTrigger("myQueue", Connection = "MyServiceBusConnString")] string queueItem, ILogger log)
{
_logger = log;
_logger.LogInformation($"Starting Azure Function...");
// custom code...
}
}
Look at the Connection property of ServiceBusTrigger. It's referencing the key from the local.host.json which in turn is trying to read the value as mentioned before from .ENV file or user secrets.
When I run the Azure Function, this is the error I am getting:
At this point, I'm kind of lost on how to achieve this. So, any comment on how to fix this or any guidance is very appreciated.
For local development you can leave as it is, however, when publishing to Azure you should use Azure Key Vault to proper store the secrets of your application.
https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references#reference-syntax

how to change value in the local.settings.json file in function app

I'm using visual studio 2019 and I created the function app I need to change the value in the local.settings.json file when I run the function app that I want to change the schedule data Cron expression string dynamically
JSON file
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"schedule": "*/10 * * * * *"
}
}
function app:
[FunctionName("Function3")]
public static async System.Threading.Tasks.Task RunAsync([TimerTrigger("%schedule%")]TimerInfo myTimer, ILogger log)
{
}
There is no solution to set the schedule of Azure Function dynamically by code.
But you could do it using Durable Function, or change the value using kudu API.
Please check the answer of this question: How to create dynamically schedule Azure function using c# in visual studio?

Azure Function Trigger Name/Connections from App Configuration

Is there now a way to set the Trigger Properties(Name/Connection) using the value from Azure App Configuration?.
I added a startup class that reads the data from Azure App Configuration but it seems the trigger set its properties earlier than that, therefore not able to bind the data that came from the app configuration.
I also found this thread about it but im not sure if there is a new update?:
https://github.com/MicrosoftDocs/azure-docs/issues/63419
https://github.com/Azure/AppConfiguration/issues/203
You can do this. The following code gets the name of the queue to monitor from an app setting, and it gets the queue message creation time in the insertionTime parameter:
public static class BindingExpressionsExample
{
[FunctionName("LogQueueMessage")]
public static void Run(
[QueueTrigger("%queueappsetting%")] string myQueueItem,
DateTimeOffset insertionTime,
ILogger log)
{
log.LogInformation($"Message content: {myQueueItem}");
log.LogInformation($"Created at: {insertionTime}");
}
}
Similarly, you can use this approach for other triggers.

Is it possible to Pass Azure Function ServiceBusTrigger connection at runtime

My Code Look like this :
public class Startup : IWebJobsStartup
{
public async void Configure(IWebJobsBuilder builder)
{
Get Connection string Via HTTP Service.
ServiceBusConnectionString = jArray["connectionString"].ToString();
}
}
And I want to Pass Connection Like this
[FunctionName("FunctionTopicMessageLogger")]
public void Run([ServiceBusTrigger("topic", "FunctionTopicMessageLogger",Connection = **ServiceBusConnectionString** )]Message mySbMsg)
{
}
This is my Local.setting.json file for first time
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"Connectinstring": " "
}
}
Problem is that connection only take Const Parameter (So it's not allow to change) So i am trying to write in a local.setting.json and trying to read it from there, I am getting error first time when i am running , and from second time connection is there so it's working fine.
Is i am doing something wrong Please suggest.
There are two important parts in the solution for your problem.
During creation of Azure Function with Service Bus trigger you have to specify the name of the connection string parameter that will be used to retrieve connection string value. In this case if you type "ServiceBusConnectionString" you have to add such configuration parameter in the local.settings.json file in the "ConnectionStrings" section:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
},
"ConnectionStrings": {
"ServiceBusConnectionString": "xxx"
}
}
After depoying your function to Azure, you should use "Configuration" section in the portal and you should avoid using "local.settings.json" file because it is only for local development:
I hope this will help.
If your intention is to use the key Connectionstring from the local.settings.json, you should be able to get the value from there automatically just by doing this:
public static void Run([ServiceBusTrigger("topic", "FunctionTopicMessageLogger", Connection = "connectionString")]string mySbMsg)
The value for Connection is the name of the Key from the local.settings.json file.
If you don't have a lot of different Service Bus, you can create one function for each different connectionString you have.
Each function needs to know the connectionString before starting, and start waiting for message in the service bus.
If you have to do that dynamically, you don't have to use an Azure function, you can use the Service Bus SDK:
Here you can see how to manage a client manually: https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
I hope this will help you!

Blob Trigger : Storage account is not configured

I am trying to make a blob trigger azure function in Visual Studio. I gave the connection string value in the connection string and the container name in path. But when I run the boilerplate code that is generated I get the error that the storage account is not configured and a warning that
Warning: Cannot find value named *connection-string-here* in local.settings.json that matches 'connection' property set on 'blobTrigger'. You can run 'func azure functionapp fetch-app-settings <functionAppName>' or specify a connection string in local.settings.json.
Do I have to configure in the local.setting.json aswell?
This is my function currently
public static class Function1
{
[FunctionName("Function1")]
public static void Run([BlobTrigger("*container-name*/{name}", Connection = "*connection-string*")]Stream myBlob, string name, ILogger log)
{
log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}
}
The value for Connection is the name of the app setting that contains the connection string. It is not the connection string itself.
If you specify 'MyStorage' as the value then you need to have the 'AzureWebJobsMyStorage' property set in local.setting.json for local development.

Categories