Value not being read in AppSettings using host.Appsettings.GetString() - c#

I am getting a project setup. I have my redis configuration in appsettings as shown below. However, when I attempt to get the string from the appsettings I get null value. See below code. Let me know if there is something I am missing. I get the following error. One thing to note is that I am getting count value of 0 in Data for provider. in Appsettings object. Not sure what may be causing this.
Code to for retrieving appsettings
var redis= host.AppSettings.GetString("AppSettings:Redis.Host.Default");
var rf= new PooledRedisClientManager(redis);
My appsettings looks like this.
"AppSettings": {
"Redis.Host.Default": "REDIS:6379",
}
}
I attempted to build demos and clean DLL's. I also copied appsettings directly from live production environment but that did not fix the null issue

Related

Does development environment on Net Core 6 implies that it reads configurations from appsettings.Development first?

Good morning guys, just a simple question regarding this little builder snippets in Program.cs.
builder.Services.AddDbContext<SteelworksContext>(options =>
{
if (builder.Environment.IsDevelopment())
{
options.UseSqlServer(builder.Configuration.GetConnectionString("SteelworksDev")); //from appsettings.Development
}
else
{
options.UseSqlServer(builder.Configuration.GetConnectionString("Steelworks")); //from appsettings
}
});
Does that code implies that if condition is true the connection string is read from appsettings.Development or it just reads from appsettings as it normally does?
It depends on how the config settings have been loaded into the program but that would be a reasonable assumption to make.
You should look at the code that loads the config settings (this might be in a Startup class but will depend on your project).
FYI: It looks like the connection string has a different name in the appsettings & appsettings.Development config files. This is unnecessary and somewhat defeats the point of having the two files. Both files should just have the same connection string name e.g. "Steelworks" and only one line of code that sets up the DbContext:
options.UseSqlServer(builder.Configuration.GetConnectionString("Steelworks"));

C# AWS Parameter Store - Configuration not loading SystemManagerConfiguration in .Net 6

Application is not able to talk to AWS Parameter Store in .NET 6.
It is always talking to appsettings.json.
I tried debugging locally, still same behavior. Not able to find the SystemManagerConfiguration under list of configuration .
var builder = WebApplication.CreateBuilder();
var connectionString = builder.Configuration.GetConnectionString("OrderTrackerDatabase");
Packages Used
Library Source Code : https://github.com/aws/aws-dotnet-extensions-configuration
image
I got the same issue and finally resolved it.
The samples code in https://github.com/aws/aws-dotnet-extensions-configuration missed one line as below after called "AddSystemsManager" method in .Net 6.
builder.Services.Configure<Settings>(builder.Configuration.GetSection($"common:settings"));
After added above line, then I'm able to get the correct values from AWS Parameter Store when using the settings.
I've also created an issue of this in GitHub as below -
https://github.com/aws/aws-dotnet-extensions-configuration/issues/114
I believe the problem might be the trailing slash after "/OrderTracking/", try "/OrderTracking" instead.
WebApplication.CreateBuilder() will create new instance and doesn't carry over the SystemManager configuration.
Instead, use IConfiguration instance through constructor DI.
var connectionString = _configuration.GetConnectionString("OrderTrackerDatabase");
In my case this extensions method was returning null at my lambda:
private static IConfiguration InitializeConfiguration() => new ConfigurationBuilder()
.AddSystemsManager($"/my-data", true, TimeSpan.FromMinutes(5))
.Build();
Because the role of lambda didn't have permission for read SSM for that resource.
User: is not authorized to perform: ssm:GetParametersByPath on resource
So, just add necessary permission (ssm:GetParametersByPath) for the role of lambda to your resource at System Manager.
In my case, I am using lambda serverless, so the IConfig is always null when it is passed to the controller.
I resolved it by changing the IOptions<Settings> settings in the Controller constructor to IConfiguration settings and then access the parameters by name like _settings.GetValue<string>("ParameterName")
A little less "Object Oriented", but it seemed much easier than this complex solution

Change a Line of Code based on Configuration selected

