What does ConfigurationManager.AppSettings do? - c#

My current understanding is that it making a call to something in my config file and returning data. I am not clear what the parameters are for ConfigurationManager.AppSettings are.
I have looked through this documentation (https://msdn.microsoft.com/en-us/library/1xtk877y%28v=vs.110%29.aspx) but don't quite understand it.
For context this is the code I'm working with:
string code1 = ConfigurationManager.AppSettings[string1 + string2];
string code2 = ConfigurationManager.AppSettings[string3];
string query = new BuildMDXQuery(cube).BuildFetchInventoryQuery(code1, code2);
I'd like to know how I can find what's getting called in my config file, if anything, and what the purpose of using ConfigurationManager.AppSettings is. Thanks!

It reads from the appSettings section of the config file, so...
Configuration.AppSettings["Whatever"]
...would return "Blah" in the case of:
<configuration>
<appSettings>
<add key="Whatever" value="Blah" />
</appSettings>
</configuration>

Related

Get appSettings configSource from code

Is there a way to retrieve configSource from code? I founded How to programmatically retrieve the configSource Location from config file, but all answers are wrong.
I have following config:
<configuration>
<appSettings configSource="appsettings.config"/>
</configuration>
When I tried to invoke following code:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var file = config.AppSettings.File;
file is always empty. Same is for ConfigurationManager.AppSettings["configSource"]. I think something changed in .NET 4, because answers are old ones.
I tried also config.AppSettings.SectionInformation.ConfigSource but it is also empty.
I need this path to enable monitoring of appSettings. You could read more: How to discover that appsettings changed in C#?
I have some problems with this but I finally find an answer.
When config file looks like this:
<configuration>
<appSettings file="appsettings.config"/>
</configuration>
The code above is working correctly:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var file = config.AppSettings.File;
But when config file is (it works same as above but syntax is different):
<configuration>
<appSettings configSource="appsettings.config"/> <!-- configSource instead of file -->
</configuration>
I have to use following:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var file = config.AppSettings.SectionInformation.ConfigSource;
So I have to check if config.AppSettings.SectionInformation.ConfigSource and config.AppSettings.File is not an empty string and monitor correct one.

use ConfigurationManager to store user values in a file that is separate from the app config

Ok, I've just about given up on this.
I would like to be able to record user preferences using a user config file, which would be referenced from the app config file. I am trying to do this with ConfigurationManager and an app config file. I can read just fine from the user settings, but setting them is a whole other problem. I would like to keep the app settings separate from the user settings in two different files.
When I use this:
<appSettings file="user.config">
</appSettings>
and user.config looks like:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="localSetting" value="localVal"/>
</appSettings>
I can use ConfigurationManager to READ the local setting, but not to save to the file.
var oldLocVal = ConfigurationManager.AppSettings["localSetting"];
ConfigurationManager.AppSettings.Set("localSetting", "newLocalValue"); // Doesn't save to file.
If instead my user.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="localSetting" value="localVal"/>
</appSettings>
</configuration>
I would then like to call and save the AppSettings in this way:
var uMap = new ConfigurationFileMap("user.config");
var uConfig = ConfigurationManager.OpenMappedMachineConfiguration(uMap);
var oldLocalVarFromConfig = uConfig.AppSettings.Settings["localSetting"]; // NO
uConfig.AppSettings.Settings.Remove("localSetting"); // NO
uConfig.AppSettings.Settings.Add("localSetting", "newValue");
uConfig.Save();
but it won't let me access the configuration's app settings. (It has a problem casting something as an AppSettings)
I also tried with configSource instead of file attributes in the app config appSettings element.
I was using the examples here for help, but unfortunately it wasn't enough.
Thanks in advance.
You can load external config files into a 'Configuration' instance. Here is an example of a singleton class with a static constructor that uses this strategy. You can tweak it a bit to do what you want, I think.
private const string _path = #"E:\WhateverPath\User.config"
static ConfigManager()
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
{
ExeConfigFilename = _path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
// get some custom configuration section
_someConfigSection = config.GetSection("SomeSection") as SomeSection;
// or just get app settings
_appSettingSection = config.AppSettings;
}
Maybe try adding this way, making sure to call Save()
_appSettingSection.Settings.Add("SomeKey", "SomeValue");
//make sure to call save
config.Save();
To its credit, this code here works.
Also, I made a simple XML serializable object that saved itself to disk any time Save was called on it.

Best way to do a setting in ASP.net

With settings, I've always had some const variable in a file somewhere. Is it possible to create a new config file with all my settings for my website? IE:
CONST imagePrefixPath = "http://img.domain.com/"
Is the sort of thing I want to store and use all over my web code
Use the appSettings in the web.config instead:
<configuration>
<appSettings>
<add key="imagePrefixPath" value="http://img.domain.com/" />
</appSettings>
</configuration>
Then access it in code access the appSettings variables using OpenWebConfiguration
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
String imagePath = config.AppSettings.Settings["imagePrefixPath"] + "myimage.jpg";
You can create a Settings file (add a new item=> settings file), which will also create a strongly typed class with the same names and values you set inside it.

add connection string without using app.config

i created a data access layer dll using subsonic. however it uses the connectionstring from the app.config.
i am using it in ninjatrader and dont want to mess around with the ninjatrader app.config for the connecitonstring. how do i avoid this issue.
I believe the best you can hope for here is to use a separate file for the connection strings:
in app.config
<connectionStrings ConfigSource="myConnStr.config" />
in myConnStr.config:
<connectionStrings >
<add .... />
<add .... />
</connectionStrings >
I believe you can set it at runtime using the SetDefaultConnectionString method:
SubSonic.DataService.GetInstance("InstanceName").SetDefaultConnectionString("ConnectionString");
Sample how to programatically hardcode connectionstring:
string connectionString = string.Format(#"Data Source={0}", Path.Combine(this.ConfigFolder, ConfigDb));
string providerName = #"System.Data.SQLite";
var provider = ProviderFactory.GetProvider(connectionString, providerName);
_configRepo = new SimpleRepository(provider, SimpleRepositoryOptions.RunMigrations);
This sample use sqlite database which is located in this.ConfigFolder. ConfigDB contains name of a database file.

Get values from the web.config section in an app.config file?

I'm trying to unit test values that will eventually wind up in a web.config file. In my test project, I created an app.config file with a web.config section to hold the settings. In a normal situation, I would call System.Configuration.ConfigurationSettings.AppSettings, but in this case, that doesn't work. I saw this question, which is very similar, but doesn't address how to get the NameValueCollection out of the config file. Here is an example of the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add
name="CustomMembershipProvider"
applicationName="SettlementInfo"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="true"
writeExceptionsToEventLog="true" />
</providers>
</membership>
</system.web>
</configuration>
Has anyone dealt with this before?
I guess I'm confused here; it looks like you're trying to test that ASP.NET is using your custom membership provider appropriately. Correct?
If so, I'm 99.999% sure that you cannot unit test this using the MS framework; you must integration test it by deploying it to the webserver (or running Cassini in VS) and typing a username/password into your login page.
Now, it's possible I've misunderstood your request. If so, let me know and I'll edit my answer accordingly.
Edit:
For right now, I'm really just trying
to test the NameValue pairs coming out
of the config file, to make sure that
if the values aren't present, my
defaults are being applied. In other
words, I want to try to pull
applicationName, and verify that it
equals "SettlementInfo", and so on.
After that, I will be using
integration testing to ensure that
ASP.NET is using the custom framework
in place of the default one. Does that
make sense?
I need more than a comment to reply, so I'm editing. If I read you correctly, you are wanting to unit test your program to ensure that it deals with configuration correctly, yes? Meaning you want to ensure that your code grabs, for example, the correct AppSettings key and handles a null value therein, correct?
If that's the case, you're in luck; you don't need an app.config or web.config at all, you can set the values you need as part of your test setup.
For example:
[TestMethod]
public void Test_Configuration_Used_Correctly()
{
ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigValue");
}
[TestMethod]
public void Test_Configuration_Defaults_Used_Correctly()
{
// you don't need to set AppSettings for a non-existent value...
// ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigDefaultValue");
}
I believe you only have access to the webconfig file while your application is actually beeing started up. The solution is rather easy -> "Fake" your config. Use a NameValueCollection and use that instead:
private static NameValueCollection CreateConfig()
{
NameValueCollection config = new NameValueCollection();
config.Add("applicationName", "TestApp");
config.Add("enablePasswordReset", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("maxInvalidPasswordAttempts", "5");
config.Add("minRequiredNonalphanumericCharacters", "2");
config.Add("minRequiredPasswordLength", "6");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("requiresUniqueEmail", "true");
config.Add("passwordAttemptWindow", "10");
return config;
}
Now you could easily pass that collection into your class that parses data from it.
You should be able to use the ConfigurationManager.GetSection() method to pull out whatever you want.
Actually, if you are using NUnit, you can stick that in an App.config in your test project.
Then add this line to your Post-build event:
copy /Y “$(ProjectDir)App.config” “$(TargetDir)$(TargetFileName).config”
When you create the new provider in your tests, NUnit will pass the values in your app.config to the provider in the initialize method.
Why not just stick it in the web.config file?

Categories