Getting a Connection String from Azure App Config via Configuration.GetConnectionString() - azure

Is there a special way to define a Key Value setting for ConnectionStrings in Azure App Configuration?
I have tried using:
ConnectionStrings:DatabaseKeyName
ConnectionStrings\DatabaseKeyName
Using the standard builder.Configuration.GetConnectionString("DatabaseKeyName") always results in a null value. Using builder.Configuration["ConnectionStrings:DatabaseKeyName"] also results in null, however if I use a keyname that does not start with ConnectionStrings (e.g. Test:ConnectionStrings:DatabaseKeyName it works as an app setting via builder.Configuration["Test:ConnectionStrings:DatabaseKeyName"]
The Null value for ConnectionStrings:DatabaseKeyName indicates there is some special handling for ConnectionStrings in Azure App Config, but I don't know where I am going wrong. The Microsoft example pages don't seem to cover ConnectionStrings (except via KeyVault).
Basically I do not want to have to change this:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(Configuration.GetConnectionString("DatabaseKeyName"));
});
To this:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(builder.Configuration["DatabaseKeyName"]);
});
Standard app config connection string setting I need to simulate from Azure App Config:
{
"ConnectionStrings": {
"DatabaseKeyName": "Data Source=localhost;Initial Catalog=xxxx;Integrated Security=True"
},
In my secrets file it is in this format (which does not work with Azure App Config):
{
"ConnectionStrings:DatabaseKeyName": "Server=xxxx;Database=xxxx;User ID=xxxx;Password=xxxx"
}

To get the Connection String from Azure App Configuration, please check the below process.
Install the NuGet Package Microsoft.Azure.AppConfiguration.AspNetCore latest version to add the AddAzureAppConfiguration and read the key values.
To read Azure App Configuration locally, we need to set the secret manager to store the connection string.
dotnet user-secrets init
The above command enables the secret storage and sets the secret ID in .csproj of your application.
In Program.cs, add the below code
var myAppConn= builder.Configuration.GetConnectionString("AppConfig");
Output:
As mentioned in the MSDoc, For the Apps deployed in Azure App Service it is recommended to store Connection String in Configuration Section => Application Settings => Connection Strings of the deployed App.
Is there a special way to define a Key Value setting for ConnectionStrings in Azure App Configuration?
In Azure App Configuration => *YourAppConfiguration* => click on Configuration explorer Under Operations => click on Create => Key-value
In Program.cs, add the below code
var myconn = builder.Configuration.GetConnectionString("AppConfig");
builder.Host.ConfigureAppConfiguration(builder =>
{
builder.AddAzureAppConfiguration(myconn);
})
.ConfigureServices(services =>
{
services.AddControllersWithViews();
});
In any of the cshtml file, add the below code
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
<h1>#Configuration["MyConnection"]</h1>
Output for Key-Value from AppConfiguration:

Related

Get Azure Configuration value for Blazor

I am trying to pull appsetting.json settings (In Blazor Server app) when I run my code locally and have the settings be pulled from Azure's Configuration when it is running on Azure. But, my code will pull from appsettings.json even if it is live. I pull these values for my Startup.cs file, like this:
options.Authority = Configuration.GetValue<string>("AuthenticationServer:IDAuthority");
options.ClientId = Configuration.GetValue<string>("AuthenticationServer:IDClientID");
options.CallbackPath = Configuration.GetValue<string>("AuthenticationServer:IDRedirectURI");
In my appsetting.json file, I have the settings stored like this:
{
"AuthenticationServer": {
"IDAuthority": "Some Value",
"IDClientID": "Another Value",
"IDRedirectURI": "/Index/"
},
}
And in Azure App Service, under Settings->Configuration, in the Application Settings Tab, I have three key/value pairs:
"IDAuthority" - "New Value"
"IDClientID" - "Another New Value"
"IDRedirectURI" - "/Index/"
But when I do this, the values still get pulled from appsettings.json and not Azure. I've also tried:
"AuthenticationServer_IDAuthority" - "New Value"
"AuthenticationServer_IDClientID" - "Another New Value"
"AuthenticationServer_IDRedirectURI" - "/Index/"
And get the same results. So, how should I pull these values from Azure?
As an aside, getting the Azure db connection string like this, works fine:
services.AddDbContext<DBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("ConnString")));
I think you can only change the code before publish it to AZURE.
Firstly we need to know when we want to read the value stored in azure app configuration, we need to make your application connect to Azure app configuration and then we can get what we set, and we can get value with the key name. And the opreation should be the same as getting value from appsettings.json, here's my code:
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
var connectionString = "connection_string_of_app_configuration";
builder.Host.ConfigureAppConfiguration(builder =>
{
//Connect to your App Config Store using the connection string
builder.AddAzureAppConfiguration(connectionString);
});
var a = configuration["Logging:LogLevel:Default"];//get log setting in appsetting.json
var c = configuration["Logging:LogLevel:Default"];//also set the same key in azure
var b = configuration["TestApp:Settings:Message"];//get from app configuration
So I think you may comment the code connect to Azure app configuration when you want to read configuration in appsettings.json, and un-comment the code before you want to publish to azure.
Seems to be a naming convention issue. Because my values were nested in my appsettings.json file, I had to make sure the depth of the parameter was included in the Azure setting.
To get the value:
options.Authority = Configuration["AuthenticationServer:IDAuthority"];
and I then had to make sure the configuration setting, in Azure, was titled: "AuthenticationServer:IDAuthority"

