I am having two projects one is basically a Windows service and second is class project in which I am doing my business processing. My App.config file is in Windows service project and in my Class project I am using below
ConfigurationManager.RefreshSection("appsettings");
string scheduledTime = ConfigurationManager.AppSettings["ScheduleTime"];
this setting is in my appsettings section of config file
I am using RefreshSection and also updating my app.config value in windows service project but its not getting updated at run time in my class project.
What is the catch in this ?
I'm having a little trouble myself with something similar, however I did come across something for AppSettings. Give this a shot:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
I think appsettings should be appSettings
If you want to get latest value use this code:
var appSettings = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
var mySetting = appSettings.Settings["keyOfSetting"].Value;
remember every time you need latest value, must use two line of code in same place!
Related
I have simple console application. In application there is app.config and i have defined few settings which i fetch using ConfigurationManager class like below
var setting = ConfigurationManager.AppSettings[key]
This works ok when i am debugging on local env. Now when i deploy this code to develepment server then it reads setting from dll.config instead of app.config.
I tried to google but i am not able to find any clue.
Is it possible to change behaviour to read from app.config always? The reason i am asking is because i have added transformation for app.config. So for Dev server its called app.DevServer.config and it has some specific settings.
Yes, you can manually read your app.config file with code like this:
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "app.DevServer.config" };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None, true);
var setting = config.AppSettings.Settings[key];
I have a number of projects that need to access settings, database connection, web api url, authentication server url etc, that will change depending on its deployment.
The application could be deployed multiple times to different departments, each with distinct databases and webservers.
Initially I was using appSettings and exposing them as properties. This appeared to work in development through the ide (Visual Studio 2013).
I followed suggestions here in order to get the location correctly and it seemed to work.
So Initially I had:
private static KeyValueConfigurationCollection GetAppSettings()
{
// The dllPath can't just use Assembly.GetExecutingAssembly().Location as ASP.NET doesn't copy the config to shadow copy path
var dllPath = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
var dllConfig = ConfigurationManager.OpenExeConfiguration(dllPath);
// Get the appSettings section
var appSettings = (AppSettingsSection)dllConfig.GetSection("appSettings");
return appSettings.Settings;
}
public string AknowledgeSTSOrigin
{
get
{
string setting;
if (_aknowledgeSTSOrigin != null)
{
setting = _aknowledgeSTSOrigin;
}
else
{
if (System.Diagnostics.Debugger.IsAttached)
{
setting = "https://localhost:44333";
}
else
{
var settings = GetAppSettings();
if (settings.Count > 0)
{
setting = settings["AknowledgeSTSOrigin"].Value;
}
else
{
setting = System.Configuration.ConfigurationManager.AppSettings["AknowledgeSTSOrigin"];
}
}
_aknowledgeSTSOrigin =setting;
}
return setting;
}
}
AT some point it stopped working - but unfortunately I've no idea when or why because I was running in the ide so it was always defaulting to the debugger attached condition.
The problem at this point was that all the above routes were returning null from appSettings.
When searching for the problem, I found that it's now recommended to use the project properties. I did so - a new ApplicationSettings section appeared in app.config and the properties were found.
So the above got simplified to:
setting = Properties.Settings.Default.AknowledgeSTSOrigin;
This worked great, I set the values to localhost to test running in ide - all good. I compiled and Published the app, then tried to change app.config on the server. It still wouldn't work on the server. But if I changed app.config on my machine to have the server settings, rebuilt and published it, it then works.
So it appears that this method gets the properties from app.config at compile time.
What I want to do is to be able to get them from config file at runtime. So build the app once, deploy multiple times and then just update the config with deployment specific settings.
I've tried googling this and checking SO, but not finding anything useful.
tried adding
Properties.Settings.Default.Reload();
as per this post but not working.
Target Framework = .Net 4.5 and its a class library. The error message shows that its still getting the value from the config file at compile time. (Error message not relevant as if it had the correct path there wouldn't be an error)
EDIt:
getting even more confused now. Found the following post which mentioned that the default is for the properties to be compiled unless you set GenerateDefaultValueInCode to false. I've done this and I'm now back to the same result as it returning null for the properties. And for some reason, despite setting the value to false for all the properties they are still visible embedded within the dll.
Found It!
The problem was occurring in a class library.
Although I create the settings in the class library and the settings get added to the app.config, it doesn't actually look there to retrieve them. Instead it's the web.config of the parent consuming the class library.
I put the settings in web.config and it appears to work.
I want to make a library that will be used by either an exe (app.config) or a website (web.config). If I create a custom configuration section, and load it using
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
CustomSection section = config.Sections.OfType<CustomSection>().FirstOrDefault();
it won't run on web site. It throws a exePath must be specified when not running inside a stand alone exe. exception, since it's not an exe. I can use something like:
CustomSection db = (CustomSection )ConfigurationSettings.GetConfig("CustomSection");
But that relies on the section being properly named. Is there a way to get all the sections and iterate through them?
I am needing to find away to write to another programs app.config file.
we have a 3rd party application that gets some values from an AppSettings section in its own config. but the only way we can get to change the value is when we call the application and once it runs it does a function which we don't want it to do if it doesn't have the correct values.
We need to encrypt one of the values so what we were think of was creating an application that would save the values in this 3rd party app.config.
saving the values and the encryption aren't a problem its doing it in another applications config file.
Is there a way to set which config file we use or a config path setting?
Regards
Aidan
Thank you for the help with this, I managed to get it done through this code.
string configLocation = string.Format("{0}\\APP.exe.config", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configLocation;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
txtEndpoint.Text = config.AppSettings.Settings["ENDPOINT"].Value;
This now allows me to write out the set config file values in the appsettings.
Cheers All.
Aidan
I have an application that encrypts a section in the configuration file. In the first time that I try to read the encrypted section from the config file I get an error message: "Unrecognized attribute 'configProtectionProvider'. Note that attribute names are case-sensitive. "
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the section in the file.
ConfigurationSection section = config.GetSection("EncryptedSection");
if (section != null)
{
// Protect the section.
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave = true;
// Save the change.
config.Save(ConfigurationSaveMode.Modified);
}
ConfigurationManager.RefreshSection("EncryptedSection");
Properties.Settings.Default.Reset();
//This is the part where I read the encrypted section:
ConfigurationManager.RefreshSection("EncryptedSection");
System.Collections.IDictionary HSMMasterKeyConfig = (System.Collections.IDictionary)System.Configuration.ConfigurationManager.GetSection("EncryptedSection");
This only happens in the first time that I try to read the encrypted section. I have noticed that the .config file is getting updated immediately after the first save but from some reason I need to restart the application in order to use the encrypted section.
Have you read through this...
http://bytes.com/groups/net/521818-configurationerrorexception-when-reading-protected-config-section
... as it appears to be a conversation involving an MSFT support engineer that directly maps to your situation.
The best way to do this will be to encrypt the app.config sections during installation only. Add an installer class to your project and override the Install method in the class. In this method you should perform the Encryption. You must call base.Install at the end of your overridden Install method. In the Setup Project goto Custom Actions and locate the Install custom action to be pointed with Your Project output [exe or assembly] which contains the definition of your Installer class implementation. This way it will Encrypt your app.Config sections during an installation straight and you will not face this problem. The application will automatically use DPAPI provider to read/write through sections or settings.
For your reference the issue was that the process that was trying to encrypt the config section didn't have admin rights. I added this process to the administrators group and that solved it.
I just ran into the same problem today. Normally, whenever I start an application where the config is in encrypted I always check the config on startup to determine if it's protected. If not the it I follow the standard SectionInformation.ProtectSection method. This is always my first step but today for some reason I decided to reference something from the config before I performed my protection check and got the "Unrecognized attribute 'configProtectionProvider'. Note that attribute names are case-sensitive. " error. All you have to do is run protection code before you reference the config within your normal code and you will no longer have the error.
Try running your Exe in seperate Application Domain. Once your application is loaded in the new AppDomain, check if the Sections are encrypted or not. If not then Encrypt the section and trigger the AppDomain to unload and reload with your executable again.