Reading settings from a Azure Function - c#

I'm new to Azure's function... I've created a new timer function (will be fired every 30 minutes) and it has to perform a query on a URL, then push data on the buffer..
I've done
public static void Run(TimerInfo myTimer, TraceWriter log)
{
var s = CloudConfigurationManager.GetSetting("url");
log.Info(s);
}
And in my function settings I've
What am I doing wrong?
Thanks

Note that for Azure Functions v2 this is no longer true.
The following is from Jon Gallant's blog:
For Azure Functions v2, the ConfigurationManager is not supported and you must use the ASP.NET Core Configuration system:
Include the following using statement:
using Microsoft.Extensions.Configuration;
Include the ExecutionContext as a parameter
public static void Run(InboundMessage inboundMessage,
TraceWriter log,
out string outboundMessage,
ExecutionContext context)
Get the IConfiguration Root
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
And use it to reference AppSettings keys
var password = config["password"]
When debugging locally, it gets the settings from local.settings.json under the "Values" keyword. When running in Azure, it gets the settings from the Application settings tab.

You can use System.Environment.GetEnvironmentVariable like this:
var value = Environment.GetEnvironmentVariable("your_key_here")
This gets settings whenever you're working locally or on Azure.

You need to go to Platform Features -> Application settings and add it there.
Add the setting under App settings.
Reading the setting can be done by first adding this at the top:
using System.Configuration;
And then reading a setting with:
string setting = ConfigurationManager.AppSettings["url"];
Where url is your setting key. The setting variable will contain your setting value.

Recommended way — use environment variable to read settings
string Secret = System.Environment.GetEnvironmentVariable("Secret");
This works perfect if you run from your local PC or from Azure Functions using C#

You don't have to do step 3 anymore. Just do the following in your Startup.cs
`
Startup.cs
public IConfiguration Configuration { get; }
public Startup() { }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
Then use DI in your code file:
`
YourCode.cs
public class SomeWorker : ISomeWorker
{
private readonly IConfiguration _configuration;
public SomeWorker(IConfiguration configuration)
{
_configuration = configuration;
}
public void bool ForKicks()
{
// Get Value
var val = _configuration["SomeValueInLocalSettingsJsonFile"];
}
// Other code here...
}

For those who needs to do it in python :
import os
os.environ['ENVIRONMENT_VARIABLE']

Related

appsettings.json values not binding in Azure Functions App V3

I am a new a developer in terms of dealing with creating an Azure functions App. Since we have different environments for deployment, we use environment based appsettings.json files to load the correct values from the Azure Key Vault. I followed the tutorial here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection for adding appsettings.json files. Here is what my Startup class looks like.
[assembly: FunctionsStartup(typeof(Trialtimer.FunctionApp.Startup))]
namespace Trialtimer.FunctionApp
{
public class Startup: FunctionsStartup
{
public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
FunctionsHostBuilderContext context = builder.GetContext();
var config = builder.ConfigurationBuilder
.AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: true, reloadOnChange: false)
.AddJsonFile(Path.Combine(context.ApplicationRootPath, $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json"), optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddOptions<MyOptions>().Configure<IConfiguration>((options, configuration) =>
{
var section = configuration.GetSection("MyOptions");
section.Bind(options);
});
}
}
}
My appsettings.json file is empty while my appsettings.build.json file has the following, based on the tutorial above
"MyOptions": {
"MyCustomSetting": "Foobar"
}
My MyOptions class is the following
public class MyOptions
{
public string MyCustomSetting { get; set; }
}
My main class which houses the Azure Timer function is the following
public class TestTimerFunction
{
private readonly MyOptions _settings;
public TestTimerFunction(IOptions<MyOptions> options)
{
_settings = options.Value;
}
[FunctionName("AzureTimerFunction")]
public async Task Run([TimerTrigger("*/3 * * * * *")]TimerInfo myTimer, ILogger log)
{
var option = _settings;
log.LogInformation($"Renew function executed at: {DateTime.Now} successfully with {option.MyCustomSetting}");
}
}
The problem i'm having is, when i run the app, the "MyCustomSetting" variable is null. If i add the same json block that is in my appsettings.build.json file to the local.settings.json file, it looks like it gets read correctly and "MyCustomSetting" has the value "FooBar".
The ASPNETCORE_ENVIRONMENT variable is also correctly returning "build". I've checked to make sure that both the appsettings.json files are "Copy if Newer" and when hovering over the "configuration" variable in the "Configure" method, i see that my appsettings.build.json file there. How can I make the function app bind the block from appsettings.build.json rather than local.settings.json? Am i doing something incorrectly?
Got it to work by swapping out the
builder.Services.AddOptions<MyOptions>().Configure<IConfiguration>((options, configuration) =>
{
var section = configuration.GetSection("MyOptions");
section.Bind(options);
});
with
builder.Services.Configure<MyOptions>(builder.GetContext().Configuration.GetSection("MyOptions"));
I don't know why this worked while the way that was described in the tutorial did not. But this has resolved my issue so I'm marking the question as answered.