Azure: Function host is not running

I have a Function App in azure and when I hit the URL of the function app it says "Function host is not running." I have checked the log also in the app insights or in the Azure portal's function app service, it shows the following error message in the function app.
Note: My pipeline's Build & Releases got succeeded, so I am not sure where to check and what is the solution for this. I tried with a new function app but still no luck.
My Startup.cs file to understand How I have referred the config values,
public override void Configure(IFunctionsHostBuilder builder)
{
//var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DBConnection");
var serviceProvider = builder.Services.BuildServiceProvider();
_configuration = serviceProvider.GetRequiredService<IConfiguration>();
var appSettingsSection = _configuration.GetSection("AppSettings");
builder.Services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
RuntimeConfig.appsettings = appSettings;
var ConnectionString = RuntimeConfig.appsettings.AppDBConnection;
///builder.Services.AddDbContext<ShardingDbContext>(options => options.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
//builder.Services.AddScoped<ITestService, TestService>();
}
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
FunctionsHostBuilderContext context = builder.GetContext();
builder.ConfigurationBuilder
.AddJsonFile(Path.Combine(context.ApplicationRootPath, "local.settings.json"), optional: true, reloadOnChange: false)
.AddJsonFile(Path.Combine(context.ApplicationRootPath, $"{context.EnvironmentName}.settings.json"), optional: true, reloadOnChange: false)
.AddEnvironmentVariables();
}
I am taking the config values as IConfiguration, it works for my local but don't know how to do the same in the server.
while deploying your Function app it neither upload local.settings.json to Azure or nor makes modification on Application Settings based on local.settings.json file.
The Key-value pair related to EIA present in local.settings.json, add the same key-value pair in Azure Function App Configuration > Application Settings in the Portal.
For that we have to manually update the App Settings in portal or if you are using Visual studio, we can update using VS publish panel.
Add Application Settings using Portal
Azure Portal -> Your Azure Function -> Configuration Panel -> Application Settings/Connection Strings (Add your custom configuration)
Add Application Settings using Visual Studio Publish panel
While publishing your azure function Add your Application settings.
In a hosting panel right corner click (...).
Add your app Settings in Manage Azure App Service Settings.
Add your settings like below

How do I allow ContinuousIntegration.exe to use a connection string in Azure Key Vault