In my ASP.NET MVC 3 application, I have 2 configurations setup; Play and Live.
Right now, I have to change the following code before loading my application with a configuration based on what I currently have selected:
Mailer.SendMessageTo("playEmailAddress", "MailBody");
// Mailer.SendMessageTo("liveEmailAddress", "MailBody");
So if I have Play configuration selected I'll comment out the liveEmailAddress line and vice versa
What I'd like to do is perhaps make use of the web.config file to change this code for me without manually doing it every time I load up my application with a different configuration by putting the lines of code in the config file and then reading it from the config file from within my class
You should add the "app key" in your web configuration file. Give it anyname like "OptionalEmail" and set the value accordingly.
When you send the email check the value in the configuration file like
If(ConfigurationManager.AppSettings["OptionalEmail"]=="PlayEmail")
SendEmail using PlayEmail address else SendEmail using Work emai
Address.
Hope this help. "ConfigurationManager.AppSettings[use key or index]
Please keep in mind, Config Transformations "xdt" works only when you deploy your web application.
it's generally a good idea to have a configuration parameter named "environment" (or the like).
This link explains how to read from the web.config: http://msdn.microsoft.com/en-us/library/610xe886.aspx.
one way to implement this would be:
var env = "play";
if( ConfigurationManager.AppSettings["environment"]=="live" ) env="live";
var email = env + "EmailAddress";
Mailer.SendMessageTo(email, "MailBody");
as an additional note, if you have multiple developers that each want their own "play"-Address, then you can extend the setting to include the developers machine name:
<appSettings>
<add key="environment" value="play"/>
<add key="liveEmailAddress" value="a#b.com"/>
<add key="myCoolPC-playEmailAddress" value="c#d.com"/>
<add key="otherDevPC-playEmailAddress" value="bubba#test.com"/>
</appSettings>
but then you would have to change the implementation above to prefix the hostname before getting the setting, but only if currently in play-mode.

Programatically access arbitrary web.config - can't access appSettings (app.config is fine)

I'm accessing a config file thusly:
var map = new ConfigurationFileMap(configPath);
var config = ConfigurationManager.OpenMappedMachineConfiguration(map);
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
It works fine for any .exe.config file, but not for any web.config.
Note: I am not trying to access the web.config of the current application, I am attempting to modify the web.config in an arbitrary path.
(I've tried WebConfigurationManager instead of ConfigurationManager, but it gives identical results)
The exception is thrown by the AppSettings property accessor - trying to GetSection("appSettings") and cast it to an AppSettingsSection of course gievs the same exception. Either way, here it is:
System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
I have obviously searched around, but have found only people accessing the web.config for the 'current web app' or using XmlDocument/XDocument.
My guess is .exe.config files automatically get some configSections-type information inferred which means it correctly knows how to deal with appSettings. However I have no idea why, based on the filename, it wouldn't work with web.config.
Ah. For app.config I'm using OpenExeConfiguration:
// works fine for .exe.config
var config = ConfigurationManager.OpenExeConfiguration("some-assembly-here.exe");
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
config.Save();
Here I'm using OpenMappedMachineConfiguration which appears to be for machine.config, however I can't see another way of opening an arbitrary web.config file - anyone?
My mistake - I can use OpenMappedExeConfiguration just fine when opening web.config files:
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

get reference to the ASP.NET web.config customErrors section

I'm trying to obtain a reference to the web.config customErrors section. When I use the following code I always get a null. I don't have this problem when I get a reference to a custom section that I've created so I'm a bit dumbfounded why this won't work.
CustomErrorsSection customErrorSection =
ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;
EDIT:
ARGH! Such is the case with most things I figured out the answer right after asking the question.
This works for me:
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
Or more simply like this:
CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
This also works:
CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
So I guess I understand now why I had the problem in the first place. I had incorrectly thought that I could get a reference to the customErrors section by trying to GetSection("customErrors") but I had failed to tell it what root section it lived in and I was basing my attempts on the fact that I knew how to get a custom section when I failed to realize that my custom section was the root of the section so I did not have to prepend something like system.Web/ in front of it when I called GetSection().
Try this:
var configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.config");
// Get the section.
CustomErrorsSection customErrors =
(CustomErrorsSection)configuration.GetSection("system.web/customErrors");
More on the subject here: CustomError Class

Categories