Is it possible to save Azure Function app setting from code?

Let's consider the following class that I'm using for a configuration for my Azure function:
internal class Configuration
{
private readonly IConfigurationRoot config;
public Configuration(ExecutionContext context)
{
config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
public bool MyFlag
{
get => bool.TryParse(config[nameof(MyFlag)], out var value) ? value : false;
set => config[nameof(MyFlag)] = value.ToString();
}
}
The function can easily read the MyFlag property out of the app settings.
But I want my function to be able to set the value of the MyFlag property in azure function app settings as well. Unfortunately, the value doesn't get changed on both Azure and local environments.
I tried to bind the property like this
config.Bind("Values", this);
in the Configuration class constructor and it works but only on local environment. However, it doesn't work on Azure environment.
Is it possible to store the value to the app settings from azure function?
You need to use the IConfiguration class to be able to retrieve values from the appSettings config or also can be called as your local.settings.json.
To access you myFlag you can do this
public MyService(IConfiguration configuration){
// For a section
var emailConfig = configuration.GetSection("Email");
// For a single value
var myFlagVal = config["MyFlag"];
}
Another post with a solution exists here : Save Changes of IConfigurationRoot sections to its *.json file in .net Core 2.2
Hope it answers to your question as expected...

Can't read data from config.json in .NET Core 2 console application

I have the following code.
IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", true, true)
.Build();
string beep = config.GetSection("beep").Value;
My config.json looks like this.
{ "beep": "bopp" }
When I hit a breakpoint I can see that there's one provider but the data in it is of zero length. I've tried different approaches as config["beep"] etc. but sems to fail to get the value in. It's null all the time. I'm trying to follow the docs but must be missing something.
Make sure the json file is set to copy to directory as discussed in this blog. Otherwise when you build or debug the configuration file won’t be included. Make sure you change it in the properties.
The reason you are not able to access your configuration, is because the IConfigurationRoot does not reference the dependency for ConfigurationBuilder. To ensure that your configuration content will load, would be to do something along these lines:
public static class ConfigurationProvider
{
public static IConfiguration BuildConfiguration => new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.Build();
}
The above will build our configuration, now we should use the configuration.
public static class ServiceProvider
{
public static IServiceProvider BuildServiceProvider(IServiceCollection services) => services
.BuildDependencies()
.BuildServiceProvider();
}
Once we have defined our provider, we can do the following so we can pass our IConfiguration around the application to access the objects.
var serviceCollection = new ServiceCollection()
.AddSingleton(configuration => ConfigurationProvider.BuildConfiguration());
var serviceProvider = ServiceProvider.BuildServiceProvider(serviceCollection);
Then inside of another class, you would have the following:
public class SampleContext : ISampleRepository
{
private readonly string dbConection;
public SampleContext(IConfiguration configuration) => configuration.GetConnectionString("dbConnection");
...
}
Then our appsettings.json would look like this:
{
"ConnectionStrings": {
"dbConnection": "..."
}
}
The above is the correct format for a json object. If you have a nested object along these lines:
{
"Sample" : {
"Api" : {
"SampleGet" : "..."
}
}
}
Then your C# would be:
configuration.GetSection("Sample:Api")["SampleGet"];
The above is based on the assumption your configuration and usage are not in the same sequential area, ie directly in your main. Also you should use appsettings.json since that is the default, less extra wiring if I remember correctly. Your json also needs to be correctly formatted.
But that will definately work, if you need more help let me know and I can send you some sample console core applications to demonstrate usage.
I feel like you are just missing the name for the object.
Try adding a name for the object in the config.json like so:
{"beep":{"beep":"bopp"}}
Then you can do string beep =config.GetSection("beep").Value

Get root directory of Azure Function App v2

I build an Azure Function App (v2). Configuration tasks necessary for all functions are done in a Setup class that is structured like the following:
[assembly: WebJobsStartup(typeof(Startup))]
internal class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(<functionAppDirectory>)
.AddJsonFile("local.settings.json")
.Build();
builder.AddDependencyInjection(ConfigureServices);
}
public IConfiguration Configuration { get; set; }
private void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("<myconnection-string>");
...
}
}
In ConfigureServices I want to read a connection string from a configuration file. For that the function app base folder has be specified with SetBasePath. But I found no way to get access to this path. According to https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function an ExecutionContext can be injected in a function, which contains the path need. But how do I access ExecutionContext in my Startup class?
You can use this piece of code in your startup file.
I have just tested it today for my project and it works on both cloud and local.
var executioncontextoptions = builder.Services.BuildServiceProvider()
.GetService<IOptions<ExecutionContextOptions>>().Value;
var currentDirectory = executioncontextoptions.AppDirectory;
TL;DR: just use Environment.GetEnvironmentVariable.
The ConfigurationBuilder approach shows up in a lot of blog posts, and worked up until we started doing DI. But there is no context parameter, so ConfigurationBuilder immediately starts to cause some strain.
I think people went this direction because in Azure Functions 2, we switched to ASP.NET Core configuration which caused ConfigurationManager to stop working. ConfigurationBuilder was a reasonable place to land. It felt congruent with MVC, and worked fine up until the introduction of DI.
But now that we are doing DI, it's becoming clear that Environment.GetEnvironmentVariable might have been the better choice all along for this platform... There's less code overhead, and it maps cleanly to the configuration model of Azure Functions: in dev, it picks up items in the local.settings.json > Values array, and in production it picks up your environment variables, and it just works.
It is different than what we do in MVC. Until these platforms come into closer parity, however, we should do what makes sense in Functions, rather than trying to force solutions from MVC.
So:
[assembly: WebJobsStartup(typeof(StartUp))]
namespace Keystone.AzureFunctions
{
public class StartUp : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var connectionString = Environment.GetEnvironmentVariable("KeystoneDB");
// Configure EF
builder.Services.AddDbContext<KeystoneDB>(options => options.UseSqlServer(connectionString));
}
}
}
And your local.settings.json might look like this:
{
"IsEncrypted": false,
"Values": {
"KeystoneDB": "[CONNECTION STRING HERE]"
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
You can also use Key Vault with Environment. It works great.
Greeting,
I found a solution that works in the Startup :
var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
string path = fileInfo.Directory.Parent.FullName;
var configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.SetBasePath(path)
.AddJsonFile("appsettings.json", false)
.Build();
You might want to use FunctionsStartupAttribute and IFunctionsHostBuilder from Microsoft.Azure.Functions.Extensions, for example:
[assembly:FunctionsStartup(typeof(SampleFunction.FunctionsAppStartup))]
namespace SampleFunction
{
public class FunctionsAppStartup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
string appRootPath = builder.GetContext().ApplicationRootPath;
// ...
}
}
}
The only workaround I found for configuration builder in Startup() method is to use hardcoded path "/home/site/wwwroot/"
var config = new ConfigurationBuilder()
.SetBasePath("/home/site/wwwroot/")
.AddJsonFile("config.json", optional: false)
.Build();
System.Environment.CurrentDirectory does not work in Azure. Though it works locally. But in Azure it gives an error: The configuration file 'config.json' was not found and is not optional. The physical path is '/config.json'. And function does not start.
Try using Environment.CurrentDirectory

