Azure Functions: Configuration file for referenced assembly - azure

We have a referenced project in azure function app project. The referenced assembly is a data service project which is referred to by web api project too.
When referenced in web-api project the data service project automatically refers to web.config file for connection strings and app settings. While in azure functions app the data service project is not able to locate the connection strings stored in local.settings.json file.
How to address this issue locally?
How to address the issue in production?
NOTE: Would like to have DRY approach here.

As Jan V said, you could add a data connection string in json file. Besides, you could set a break point to see whether you get the 'str' value (Debug).
var str = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
Code in local.settings.jons file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage":
"your storage account connection string",
"AzureWebJobsDashboard":
"your storage account connection string"
},
"ConnectionStrings": {
"ConnectionStringName": "Data Source=tcp:database server name,1433;Initial Catalog=database name;Integrated Security=False;User Id=user name;Password= your Password;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" // Refer to Azure portal>SQL database> connection string
}
}
For more details about how to use Azure Functions to connect to an Azure SQL Database ,you could read this article.

Related

Why I am not seeing all properties available in local.settings.json file after deploying Azure function

I created an Azure function using Visual Studio. Local.setting.json file had following properties:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnString": "Endpoint=sb://sb-new-two.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=9FygKPHH2eJVp3GmAiUxtT7sGnddsaddadNIrciM0=",
"Test": "sb-new-two.servicebus.windows.net"
}
}
This is how my function looks:
[FunctionName("Function1")]
public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")] string mySbMsg)
{
_logger.LogInformation("Processing message");
_logger.LogInformation($"Message : {mySbMsg}");
Console.WriteLine(mySbMsg);
}
After deploying the azure function, I do not see the test property. I am not using it in my code. But wondering why is this property missing?
Check in your .gitignore file if it includes the local.settings.json. Better yet add the value of your Test config manually in the Configuration section of your Azure function. Go to your function app in Azure, under Settings > Configuration > New Application setting, then add your Test config.
One of the workarounds to publish the app settings from local.settings.json to the Azure Portal Function App Configuration is:
Before publishing the function project to the Azure Portal, below is the configuration of my Function App:
Azure Functions Core Tools cmdlet:
func azure functionapp publish KrishSbFunApp01 --publish-local-settings -i
Before running this cmdlet, you have to change the value of AzureWebJobsStorage to the Azure Storage account connection string.
Also, you can overwrite the app settings by using the parameter --overwrite-settings -y, available in MS Doc Source.

Azure function nested configuration

In my local.settings I have nested settings like this
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"Email:Email": "test",
"Email:Password": "*******",
},
}
I am reading the values like this
config.GetValue<string>("Email:Email")
But when I am adding azure settings in azure function app (after deploying) I cannot add : into the name. Any suggestions for it?
One of the workaround you can follow,
When we are creating azure function in local and deploy to azure our localsettings.json file not upload .We need to update them manually by adding it on portal.
In localsettings.json file you have used : which is accepted by local environment. But When deploying we need to use __ instead.
Followed by this MICROSOFT DOCUMENTATION:-
The app setting name like ApplicationInsights:InstrumentationKey
needs to be configured in App Service as
ApplicationInsights__InstrumentationKey for the key name. In other
words, any : should be replaced by __ (double underscore).
Likewise you can set something like below e.g;
"Email__Email": "test",
"Email__Password": "*******",
For more information please refer this SO THREAD| azure application settings - how to add nested item & Nested object from local.settings.json in Azure function v3 settings .

how to override local connection string with azure connection string

I am using appsettings.json in .Net core project for connection string. My connection string is :
"ConnectionStrings": {
"OT_DB_Connection": "Data Source=108.***.**.**;Initial Catalog=O*******s;User ID=O*******s;Password=O*********$"
},
In startup.cs i am accessing connection string with key like this
options.UseSqlServer(Configuration.GetConnectionString("OT_DB_Connection"));
I deployed this code on azure and i have sql database on azure.
After deployment how my website will use the connection string of azure ?
How to override the local connection string with azure connection string at run time.
You should read the following article:
Multiple Environment Configuration Files in ASP.NET Core
You can have multiple appSettings e.g. 1 for you local environment and 1 for Azure etc. When you publish your app to Azure, you can add an application setting called ASPNETCORE_ENVIRONMENT and add a value that maps to your environment for your app to pick up the correct configuration. If you have an appSettings.Azure.json file you can set ASPNETCORE_ENVIRONMENT to Azure and it will use that configuration file.
If you do not want to take this approach, you can also override the connection string directly in Azure as show in the picture below. This is accessible under your app service -> Application Settings -> Connection Strings. You will want to override OT_DB_Connection.

Azure WebApp Containers and AppSettings/Environment Variables

I've created an AzureWebApp running a docker image. The app starts, but it does not appear to be getting a connection string. I've defined the connection string as an AppSetting but I am not seeing that setting passed as an environment variable.
Should I expect to see my AppSetting on the container output? Something like
docker run -e CONNSTR=FOO
The docs imply that it should just be passed automatically, but I feel like I'm missing something.
Thanks
Joe
Turns out it was working all along. I had a legit issue with authenticating against the db. I needed some logging in the service to verify that it was getting the right connection string.
It appears that the app settings are passed to the container implicitly without showing up in the logs as an -e param.
I run into a similar issues when deploying an .NET Core 2 Azure Function, which was reading settings and connection strings using System.Configuration.ConfigurationManager. The root cause in my case was that ASP.NET Core introduced a new configuration API.
Find more details at https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.0&tabs=basicconfiguration.
Assuming you're deploying an ASP.NET Core application deployed into Web Apps for Containers, you may be running into a similar issue. Please try to the following:
a) Initialize the configuration as follows:
using Microsoft.Extensions.Configuration;
...
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json")
.AddEnvironmentVariables()
.Build();
b) Read connection strings as follows:
configuration.GetConnectionString("StorageAccountConnectionString");
c) Read settings as follows:
configuration["ContainerName"];
Here is a sample configuration file for my Azure Function:
{
"IsEncrypted": true,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"ContainerName": "container"
},
"Host": {
"LocalHttpPort": 7071
},
"ConnectionStrings": {
"StorageAccountConnectionString": "UseDevelopmentStorage=true"
}
}

How to Access Emulated Azure storage on local PC

I am beginning development with Azure functions. Ive been able to connect to my actual azure Storage account Queue for testing how to program with Azure functions. Now my next step is to use the Microsoft Azure Storage Explorer to use the Local storage account so I do not have to be connected to azure. I saw how to do it in this article: https://learn.microsoft.com/en-us/azure/storage/storage-configure-connection-string#create-a-connection-string-to-the-storage-emulator
in the appsettings.json I changed my values to this exactly:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
"AzureWebJobsDashboard": "",
"StorageConnectionString": "UseDevelopmentStorage=true"
}
}
When i start up the Azure Fuctions CLI using Visual Studio i get this error message:
ScriptHost initialization failed Microsoft.WindowsAzure.Storage: The
remote server returned an error: (403) Forbidden.
Has anyone encountered this?
Please change the following line of code:
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
to either:
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
or:
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;
AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;
BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;
TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;
QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;"
That should take care of 403 error.
Basically storage emulator has different endpoints than the cloud storage account. For example, the default blob endpoint for a cloud storage account is http://[youraccount].blob.core.windows.net while the blob endpoint for storage emulator is http://127.0.0.1:10000. When you just specify the storage account name and key for the storage emulator in your connection string, storage client library treats it like a cloud storage account and tries to connect to http://devstoreaccount1.blob.core.windows.net using the account key you provided. Since the key for devstoreaccount1 in the cloud is not the one you provided, you are getting 403 error.

Resources