I've got a Kentico Xperience (v13) instance in Azure and I want to run ContinuousIntegration.exe to populate my database up there with content from my CI xml files. The catch is that we're injecting the CMSConnectionString setting into the web app from Azure Key Vault (AKV) and the CI.exe isn't seeing it. Instead I get this error message:
CMS.DataEngine.ApplicationInitException: Cannot access the database specified by the 'CMSConnectionString' connection string. Please install the database externally and set a correct connection string.
Or maybe this error message:
Failed to execute the command.
Here's the relevant section from our web.config (that works for the website!):
<connectionStrings>
<!--Should be provided by Azure Key Vault-->
</connectionStrings>
How do I ensure that the executable gets access to the secrets in AKV?
It is possible to let ContinuousIntegration.exe know about a secure connection string with a small custom module that sets the connection string at startup. Here is the basic code of the module:
[assembly: AssemblyDiscoverable]
[assembly: RegisterModule(typeof(AzureConnectionStringModule))]
public class AzureConnectionStringModule : Module
{
public AzureConnectionStringModule()
: base(nameof(AzureConnectionStringModule))
{
}
protected override void OnPreInit()
{
base.OnPreInit();
var azureConnectionString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_CMSConnectionString");
if (string.IsNullOrWhiteSpace(azureConnectionString))
{
azureConnectionString = Environment.GetEnvironmentVariable("CMSConnectionString");
}
if (!string.IsNullOrWhiteSpace(azureConnectionString))
{
SettingsHelper.ConnectionStrings.SetConnectionString("CMSConnectionString", azureConnectionString);
}
}
}
From a fresh installation of Kentico Xperience 13, here are steps to configure this:
Follow the steps here to add Key Vault support to the admin app locally: https://learn.microsoft.com/en-us/azure/key-vault/general/vs-key-vault-add-connected-service.
Add the module above to the solution in a class library. Make sure the main project references the class library so that it is included during building.
Ensure that the ~\web.config does not have a connection string, or an app setting, named CMSConnectionString.
Deploy the app to an App Service.
In Azure, create an App Service configuration setting with name CMSConnectionString and value #Microsoft.KeyVault(VaultName=your-keyvault;SecretName=CMSConnectionString).
In the Key Vault, create a secret with name CMSConnectionString and value a connection string to an Azure SQL database. You may also need to follow https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references to create an access policy for my App Service.
At this point, the Kentico Xperience 13 admin should load with access to the database.
In the App Service portal, under Development Tools select Console.
In the console, run cd bin and then ContinuousIntegration.exe -r. This should produce a message about the repository not being configured, or output on the restore action.

How to use Azure App Settings in a Blazor WebAssembly Client side application at runtime as appsettings.json configuration?

I'm Working on Blazor WebAssembly Client/Server project (directory structure as above)
Have some application settings in both client and server projects.
The projects are hosted in Azure.
The problem is in the Client side with the appsettings.json
In the client side, the appsettings.json is within the wwwroot directory. It is okay to access the file within the app, However, the settings cannot be overwritten by Azure Portal Application Settings of the App service.
It means, that after the app is deployed in Azure portal on a Web App Service, my configuration settings do not work with the application settings' variables.
This is the code in the Progam.cs, which works fine and read the configuration from the file, but ignores the configuration settings of the Web App Service on Azure.
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
//Add a named httpClient and set base Address and Default Request Headers
builder.Services.AddHttpClient("SOME_WEB_URL", client => // SOME_WEB_URL is defined in the appsettings.json or in the Azure App Service configuration (Application Settings)
{
client.BaseAddress = new Uri(builder.Configuration["sbformsapi"]);
});
//Add a named httpClient and set base Address and Default Request Headers
builder.Services.AddHttpClient("WEB_APP_API", client => // WEB_APP_API is defined in the
{
client.BaseAddress = new Uri(builder.Configuration["sbwebappapi"]);
});
builder.Services.AddAuthorizationCore();
....
await builder.Build().RunAsync();
}
Could someone please guide how can I either
set the appsettings.json file outside the wwwroot and read it from there?
OR
inject/use the values from Azure App Service configuration's Application settings at runtime?
I am talking about the application settings here (as in the pic)...
Currently application settings are only available for the backend API associated with your Blazor App (assuming using Static App?).
https://learn.microsoft.com/en-gb/azure/static-web-apps/application-settings
So, looking at the Blazor docs, I don't think it is possible to load Azure App Settings directly in a WebAssembly. You can look for yourself
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0
I suggest instead to put the backend URL in the appsettings.json and then use a backend service to load the configuration information from there.

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.

Resources