I have got a local.settings.json like this
{
"IsEncrypted": false,
"ServiceBusSettings": {
"TransformedJson": {
"ConnectionString": "connectionstring2"
},
"ServiceLogs": {
"ConnectionString": "connectionstring3"
}
},
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
First of all is it acceptable to have nested JSON in Azure Functions Local.settings.json? I have that confusion because in Azure we dont have a json file instead we have environment variables as key val pair. (Please correct I am wrong)
If above json is acceptable, how can I get a specific key from the nested settings
For getting IsEncryped I can just use
bool IsEncryped= configuration.GetValue<bool>("IsEncrypted")
Also in function parameter if I need to use value I can Just use
%IsEncrypted%
In my case if I need to get the connection string under TransformedJson attribute and get its values and also I'd like to use that in my parameter with percentage notation.
Please suggest how can I accomplish that?
Related
I am unable to read the few of the keys from local.settings.json file. Below is the file content.
{
"IsEncrypted": false,
"Values": {
"KeyVaultUrl": "https://mykeyvault.azure.net/",
"SecretKey": "myconnectionstring",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
I used the below code to read these values
var keyVaultUrl = Environment.GetEnvironmentVariable("KeyVaultUrl"); // returns null
var secretKey = Environment.GetEnvironmentVariable("SecretKey"); // returns null
var sample = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); // returns "UseDevelopmentStorage=true"
I am not sure why it returns null for the key I have added. I have set Copy Always in Copy to Output Directory and Build Action to None.
Please assist.
Values you are trying to read, are not written in environment variables. To use config files, use IConfiguration. It can contain environment variables, multiple config files and much more.
It depends on type of your application, if you are using simple console application without hosts and builders, use this, but if you are using some kind of framework use this approach.
An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system!
Your data in appsettings is just key-value pairs of configuration settings for your application (from it's name - appsettings).
To access data in your appsettings you need to inject IConfiguration to your service (or controller or whatever)
private readonly IConfiguration _configuration;
public ServiceConstructor(public IConfiguration)
=> _configuration = configuration;
and then you can read values from there like this:
_configuration["IsEncrypted"]
and
_configuration["Values:KeyVaultUrl"]
I use IdentityServer in my Angular app based on .NET Core and I am trying to set some of the parameters like client_id, redirect_uri, authority in appSettings.json file.
"IdentityServer": {
"Key": {
"Type": "Development"
},
"Authentication": {
"Authority": "localhost:8081",
"ClientId": "localhost:8081",
"AppIdUri": "localhost:8081"
}
}
So, how can I do this?
I need to set these parameters via appSettings.json and retrieve them when using the following url: https://localhost:8081/_configuration/DemoProject.Web
You can call your settings in your code like this:
string ClientId = Configuration["IdentityServer:Authentication:ClientId"];
I hope this helps. If it is not what you ment let me know.
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!
In my Azure Function I am using a Library which establishes a connection to an SQL server via the ConnectionString from the ConfigurationManager like this:
var cs = System.Configuration.ConfigurationManager.ConnectionStrings["DbConString"].ConnectionString;
DbConnection connection = new SqlConnection(cs);
Now when i set the connection string DbConString in the portal via the Application Settings everything is working fine. But for local development I use the azure-functions-cli and unfortunately I have no idea where i should place the connection string to have it loaded correctly via the ConfigurationManager.
I've tried to place it in the appsettings.json file but without success.
Edit:
My appsettings.json currently looks like this:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"AzureWebJobsDashboard": "",
"MyServiceBusReader": "Endpoint=sb://xxxx=",
"DbConStr1": "data source=(localdb)\\MSSQLLocalDB;initial catalog=MyDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework",
"ConnectionStrings": {
"DbConStr2": "data source=(localdb)\\MS..."
}
}
}
But I am not able to access "DbConStr1" via the ConfigurationManager.
Adding "DbConStr2" within "ConnectionStrings" like described here leads to a compilation error. Maybe because I am not using .NET Core?
Edit2:
I messed up the nesting of "ConnectionStrings". It has to be on the same nesting level as "Values":
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"AzureWebJobsDashboard": "",
"MyServiceBusReader": "Endpoint=sb://xxxx="
},
"ConnectionStrings": {
"DbConStr": "data source=(localdb)\\MS..."
}
}
Add file local.setting.json
{
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"tenantId": "You tenantId",
"resource": "https://management.azure.com/",
"ClientSecret": "You ClientSecret, Key from App Registry",
"ClientId": "You ClientId, Application ID from App registry",
"subscriptionId": "You subscriptionId",
"resourceGroupName": "Your resourceGroupName",
"serverName": " Your SQL Server",
"databaseNameDW": "Your Database",
"apiversion": "2017-10-01-preview"
}
}
In C# Code use:
private readonly static string tenantId = ConfigurationManager.AppSettings["tenantId"];
// C# Environment Variables example for Azure Functions v1 or v2 runtime
// This works all the way up to but not including .NET Core 2.0
var clientId = Environment.GetEnvironmentVariable("ClientId");
var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
var aadDomain = Environment.GetEnvironmentVariable("AADDomain");
Please do remember the settings you do in local.settings.json will not be reflected in azure. Please add your values in app setting from Azure portal follow the link-
https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings
I had this same issue and am using .net standard (as opposed to core). I added my settings to the Application Settings section of my Azure function (in Azure Portal):-
I then downloaded a zip of the function:-
Included in this download is a copy of local.settings.json that includes my app settings in the correct json format. I then access them via ConfigurationManager.Appsettings["mysetting"]
The problem was, that a connection string known from e.g. a Web.config file consists of two parts:
The connection string itself and
the provider name.
But since the configuration file uses the JSON format it was not possible to specify both parameters.
At the time when the question was asked, it was not possible to set the provider name in the appsetings.json (now renamed to local.settings.json). But the Azure-Functions-team change this and set a default value for providerName to System.Data.SqlClient, which solved the problem.
The providerName defaults to System.Data.SqlClient. You don't have to set it manually. Just add your connection string X and read it via ConfigurationManager.ConnectionStrings["X"].
I've found a method which feels hacky, but works: if you do evaluate Environment.GetEnvironmentVariables() you can spot that all Connection Strings from your local.settings.json are available as Environment Variables with a "ConnectionStrings:" prefix if run locally, or one from several "xxxCONNSTR_" if running on Azure, so you can define this helper function:
private static Array ConnectionStringKeyPrefixes = new[] { "ConnectionStrings:", "SQLCONNSTR_", "SQLAZURECONNSTR_", "MYSQLCONNSTR_", "POSTGRESQLCONNSTR_", "CUSTOMCONNSTR_" };
public static string GetConnectionStringFromSettings(string connectionStringName)
{
string connectionString = null;
foreach(string prefix in ConnectionStringKeyPrefixes) {
connectionString = Environment.GetEnvironmentVariable($"{prefix}{connectionStringName}");
if (!string.IsNullOrWhiteSpace(connectionString))
{
break;
}
}
return connectionString;
}
You should be able to manage your configuration settings with an appsettings.json file in your project structure. You can take a look here for an example of the folder structure for Azure Functions.
Additionally, this link will have some details about how to manage configuration settings with .NET Core.
I'm trying to add some custom binding using my app settings for my Azure Function. I need to receive only string a string from my settings.
I would like to get simpleValue from my settings.
{
"bindings": [
{
"name": "someValue",
"type": "stringSetting",
"connection": "simpleValue",
"direction": "in"
}
],
"disabled": false
}
and the get it in Run method:
static void GetOrders(TraceWriter log, string someValue)
{
log.Info(someValue);
}
Is it even possible. Maybe there is other way to do it?
I already found the solution. Just add:
using System.Configuration;
and add this line to code with the key ("simpleValue") value:
ConfigurationManager.AppSettings["simpleValue"]
App Settings configurations can be referred in binding json as %MY_CUSTOM_CONFIG% - enclosed within percent symbols.
Note that the connection property of triggers and bindings is a
special case and automatically resolves values as app settings,
without percent signs.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings