reading from app.config file - c#

I am trying to read StartingMonthColumn and CategoryHeadingColumn
from the below app.config file using the code
ConfigurationSettings.AppSettings["StartingMonthColumn"]
but it is returning null, also ConfigurationSettings.AppSettings.Count returns zero
Please help me to read this in my windows application
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CTARepository.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<CTARepository.Properties.Settings>
<setting name="Setting" serializeAs="String">
<value />
</setting>
</CTARepository.Properties.Settings>
</userSettings>
<appSettings>
<add key="StartingMonthColumn" value="7"/>
<add key="CategoryHeadingColumn" value="1"/>
</appSettings>
</configuration>

ConfigurationSettings.AppSettings is obsolete, you should use ConfigurationManager.AppSettings instead (you will need to add a reference to System.Configuration)
int value = Int32.Parse(ConfigurationManager.AppSettings["StartingMonthColumn"]);
If you still have problems reading in your app settings then check that your app.config file is named correctly. Specifically, it should be named according to the executing assembly i.e. MyApp.exe.config, and should reside in the same directory as MyApp.exe.

Just for the future reference, you just need to add System.Configuration to your references library:

ConfigurationSettings.AppSettings is deprecated, see here:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx
That said, it should still work.
Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?
Try attaching a debugger and checking the following value:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
And then opening the configuration file and verifying the section is there as you expected.

Try:
string value = ConfigurationManager.AppSettings[key];
For more details check:
Reading Keys from App.Config

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:
Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]
Hope this helps

This:
Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);
works fine for me.
Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.
Also, be sure you set system.configuration.dll as a reference in your project or build script.

Try to rebuild your project - It copies the content of App.config to
"<YourProjectName.exe>.config" in the build library.

Also add the key "StartingMonthColumn" in App.config that you run application from, for example in the App.config of the test project.

Related

dynamically change web service url on a windows service using app.config