How do I access Configuration in any class in ASP.NET Core?

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.
Below is Startup.cs created by template
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}
}
So in Startup.cs we configure all the settings, Startup.cs also has a property named Configuration
What I'm not able to understand how do you access this configuration in controller or anywhere in the application? MS is recommending to use options pattern but I have only 4-5 key-value pairs so I would like not to use options pattern. I just wanted to have access to Configuration in application. How do I inject it in any class?
Update
Using ASP.NET Core 2.0 will automatically add the IConfiguration instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration on the WebHostBuilder.
For example:
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.AddIniFile("foo.ini");
})
.UseStartup<Startup>()
.Build();
host.Run();
}
It's just as easy as adding the IConfiguration instance to the service collection as a singleton object in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// ...
}
Where Configuration is the instance in your Startup class.
This allows you to inject IConfiguration in any controller or service:
public class HomeController
{
public HomeController(IConfiguration configuration)
{
// Use IConfiguration instance
}
}
The right way to do it:
In .NET Core you can inject the IConfiguration as a parameter into your Class constructor, and it will be available.
public class MyClass
{
private IConfiguration configuration;
public MyClass(IConfiguration configuration)
{
ConnectionString = new configuration.GetValue<string>("ConnectionString");
}
Now, when you want to create an instance of your class, since your class gets injected the IConfiguration, you won't be able to just do new MyClass(), because it needs a IConfiguration parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:
1) Add your Class/es - where you want to use the IConfiguration, to the IServiceCollection at the ConfigureServices() method in Startup.cs
services.AddTransient<MyClass>();
2) Define an instance - let's say in the Controller, and inject it using the constructor:
public class MyController : ControllerBase
{
private MyClass _myClass;
public MyController(MyClass myClass)
{
_myClass = myClass;
}
Now you should be able to enjoy your _myClass.configuration freely...
Another option:
If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class, which you will configure in the Startup.cs, something like:
public static class MyAppData
{
public static IConfiguration Configuration;
}
And your Startup constructor should look like this:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
MyAppData.Configuration = configuration;
}
Then use MyAppData.Configuration anywhere in your program.
Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.
I know this is old but given the IOptions patterns is relatively simple to implement:
Class with public get/set properties that match the settings in the configuration
public class ApplicationSettings
{
public string UrlBasePath { get; set; }
}
register your settings
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
...
}
inject via IOptions
public class HomeController
{
public HomeController(IOptions<ApplicationSettings> appSettings)
{ ...
appSettings.Value.UrlBasePath
...
// or better practice create a readonly private reference
}
}
I'm not sure why you wouldn't just do this.
There is also an option to make configuration static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
internal static IConfiguration Configuration { get; private set; }
This makes configuration accessible anywhere using Startup.Configuration.GetSection... What can go wrong?
I'm doing it like this at the moment:
// Requires NuGet package Microsoft.Extensions.Configuration.Json
using Microsoft.Extensions.Configuration;
using System.IO;
namespace ImagesToMssql.AppsettingsJson
{
public static class AppSettingsJson
{
public static IConfigurationRoot GetAppSettings()
{
string applicationExeDirectory = ApplicationExeDirectory();
var builder = new ConfigurationBuilder()
.SetBasePath(applicationExeDirectory)
.AddJsonFile("appsettings.json");
return builder.Build();
}
private static string ApplicationExeDirectory()
{
var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
var appRoot = Path.GetDirectoryName(location);
return appRoot;
}
}
}
And then I use this where I need to get the data from the appsettings.json file:
var appSettingsJson = AppSettingsJson.GetAppSettings();
// appSettingsJson["keyName"]
I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:
My startup class is as default
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
My appsettings.json is like this
{
"CompanySettings": {
"name": "Fake Co"
}
}
My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;
public class EmployeeController
{
private IConfiguration _configuration;
public EmployeeController(IConfiguration configuration)
{
_configuration = configuration;
}
}
Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
var companyName = configuration.GetValue<string>("CompanySettings:name");
// companyName = "Fake Co"
}
I looked into the options pattern sample and saw this:
public class Startup
{
public Startup(IConfiguration config)
{
// Configuration from appsettings.json has already been loaded by
// CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
// the configuration into the Configuration property.
Configuration = config;
}
...
}
When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.
Example:
public class MyClass{
private Iconfiguration _config;
public MyClass(Iconfiguration config){
_config = config;
}
... // access _config["myAppSetting"] anywhere in this class
}
In 8-2017 Microsoft came out with System.Configuration for .NET CORE v4.4. Currently v4.5 and v4.6 preview.
For those of us, who works on transformation from .Net Framework to CORE, this is essential. It allows to keep and use current app.config files, which can be accessed from any assembly. It is probably even can be an alternative to appsettings.json, since Microsoft realized the need for it. It works same as before in FW. There is one difference:
In the web applications, [e.g. ASP.NET CORE WEB API] you need to use app.config and not web.config for your appSettings or configurationSection. You might need to use web.config but only if you deploying your site via IIS. You place IIS-specific settings into web.config
I've tested it with netstandard20 DLL and Asp.net Core Web Api and it is all working.
Using the Options pattern in ASP.NET Core is the way to go. I just want to add, if you need to access the options within your startup.cs, I recommend to do it this way:
CosmosDbOptions.cs:
public class CosmosDbOptions
{
public string ConnectionString { get; set; }
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// This is how you can access the Connection String:
var connectionString = Configuration.GetSection(nameof(CosmosDbOptions))[nameof(CosmosDbOptions.ConnectionString)];
}
I have to read own parameters by startup.
That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.
After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...
Complete example, valid for core 2.1 (mvc):
Create an .ini-file - example:
[Startup]
URL=http://172.16.1.201:22222
[Parameter]
*Dummy1=gew7623
Dummy1=true
Dummy2=1
whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).
Added a code file in the root of the project, to store the global variables:
namespace MatrixGuide
{
public static class GV
{
// In this class all gobals are defined
static string _cURL;
public static string cURL // URL (IP + Port) on that the application has to listen
{
get { return _cURL; }
set { _cURL = value; }
}
static bool _bdummy1;
public static bool bdummy1 //
{
get { return _bdummy1; }
set { _bdummy1 = value; }
}
static int _idummy1;
public static int idummy1 //
{
get { return _idummy1; }
set { _idummy1 = value; }
}
static bool _bFehler_Ini;
public static bool bFehler_Ini //
{
get { return _bFehler_Ini; }
set { _bFehler_Ini = value; }
}
// add further GV variables here..
}
// Add further classes here...
}
Changed the code in program.cs (before CreateWebHostBuilder()):
namespace MatrixGuide
{
public class Program
{
public static void Main(string[] args)
{
// Read .ini file and overtake the contend in globale
// Do it in an try-catch to be able to react to errors
GV.bFehler_Ini = false;
try
{
var iniconfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
.Build();
string cURL = iniconfig.GetValue<string>("Startup:URL");
bool bdummy1 = iniconfig.GetValue<bool>("Parameter:Dummy1");
int idummy2 = iniconfig.GetValue<int>("Parameter:Dummy2");
//
GV.cURL = cURL;
GV.bdummy1 = bdummy1;
GV.idummy1 = idummy2;
}
catch (Exception e)
{
GV.bFehler_Ini = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
Console.WriteLine("Message:" + e.Message);
if (!(e.InnerException != null))
{
Console.WriteLine("InnerException: " + e.InnerException.ToString());
}
Console.ForegroundColor = ConsoleColor.White;
}
// End .ini file processing
//
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>() //;
.UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress
}
}
This way:
My Application config is separated from the appsettings.json and I
have no sideeffects to fear, if MS does changes in future versions ;-)
I have my settings in global variables
I am able to set the "to listen url" for each device, the applicaton run's on (my dev machine, the intranet server and the internet server)
I'm able to deactivate settings, the old way (just set a * before)
I'm able to react, if something is wrong in the .ini file (e.g. type mismatch)
If - e.g. - a wrong type is set (e.g. the *Dummy1=gew7623 is activated instead of
the Dummy1=true) the host shows red information's on the console
(including the exception) and I' able to react also in the
application (GV.bFehler_Ini ist set to true, if there are errors with
the .ini)

Categories

Resources