.NET ConfigurationSettings.AppSettings("TheDB") - c#

I'm looking at a custom built .NET control (vb). It has a public string declared as:
Public Shared strConn As String = ConfigurationSettings.AppSettings("TheDB")
I'm trying to find out what "TheDB" is supposed to be exactly.
I looked the web.config file of the website using this custom control, but there is no "TheDB" parameter anywhere. I also looked in the web server's machine.config file, and again, no "TheDB" parameters there either.
Help.

If it's missing, just add it:
<appSettings>
<add key="TheDB" value="somevalue" />
</appSettings>
(assuming that ConfigurationSettings.AppSettings really corresponds to appSettings section of the web.config. This is not clear as normally you refer to standard sections of configuration files using builtin ConfigurationManager class)

Look in your web.config. Somewhere in there is a section called "AppSettings", where there should be some elements that look like this:
<add key="TheDB" value="something" />
One of them will be yours. Or possibly somebody took it out. More than likely, though, it's the connection string to your database.

web.config is hierarchical. Each web.config supplies configuration information to the directory in which it is located and to the entire directory hierarchy beneath it.
http://msdn.microsoft.com/en-us/library/ms178685.aspx
Been that way since .Net v1.1. When you look for a configuration value or section, the .Net configuration system looks in the lowest level web.config. If the desired value is not found, it runs up the directory tree until it finds it.
You need to run up the directory hierarchy (and yes, that includes virtual directories mounted in IIS as well) until you find the web.config file containing the desired appsetting value. There is also the IIS ApplicationHost.config as well, located at
%windir%\system32\inetsrv\config

Related

How to specify a config file with path?

I would like to setup one web.config file for my solution. How do I specify the path of the config file I am using?
Here is how you can specify new app setting in your web.config file.
<appSettings>
<add key="LoggingDir" value="C:\\Logs\\"/>
<add key="environment" value="test"/>
<add key="smtp.server" value="incoming.ABank.com"/>
</appSettings>
And you can access in your code by
private static String logDirectory = ConfigurationManager.AppSettings["LoggingDir"].ToString();
private static String MailServer= ConfigurationManager.AppSettings["smtp.server"].ToString();
I prefer all my app or environmental settings in a separate file when I have lot of them. You can do that by
<appSettings configSource="env\ApplicationSettings.config"/>
and then write above <appSettings> </appSettings> section in ApplicationSettings.config file.
If you're creating an MVC application, then generally you can access your configuration file (web.config, in the root of the project) using ConfigurationManager:
string sConnectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
You could try loading a different configuration file using:
ConfigurationManager.OpenExeConfiguration()
Here's a link to the MSDN documentation for the ConfigurationManager class:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx - specifically, there's some information included there about the class's intended usage and operation.
Hope that helps,
Cheers!
Not knowing what your projets look like I'm going to go out on a limb here.
Just an FYI, in IIS there will be inheritance that may solve your issues, just be sure to setup your apps for debugging in IIS in the same folder structure.
If you have multiple libraries, you dont need config files for those libs (app.config), so what are you trying to to do eliminate multiple config files? Do you have multiple web sites? If you only have a single site and other class library projects, you won't beed other config files as they won't be used at runtime anyways. If you have multiple web sites, then consider inheritance.
10 things asp.net developers should know about web.config inheritance and overrides

What is the best way to store/set configuration settings for a C# application?

I have some values that I want to be able to set, and the application to load them from some kind of file.
The only concept I can think of, is a simple txt file, that might have the following lines:
DatabaseName = "DB1/test"
DatabasePassword = "password"
Development = "true"
but im thinking it should be in some kind of config file? Plus reading a txt file for these values isnt exactly tidy code. It would be nice if i could get the database name by just saying in my application:
configfile.DatabaseName
Thanks,
Paul
You really should be using the built in Application Settings
You can directly access simple settings using the ConfigurationManager
ConfigurationManager.AppSettings["MySetting"] = "SomeStuff";
var mySetting = ConfigurationManager.AppSettings["MySetting"];
There is also direct access to your Connection Strings using the ConfigurationManager
var conn = ConfigurationManager.ConnectionStrings["DevSqlServer"];
All this is stored in XML files, and by default your *.config files.
To Answer Doomsknight's question from the comments
Configuration settings can be done a number of ways, but by default, they are stored in two places.
Application Level Settings are stored in a configuration file.
For executable programs this file is located in the same directory as the .exe and is named after the assembly, or executable.
Example: MyAssembly.config, Another.Assembly.config
For web applications, the settings are stored in the web.config file (usually) located in the root directory of the web application. These are applied hierarchically and one can be located at each directory level of the Web Application.
Example: MySite\web.config, MySite\SubDirectory\web.config
User Scoped Settings are stored in the user profile
Example: C:\Documents and Settings\USERNAME\Local Settings\Application Data\ApplicationName
Connection Strings are stored in the <connectionStrings></connectionStrings> section in your config file.
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
These settings can easily be modified directly in the config file, but without writing some code to automatically refresh sections of the config file (which is possible), an application restart is typically needed.
I hope this helps out.
.NET has a configuration platform built into it. Just add an app.config file to your project and use the ConfigurationManager library to access the values.

Determining which config file a setting originated from?

I am trying to find a way to determine the location of the config file that holds a specific appsetting or connection string value. i.e. I have multiple web sites/apps on an IIS server and I would like to determine if a setting is coming from the app's config, the parent app's config or the machine.config.
Any idea?
TIA
J
There is no way to do that using System.Configuration because it was designed to be indiscriminate. If you must do what you are trying to do, you will want to manually parse the potential files, those being the app.config/web.config, application.exe.config, and machine.config.
Note: I see you are using .NET 4.0. Note that 4.0 uses application.exe.config instead of the older app.config or web.config, where application is your actual EXE file's name, to read its settings after the product has been installed through a setup.