In my windows service I have 2 web references
My windows service only contains an app.config not a web.config
my app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyFirstWindowsService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
<applicationSettings>
<MyFirstWindowsService.Properties.Settings>
<setting name="MyFirstWindowsService_postDataToMapicsWC_XAXSSTRN"
serializeAs="String">
<value>http://TESTDEV/web/services/XAXSSTRN.XAXSSTRNHttpSoap11Endpoint/</value>
</setting>
<setting name="MyFirstWindowsService_com_goodmanmfg_testdev_GETITMINFO"
serializeAs="String">
<value>http://TESTDEV/web/services/GETITMINFO.GETITMINFOHttpSoap11Endpoint/</value>
</setting>
</MyFirstWindowsService.Properties.Settings>
</applicationSettings>
</configuration>
[![enter image description here][1]][1]
the problem is my web services when i click on them the URL field is still saying
"Web reference URL" http://PROD/web/services/XAXSSTRN.XAXSSTRNHttpSoap11Endpoint
[![enter image description here][2]][2]
what is the end goal? To release this windows service to dev and prod environments without having to rebuild the entire solution.
The ideal behavior is :
Build the latest code in dev mode (test it, if all test good then , step 2)
Provide an app.config file with prod urls to dropped inside the
folder
Release
As you can see what I am trying to avoid is the need of dropping the file manually changing those 2 web services , rebuilding the solution AND THEN releasing...
Classic ASP.NET apps get their configuration from a hierarchy of web.config values. Other apps (console applications, Windows Forms apps, WPF, Services, ...) get their configuration from a configuration file named [NameOfExe].exe.config (and occasionally from [NameOfAssembly].dll.config. That file is located in the same folder as the exe itself.
For example, if your service is MyWcfService.exe, you will very likely find a MyWcfService.exe.config file in the same folder (for example, in the bin/debug folder). Its contents should be the same as your app.config.
Visual Studio makes this all "just work" by creating an app.config file in your source folder and then, at build time, copying the contents of that file to the appropriately named [NameOfExe].exe.config file in the same folder as the EXE.
In the normal case, you might have one set of URLs (and perhaps other data) for your dev environment, another for QA, another for Integration Test and another for Prod. You can manage this through the use of configuration transforms.
I think this goes some way towards answering your questions. In summary
App.config files have nearly the same capabilities as web.config
files
App.config files get "compiled" to [NameOfExe].exe.config
files at build time and placed in the same folder at the EXE
Configuration transforms may help you out with managing your URLs
Your other choice is managing a set of [NameOfExe].exe.[Environment].config files and manually putting them in the right place.

XamlParse Exception in wpf [duplicate]

I'm currently creating a Login form and have this code:
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection connect = new OdbcConnection(connectionString))
{
connect.Open();
OdbcCommand cmd = new OdbcCommand("SELECT username, password FROM receptionist", connect);
OdbcDataReader reader = cmd.ExecuteReader();
if (username_login.Text == username && password_login.Text == password)
{
this.Hide();
MessageBox.Show("Invalid User", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
else
MessageBox.Show("Invalid User", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
connect.Close();
}
}
catch (OdbcException ex)
{
MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
But whenever I try to type in the username and password there is an error called "Configuration system failed to initialize". What kind of problem is this, and how could I solve this?
Make sure that your config file (web.config if web, or app.config if windows) in your project starts as:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="YourProjectName.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
</configuration>
Note that inside the configuration element, the first child must be the configSections element.
In the name property on section element, make sure you replace YourProjectName with your actual project's name.
It happened to me that I created a webservice in a class library project, then I copied (overwriting) the config file (in order to bring the endpoints configuration) to my windows app and I started to have the same problem. I had inadvertently removed configSections.
Delete old configuration files from c:\Users\username\AppData\Local\appname and c:\Users\username\AppData\Roaming\appname and then try to restart your application.
Sometimes the Error occurs because a windows create a duplicate in the
C:\Users\App Data\Local\"You App Name"...
Just delete this folder and done. try it.
If you've added your own custom configuration sections to your App.Config, make sure you have defined the section in the <configSections> element. I added the my config XML but forgot to declare the configuration section up top - which caused the exception "Configuration system failed to initialize" for me.
After a long search I realised, this exception has an inner exception that tells you exactly what is wrong with your config file
I had this same problem with an MSTest class: Marlon Grech in his article says "the element has to be defined as the first element in the App.config."
So make sure that is the first element in under the element. I had put AppSettings first.
If you have User scoped settings you may also have a user.config file somewhere in the [Userfolder]\AppData\Local\[ProjectName] folder.
If you later remove the User scoped settings the user.config will not automatically be removed, and it's presence may cause the same error message. Deleting the folder did the trick for me.
I know this has already been answered but I had exactly the same problem in my unit tests. I was tearing my hair out - adding an appSettings section, and then declaring the configuration section as per the answer. Finally found out that I had already declared an appSettings section further up my config file. Both sections pointed to my external settings file "appSettings.config" but the first appSettings element using the attribute file whilst the other used the attribute configSource. I know the question was about the connectionStrings. Sure enough, this happens if the appSettings element is the connectionStrings element being duplicated with different attributes.
Hopefully, this can provide someone else with the solution before they go down the path I did which leads to wasting an hour or two. sigh oh the life of us developers. We waste more hours some days debugging than we spend developing!
I started to get this problem after uninstalling Oracle Client Drivers and it removed my C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\machine.config!
Copying it from another computer resolved the problem.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="xyz" value="123" />
</appSettings>
</configuration>
Easy solution for .Net Core WinForms / WPF / .Net Standard Class Library projects
step 1: Install System.Configuration.ConfigurationManager by Nuget Manager
step 2: Add a new App.Config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Bodrum" value="Yalikavak" />
</appSettings>
</configuration>
step3: Get the value
string value = ConfigurationManager.AppSettings.Get("Bodrum");
// value is Yalikavak
If you are calling it from a Class Library then add the App.Config file on your Main Project.
Wow it took me forever to figure out this one. For some reason changing the attribute [assembly: AssemblyCompany("CompanyName")] at AssemblyInfo.cs made this error disappear. I was referencing a project that had a different value for the attribute [assembly: AssemblyCompany("CompanyName")]. I maked sure both projects had the same attribute value and it worked great!
Same problem with me I solved my problem by removing verion="v3.5" from App.config.
Before
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<supportedRuntime version="v3.5" />//Remove this
</configuration>
Solution
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
</configuration>
Here is how to use version on
MSDN Support Runtime Element
I solved the problem by using the below code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="YourProjectName.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="SPUserName" value="TestUser" />
<add key="SPPassword" value="UserPWD" />
</appSettings>
</configuration>
It is worth noting that if you add things like connection strings into the app.config, that if you add items outside of the defined config sections, that it will not immediately complain, but when you try and access it, that you may then get the above errors.
Collapse all major sections and make sure there are no items outside the defined ones. Obvious, when you have actually spotted it.
In my case the only solution was to add the reference to the System.Configuration in my Test project as well.
This is kinda dumb, but for me I fixed it by doing a get latest from source control on my code. I think there was some new configuration element that was added by someone else, and I needed to overwrite my configuration files. OP shows the error I had gotten, which wasn't really pointing me in the right direction.
I too faced the same problem, But accidentally i written the
without writting the ,the previous one should go inside this tags. thus the 'Configuration System Failed to Initialize' error was arising.
Hope it will help
In My case, I have two configsections in the app.config file. After deleting the one hiding in the code lines, the app works fine.
So for someone has the same issue, check if you have duplicate configsections first.
If you are dealing with an Azure WebJob - I had to remove the following after upgrading to the latest 4.6.1.
<compilation debug="true" targetFramework="4.6.1">
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</assemblies>
</compilation>
Hope this helps.
In my case, within my .edmx file I had run the 'Update Model From Database' command. This command added an unnecessary connection string to my app.config file. I deleted that connection string and all was good again.
Try to save the .config file as utf-8 if you have some "special" characters in there. That was the issue in my case of a console application.
As #Flash Gordon mentioned in his comment, you will need to define any custom tag (as a section) in your App.config file, under <configSections>. For example, you're working on a test automation project with SpecFlow & adding <specFlow> tag, then a simplest version of App.config will look like this:
I just had this and it was because I had a <configuration> element nested inside of a <configuration> element.
I restarted Visual studio and even the whole PC.
I cleaned the project, rebuild, and deleted bin file.
Nothing helped until i changed the configuration from x64 to x86.
It worked on x86 but when i changed it back it also worked!
I tried all of the solutions above trying to figure out why one of my unit tests were failing to pick up the configuration from an app.config file that is perfect.
I had 2 references to the same assembly like so:
Removing the (duplicate) reference in yellow fixed it for me.
I hope this works for someone else, it drove me nuts for a while.
If you have a custom section, you need to mention that under configSections right below configurations tag.
Please check your transform files, make sure you remove the unnecessary tags.only the section that are going to vary needs to be there in transform files. dont mention config section in the transform files if not needed. this would also cause the problem.
if you have any syntax error in machine.config, then also this error is expected.
I was also getting
'System.Configuration.ConfigurationErrorsException' in System.Configuration.dll
If you have windows check the slashes / I was working with a project from a guy working in linux, so he had inverted them.

Repeating Configuration across Referenced Assemblies

Let's say we have Assembly1 and Assembly2.
Assembly2 is a C# class library used by Assembly1.
Web and Service References are configured and stored in Asembly2/app.Config.
Moreover, the EF connection string(s) are in Assembly2/app.Config.
When I use Assembly2 in Assembly1, the Assembly2 config file is not used. In fact, in that scenario, only the Assembly1 configuration appears accessible through default means.
As a result, I have to copy the Assembly2 config contents into the Assembly1 config.
This has worked for me for many projects.
Is there another way? A better way?
It seems wrong to have repeating configuration data.
Do you have a recommendation or technique that works?
Thank you.
You need to apply changes to the config file of entry point exe assembly. Class library assembly (dll) config files are never used. They are made by Visual Studio so you could easily copy the settings to exe config files if needed.
Bellow is example of the config file for exe assembly that has both, settings from class library ClassLibrary1 and settings from the exe assembly MainAssembly. You can see that both connection strings are in one connectionStrings settings. However, if you need to set other settings, beside connection string, you need to add extra section.
If you are already using this technique, this is correct way to go. This technique is flexible. For example if you have more than one project having the same connection strings on one box, you could specify the connection strings in machine.config file. You can also override the settings in some projects if needed.
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<!--This section declaratrion pasted here from dll conifg file -->
<section name="ClassLibrary1.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
<!--This section declaratrion was here in the first place -->
<section name="MainAssembly.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<!--This connection string was here in the first place -->
<add name="MainAssembly.Properties.Settings.MainAssemblyConnectionString"
connectionString="MainConnectionStringValue" />
<!--This connection string pasted here from dll config file -->
<add name="ClassLibrary1.Properties.Settings.LibraryConnectionString"
connectionString="LibraryConnectionStringValue"
providerName="" />
</connectionStrings>
<applicationSettings>
<!--This settings section pasted here from dll config file -->
<ClassLibrary1.Properties.Settings>
<setting name="LibrarySetting"
serializeAs="String">
<value>LibrarySettingValue</value>
</setting>
</ClassLibrary1.Properties.Settings>
<!--This strings section was here in the first place -->
<MainAssembly.Properties.Settings>
<setting name="MainAssemblySetting"
serializeAs="String">
<value>MainSettingValue</value>
</setting>
</MainAssembly.Properties.Settings>
</applicationSettings>
</configuration>
A DLL (or another referenced assembly) is not meant to carry it's own app.config, but rather have everything configured by the caller. So everything should go into the app.config of the exe.
Consider for example a shared data access library that needs connection strings to the database. The library should be possible to use from a variety of applications with different connection requirements. Having the connection string tied strictly to the shared library wouldn't work, it has to be done at the client using the library.
It is possible to put systemwide settings that affect all applications running on a machine in the machine.config file, but use that approach with caution as it will affect all applications on the machine.

<userSettings> in app.config Could not find schema information for the element 'userSettings'

Hello when I try to add parameters to the settings table
I get multiple messages for each parameter I add.
e.g.:
Could not find schema information for
the element 'userSettings'
Could not find schema information for
the element 'setting'
Could not find schema information for
the attribute 'serializeAs'
In the app.config I get:
<project1.Properties.Settings>
<setting name="ccc" serializeAs="String">
<value>vvv</value>
</setting>
</project1.Properties.Settings>
I can use, edit and save this parameter, but the messages really annoy me.
I use the following schema (and selecting other like 20 and 30 did not help):
C:\Program Files (x86)\Microsoft Visual Studio 9.0\xml\Schemas\DotNetConfig.xsd
Any ideas?
edit:
following Hans post here is my configSections
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
I don't know what it is for and if I should change it - yet here it is :)
Thanks Asaf
Well, that doesn't look healthy. Note how it is not valid XML, the project... element is mismatched with RuthSiteManager...
Not sure how it got that way, you'll have to edit it into shape. I guess you want to rename "project1". Avoid editing the .config file by hand otherwise. And make sure you have the required <configSections> element as well.
I just had this same issue. The fix I came across was to do a 'Clean Solution' followed by a 'Rebuild Solution'. This seems to rebuild the files correctly.

How do I reference configuration information from within multiple class libraries?

I've got a bunch of DLL projects that I'm pulling into my application, each contains their own Settings.settings/app.config. When I compile the app and run for debugging, everything works just fine, but come deployment time I can't get my DLLs to read their own settings files.
I've been doing some reading and it has become apparent that there's a couple of methods to getting each dll to read its own configuration - one is to dedicate a .dll.config to the library and the other is to embed the dll's configuration in the process.exe.config.
I'm having significant issues trying to implement either and I wondered if anyone has any good docs on this - there appears to be a shortage on the Net.
I'd like a separate .dll.config for each of the libraries if possible, but in a pinch, getting each of my libraries to read their own section of the process.exe.config will do.
Can anyone point me in the right direction because I'm so close to rolling this application out but this stumbling block is causing me a significant headache.
Edit: When I merge the configuration files, I start getting TypeInitializer exceptions when I initialize objects withing my libraries. This is likely just me being retarded, but does someone have a working example of a merged config file and some basic demonstrative code for reading it from multiple assemblies?
What are the "significant issues" you encountered? I started with embedding the dll's config in the exe's config, which worked, but was cumbersome. I now have all the config stuff in one dll project. The only thing I needed to do to make that work (besides copying the settings over) was to change the Settings class to be public.
Here's an example of a merged app.config that works:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="SharedConfig.Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- Begin copy from library app.config -->
<section name="SharedConfig.Library.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- End copy from library app.config -->
</sectionGroup>
</configSections>
<applicationSettings>
<SharedConfig.Client.Properties.Settings>
<setting name="Bar" serializeAs="String">
<value>BarFromClient</value>
</setting>
</SharedConfig.Client.Properties.Settings>
<!-- Begin copy from library app.config -->
<SharedConfig.Library.Properties.Settings>
<setting name="Bar" serializeAs="String">
<value>BarFromLibrary</value>
</setting>
</SharedConfig.Library.Properties.Settings>
<!-- End copy from library app.config -->
</applicationSettings>
</configuration>
Have each class library define configuration settings in a custom ConfigurationSection.
Then add custom section handlers to your process.exe.config file.
This MSDN article is pretty comprehensive in its explanation, with examples in both VB and C#.
See If app.config for a DLL should be in the "main config"… what do we do with WCF References in DLLs?. The real answer is "copy and paste". That's unfortunately the general solution Microsoft had in mind. In some cases, the .NET 2.0 Settings mechanism can be used, as it bakes the default values into the DLL itself. At runtime, the DLL can then save updated settings - into the .exe.config.

Categories