I have a console app in .Net 6 and wondering how can I have multiple appSettings files?
I want to have one for
appsettings.development.json
appsettings.test.json
appsettings.production.json
I will be deploying the console application onto windows servers and hooking it up to a scheduled task. Depending on which environment I want a different appsettings to be used. I am not sure how to do this.
I think I would have to create an environment variable on each server to make it use the right file but hoping there is more a coding way automatically use the right appsettings file.
I found this posting that seems to be almost what I need but it is for web apps and not console apps
Automatically set appsettings.json for dev and release environments in asp.net core?
You can pass environment variable via line argument, like this
C:\Myapp.exe --environment Development
EDT.
Then, (just because you have console app) you need to install Microsoft.Extensions.Configuration.CommandLine and Microsoft.Extensions.Configuration.Json packages from nuget.
After intall, get your line argument in IConfigurationRoot with:
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
Retrive your environment variable:
var environmentName = config["environment"];
And finally, build your config from appsettings.json:
var myConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json")
.Build();
Related
How can I configure application insights telemetry for an asp.net framework 4.7.1 web application that uses appsettings.json configuration files? I tried checking the Microsoft documentation but it just shows setup for ASP.NET apps that use xml-based configuration.
EDIT: Here is the part of the Startup.cs file that shows I am using appsettings.json.
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
SCENARIO - 1
This works in case of .net framework 4.7.1 web application which have no auto generated appsettings.json file.
Navigate to your Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close
In applicationinsights.config file, while Adding Application Insights automatically we need to add instrumentation key to ApplicationInsights.config before closing the </ApplicationInsights> tag file.
<InstrumentationKey>"your-instrumentation-key-goes-here"</InstrumentationKey>
And then update each Microsoft.ApplicationInsights NuGet package to the latest stable release by navigating to Project > Manage NuGet Packages > Updates.
If Adding Application Insights Automatically isn't working, then you can try manually from HERE.
REFERENCE : Configure monitoring for ASP.NET with Azure Application Insights
SCENARIO - 2
You can have application Insights configuration set from your appsettings.json file when you have one in your project
Navigate to your appsettings.json file and add your instrumentation key for your application Insights like mentioned inthe below reference.
Application Insights comes in the form of a Nuget package. Review the .csproj file of the web project and look for the Application Insights package added.
Now navigate to your startup.cs project and add services.AddApplicationInsightsTelemetry(Configuration); to your ConfigureServices method.
Navigate to Configure method and add
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
REFERENCE : Monitoring Applications using Application Insights
I'm developing an Azure webjob using .NET Framework but when I'll run this localy, I've this exception after the startup.
Microsoft.Azure.WebJobs.Host.Listeners.FunctionListenerException: The listener for function [Name of function] was unable to start.
Inner exception:
ArgumentNullException: Value cannot be null.
Parameter name: connectionString
This is the code inside the Program class of the web job.
static void Main()
{
HostBuilder builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddTimers();
});
using (IHost host = builder.Build())
{
host.Run(); // <-- error happens on this line
}
}
Inside the App.config I've added next two connection strings:
<add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=[Name];AccountKey=[Key]" />
<add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=[Name];AccountKey=[Key]" />
With [Name] and [Key] as the account name en key from a live environment.
Also when I change the connection strings to UseDevelopmentStorage=true, I'm getting the same exception.
How could I solve this?
Update:
If you're using Azure WebJobs SDK of version 3.x with .NET Framework, there is an issue: Version 3.x is incompatible with .NET Framework and PackageReference.
So there're several ways as workaround:
Directly use the Azure WebJobs template from Visual studio, it's based on .net framework.
You can add an appsettings.json file (Note: right click the file → select Properties → then set "Copy to Output Directory" to "Copy if newer") to the .NET Framework project, it will work(based on 1, it will throw errors, but it can work). The JSON file looks like below:
{
"AzureWebJobsStorage": "{storage connection string}"
}
The best solution is to use .NET Core with WebJobs SDK of version 3.x.
Original answer:
If you're using WebJob SDK version 3.x, I suggest you should create a .NET Core console project instead of .NET Framework console project, then you should follow this official doc.
First, create a .NET Core console app. And install all the necessary packages mentioned in the official doc.
Your program.cs:
static void Main()
{
HostBuilder builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
b.AddTimers();
});
using (IHost host = builder.Build())
{
host.Run();
}
}
Then create a function, please refer to this section.
Then add an appsettings.json file (Note: right click the file → select Properties → then set "Copy to Output Directory" to "Copy if newer"), add the AzureWebJobsStorage inside it:
{
"AzureWebJobsStorage": "{storage connection string}"
}
Please let me know if you still have more issues about that.
I have an ASP Core 2.2 application which runs fine.
I have an appsettings.json
I have an appsettings.QA.json
I have an Azure App Service which I have added ASPNETCORE_ENVIRONMENT variable to in the Configuration > App Settings section of the portal and set the value to "QA".
I have also added a connection string directly to the Configuration > Connection Strings section of the portal.
When I publish to my Azure App Service, I want to override the settings in appsettings.json with values from appsettings.QA.json. I am struggling to make sense of how this should be configured.
I am reading out the values from the appsettings via the Microsoft.Extensions.Configuration.IConfiguration implementation which is injected into classes where I need such configuration.
So far I have the following:
Program.cs:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
})
.UseStartup<Startup>();
When the app runs in Azure, it is picking up the connection string from the portal and using it. However, when I read out a value from the appsettings, I always get the value from appsettings.json not appsettings.QA.json.
Can anyone point out how to configure the transforms correctly for an ASP Core 2.2 application?
Am I going about this in the wrong way entirely?
Update
I have removed my custom code above as suggested as it is not needed.
If I output #Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") in my view, I get: "QA;Development". It seems that the "Development" is coming from the web.config which also has ASPNETCORE_ENVIRONMENT set.
you shouldn’t read environment from appsettings. environment is set on machine level and is read at startup.
you have 2 options:
for local machine, set environment variable in launch.settings
in azure, set it in app service configuration as environment variable
ref: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.2
I now have this working correctly:
Removed the custom code from the Program.cs as suggested by #KirkLarkin and #dee-zg.
Removed the ASPNETCORE_ENVIRONMENT setting from the Azure portal. The reason for this is that there is also a web.config in the app which has this setting. When reading from the config, it seems that this version is used, not the Azure portal version.
Why is the ASPNETCORE_ENVIRONMENT in the web.config? There is a discussion about this here. Ultimately, what I have done to work around this is to add transforms for the web.config.
Empty/null value returned when attempting to read from the local.settings.json config file when debugging an Azure Function locally using VS2017 for Mac... after scanning the internet I wasn't able to determine if this is a known issue or if there is a work around. This is how I'm accessing the configuration settings:
ConfigurationManager.ConnectionStrings["connName"].ConnectionString
This works fine if the Function app is debugged on a Windows Machine (same git code base)
Azure function v2 running on runtime 2.x(.net core) doesn't support ConfigurationManager any more. See Azure Team's reply on github.
When I debug a v2 function on Windows, System.Configuration.ConfigurationErrorsException thrown. And v1 still works well as you have found.
So as #mariocatch has said, try to read enviroment variables instead.
Two options for you to refer.
Read environment variables directly
string connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:connName");
Add ExecutionContext context to your function method parameters and read local settings.
[FunctionName("FunctionName")]
public static void Run(...,ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
string connectionString = config.GetConnectionString("connName");
.....
}
I have a test project within my solution that can run tests on a live sql database. The problem is I have to provide the connection string for it to connect to the database.
Is there anyway that I can provide a different connection string specified in the Visual Studio Online Build Parameters/Variables? I've looked into creating an appsettings.json file to but I'm still not sure how to override the value in appsettings.json.
It might be important to note that my test project is testing EF Core SqlServer.
Proceeding with appsettings.json or a config file is the correct approach. What you need in addition is the Tokenizer build task that will replace the connection string with the value of a VSO variable.
In the configuration file (appsettings.json), provide the value as __SQLConnectionString__ for the connection string property. Then, in the build VSO variable, add a variable with the name SQLConnectionString. Whatever value you provide for this variable, the Tokenizer task will replace the __SQLConnectionString__ with this value.
To get this working. I added an appsettings.json file and changed the property Copy to Output Directory to Copy Always. I then an abstract class called DbTests with a setup method
appsettings.json
{
"ConnectionStrings": {
"TestDatabase": "YOUR CONNECTION STRING GOES HERE"
}
}
DbTests.cs (snippet)
// ...
IConfigurationRoot configurationRoot = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables() // <== this is important
.Build();
string connectionString = configurationRoot.GetConnectionString("TestDatabase")
// ...
The .AddEnvironmentVariables() allows me to override variables contained in the appsettings.json with environment variables. I can set environment variables within VSTS