How to read values from App.config in .Net 4.0 using configurationManager?

I am creating a windows service in .Net 4.0 and testing some functions of said service with a windows forms client by referencing the service project.
The service project has an App.config file and that file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="myLocalMySQLDBUsername" connectionString="username"/>
</connectionStrings>
</configuration>
When a function belonging to the service calls:
ConfigurationManager.ConnectionStrings("myLocalMySQLDBUsername").ConnectionString
a null reference error is thrown because my connection string is not loaded. The only connectionStrings that are loaded are from the machine.config file located in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
If I create an application scope setting for the service, I can get that setting by using the My.Settings.setting -> so it's not like the App.config file is not being read.
My question is: why are my connectionStrings not being loaded from the App.config file?
Thank you for your help.
UPDATE:
Also, at this point, even a work around would be appreciated; the only reason for using app.config is to be able to encrypt the contents using the DpapiProtectedConfigurationProvider (the contents will have some username/password values for service and database connections).
I tried creating an AppSettings section manually in the app.config but those settings were also not read by the configurationManager (count = 0).
UPDATE 2:
Per a suggestion, I tried to manually open the app.config file like so:
Dim exePath As String = System.IO.Path.Combine(Environment.CurrentDirectory, "ServiceName.exe")
Dim myConfig As Configuration = ConfigurationManager.OpenExeConfiguration(exePath)
So here is the weird part, when I look inside, path is correct (points to my app.config) but the connectionStrings are still being loaded from the machine.config file (my connectionStrings are not loaded)!! ARGH
UPDATE 3:
Okay, so, I figured it out. When referencing a project(parent) from another project(child), the child's app.config is used even if the parent's classes are being used. Thus, I can get the connectionStrings to show up if I copy them over to the child's app.config. When trying to open it manually, my currentDirectory was of the child, not the parent (strange how it did not throw an exception - it wouldn't have been able to find the config file ... it just silently used the machine.config ... oh well).
Thanks all for the help!
The first thing you'll want to do is make sure that the service account has access to the file (if not running as SYSTEM). It sounds like it should be ok though since you mention My.Settings.Setting works.
The other thing to look out for is to make sure that the app.config has the name of the service executable in it - so if the service exe is MyService.exe the app.config must be named MyService.exe.config.
The last thing to make note of: libraries will read from the executable's app.config that loads the library, not the app.config that is with the library. So if you have a project for the service executable MyService and a project for the library MyServiceLibrary the code in the library will read the app.config from MyService not MyServiceLibrary.
I saw some people say this problem might be fixed by manually re-adding a reference to System.Configuration.dll
SIDE NOTE: If that really is you whole app.config file and not just a snippet then that is your problem... you're app.config file should be MUCH more complicated or .NET will not be able to load it.
WORK AROUND: Use the configuration manager to open this config file (there is an API for that.) You can't get it to load auto-magically just tell the config manager to open it.
I still think the problem is your config file is invalid -- could you please post the FULL file?
Make sure the config file is deployed to the same folder as the executable file, and that it's called your.assembly.exe.config.
I had a similar problem, but in my case it was because I had changed the project's namespace. This is also used as the application settings section element name in the config file, so the code was not finding the new section name. Fiddling with one of the custom setting's values in the project properties and rebuilding caused the new section to written into the app.config alongside the old ones which was what indicated the issue to me.

Can we share some contents of App.config between projects?

I have two independent projects in my Visual Studio 2008 solution. Both has its own App.config. But in one project, I need one or two properties defined in another project's App.config. Is it possible to share part of the App.config contents from other project?
Yes - of course. Any configuration section can be "externalized" - e.g.:
<appSettings configSource="AppSettings.DEV.config" />
<connectionStrings configSource="MyConnection.config" />
or
<system.net>
<mailSettings>
<smtp configSource="smtp.TEST.config" />
vs.
<system.net>
<mailSettings>
<smtp configSource="smtp.PROD.config" />
Any configuration section can be put into a separate file that can be shared between projects - but no configuration section groups, and unfortunately, it's sometimes a bit tricky to know which is which.
Also, in some cases, Visual Studio will complain (using red wavy underlines) that the "configSource" supposedly isn't valid - but it is - it's defined on the ConfigurationSection object in the .NET config system.
UPDATE:
another feature that hardly enough developers seem to know and use is the ability in Visual Studio to add existing files from a different project as a link:
With this, you can add links to files into your local project, and they'll always be kept up to date. Great productivity booster if you need to do some file-level sharing (like for common configuration files or such)!
Try this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="PROD.config">
<add key="common.Currency" value="GBP" />
</appSettings>
</configuration>
Only the "running" app.config is used, but you can go external like marc_s says.
You can also create a .Settings file that's "shared". Go to the "shared" project properties, the Settings tab on the left, create a setting with Application scope, and set the Access Modifier on top to Public. In your other project you can then use ClassLibrary1.Properties.Settings.Default.SettingName to access it. It will be strongly typed, but you may need it at compile time.
Something I like to do, especially when trying to coordinate ServiceModel elements between libraries and tests is to use configSource to fragment the config in the target library and simply link/copy always the fragments in my test projects.
That way I only maintain in one location.
You could take it one step farther and simply have a common directory in the solution and link the fragments in all projects.
In that situation, I would think using a Database to store some configuration data would be ideal. Each app does its own thing, but they look to a shared database to get those common pieces of information.
EDIT: I spoke too soon! Looks like both the OP and I learned something about config files =D

Categories