We have a Visual Studio 2010 solution that contains several C# projects in accordance with Jeffery Palermo's Onion Architecture pattern (http://jeffreypalermo.com/blog/the-onion-architecture-part-1/). We have a UI project that is an ASP.Net MVC project, and we have a C# Class Library project called Infrastructure that is referenced by the UI project. In our Infrastructure project we have added an app.config file to contain settings that are specific to the Infrastructure project. At runtime, the app.config file doesn't appear to be available to the Infrastructure project, only the web.config file contained in the UI project. We don't want to put settings that pertain to the Infrastructure project into the web.config file in the UI project, the UI has no need for those settings. How can we make the Infrastructure's app.config file available at runtime? We were thinking maybe we should put a Post Build Copy to copy the app.config out to the UI directory when the application is built - is that the right way to do this, or is there a better way?
Generally, you'll be told that this can't be done. However, you can certainly load a config file using the System.Configuration.ConfigurationManager.OpenExeConfiguration method. You can pass in the file path to your assembly (it doesn't have to be an executable, despite the method name).
Granted, this doesn't merge your assembly's config settings into the executing application's config settings, and I don't think that it should. Your assembly just has to know that it needs to retrieve its settings through a different mechanism than the System.Configuration.ConfigurationManager.GetSection function or the static AppSettings property on that class.
Below is a very simple example for a "Settings" class that loads a .config file for the assembly of which it is a part.
public static class Settings
{
public static System.Configuration.Configuration Configuration { get; private set; }
static Settings()
{
// load a .config file for this assembly
var assembly = typeof(Settings).Assembly;
Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(assembly.Location);
if (Configuration == null)
throw new System.Configuration.ConfigurationErrorsException(string.Format("Unable to load application configuration file for the assembly {0} at location {1}.", assembly.FullName, assembly.Location));
}
// This function is only provided to simplify access to appSettings in the config file, similar to the static System.Configuration.ConfigurationManager.AppSettings property
public static string GetAppSettingValue(string key)
{
// attempt to retrieve an appSetting value from this assembly's config file
var setting = Configuration.AppSettings.Settings[key];
if (setting != null)
return setting.Value;
else
return null;
}
}
And the usage...
public class UsageExample
{
void Usage()
{
string mySetting = Settings.GetAppSettingValue("MySetting");
var section = Settings.Configuration.GetSection("MySection");
}
}
Now, you'll still have to work out build issues. Adding an "Application Configuration File" (App.config) item to your class library assembly does cause Visual Studio to copy it to that assembly's output folder as .dll.config, but it is not automatically copied to the output folder of any executable applications that reference that project. Therefore, you'd need to add a post-build step to copy the file to the appropriate location, as you mentioned.
I'd consider having a post-build step on the class library that copies the .config file out to a solution-level "Configurations" folder, then have a post-build step for executable projects to copy everything from the "Configurations" folder to the output folder. I'm not sure if that would actually work well, but if it does then you wouldn't be creating additional dependencies between projects in your post-build steps (that might make maintenance difficult).
EDIT: Ultimately, you should consider whether this is really what you want to be doing. It isn't the normal approach, and generally you might be better served by utilizing the other answer to this question that mentions using the configSource attribute.
Drawbacks to this approach that may not be obvious are that you won't be able to put settings for third-party components into your class library's config file and expect them to be used. For instance, if your class library is using log4net, you can't put log4net's settings in your class library's config file, because the log4net components still expect to load settings from the executable's config file.
Even if you post-build-copy the app.config it will not solve your problem. The application is still a web app, so the config system will use the web.config file. The settings will need to go in there one way or another. One way to still keep those settings a bit separate is to put them into a custom config section, and then put the settings for this section into a separate file. It will still need to be referenced from the web.config though (using a configSource attribute).
Thank you Dr. Wily's Apprentice ! I've added the function for getting the connection string as well:
public static string GetConnectionStringValue(string key)
{
var setting = Configuration.ConnectionStrings.ConnectionStrings[key];
if (setting != null)
return setting.ConnectionString;
else
return null;
}
Related
Now I have seen this question before on SO in a variant ways, but surprisingly not in this form:
I have a solution with multiple web services (projects) that need to talk to each other. After publishing each of these web services might end up on a different machine with a different database. To tell each web service where all other web services are, I want to maintain a single config file during development.
I would like to expect that after publishing the config to be present in each published project. And I would like to expect the config file to be editable after publishing, so I can swiftly migrate a certain web service and then just edit all config files of the other web services.
I don't want to do this in the database, for the config file its self should also hold connection settings to the database(s).
I came across the following ideas/thoughts/questions:
I have a dll project called 'common' that is referenced by other projects. Let's give that one a shared.config and build a class in that project that can be used to read out the shared.config by doing System.Configuration.ConfigurationManager.OpenExeConfiguration("shared.config"). Just need to make sure the shared.config will be published along with the DLL.
I would favor this solution, as it would also let me keep a web.config inside each project having just the project specific settings. And have the shared.config having the shared settings. But I read on SO that this should not be considered lightly and could have some unwanted side-effects, like file-access-issues; though I wonder if this would apply to my case. Also I would like to ask your help here on how to actually realize this as I don't think Visual Studio supports app.config for DLL projects out of the box.
I also thought about creating a shared.config file in the Solution Items. Then linking that file inside each project. And in the Web.config of each projects, add: <appSettings configSource="shared.config" /> pointing to the linked file in that project.
Though I cannot find any reason why not to do this, first implementation failed. It seems (at least during development), c# cannot find the linked shared.config file. I'm guessing linking files is not done instantly nor maintained after creating the linked file, but the file is only copied to the projects WHEN I do a publish. Thus leaving the file missing during development. Is this correct?
The config files are app specific. This mean that you can add a config file to a class library but the file will then by used by the app (windows service, webservice and so on) referencing the library.
Same thing for external configSource, this are app specific as well and need to be included withing the project using it.
So if your solution is composed by 2 projects you then need 2 config files. One for each project.
While for a windows based application(services, winforms) the expected folder for config files is the bin directory, for web based projects this will be the directory is the root folder of the virtual directory.
This said, using a shared config file looks the easier solution (and you don't have to copy the app.config from the class library for each project). Here are the steps :
Create a solution folder.
Add the config file to it.
Add the file as a reference for each project needing it. Right click the project and Add existing item - > Choose the file and Add as link
Ensure the file is always copied by setting the copy option (properties of the file) with Copy Always.
At this point you should have the config file deployed into your project directory everytime you compile the solution.
EDIT:
I'd avoid looking into the bin for config files within a web app, the
convention is that file should be in the root, so I would avoid the
first option.
Linked files end up in the bin after building the project. Try the same steps for importing the file but this time simply add it (not as link) and it will be deployed as content in the root of your site, so it can be always available.
If your hosting in IIS it is possible to have a single web.config file at the root site level but Giorgio is right in that app.config files are app specific. it is possible to use custom build steps to automate the copying of config files across multiple projects so personally I would go with that.
This actually drove me a bit crazy. In the end I fixed it like this:
Created a Shared.config file in the dll project 'common', having the contents look like any ordinary web.config/app.config.
Set the file to be Content and Copy Always, so it would surely be copied out to all projects that reference project common. (Though the config file will indeed end up in the bin folder.
Created the class SharedConfiguration inside the common project. The really tricky part was having to use OpenMappedExeConfiguration() , and getting the path to the executable directory (including bin, and without file:// in front of it).
Now when I want to access a setting from the shared settings, I do SharedConfiguration.instance.AppSettings.Settings["CubilisEntryPointUrl"].Value.
(I cannot use SharedConfiguration.instance.AppSettings["CubilisEntryPointUrl"] directly because of this issue)
.
public static class SharedConfiguration
{
public static readonly Configuration instance = GetConfiguration("Shared.config");
private static Configuration GetConfiguration(string configFileName)
{
ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, configFileName);
return ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
}
}
I have searched for a while quite fruitlessly for a way to do this.
I am working on a project the has many parts, most of which i can not directly access, but it is extensible. So I have written a dll for it, but the problem is that I need to be able to supply some sort of settings/config that can be updated with out having to recompile the dll.
I don't have access to a main exe's app.config. and the settings/dll.config that vs2010 creates is not being picked up by the dll.
Is this actually possible? a standalone operational config file for a dll?
new update. - I have created a settings.settings file and the all successfully picks up the config data but it seems to bake it into the file when its compiled, when i edit the config after deployment it does not pick up the changes. I tried the first answer below and it didn't work.
thanks
Yes, using the System Configuration namespace you can create a ConfigurationSection which can be used to store any configuration properties you like:
public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("MyProperty")]
public string MyProperty
{
get { return (string)this["MyProperty"] }
set { this["MyProperty"] = value;
}
}
Then in your assembly project you can read your assembly specific configuration. If your assembly is called MyAssembly, then GetSection() will look for a configuration file called MyAssembly.dll.config:
var myConfig = (MyConfigurationSection)ConfigurationManager.GetSection("sectionName");
Console.WriteLine(myConfig.MyProperty);
I didn't try this specific example, but I have had to do this before. Hope this helps!
I'm trying to work with a settings.settings file in my project. There are values that need to be shared between the .exe file and various DLLs. I'd rather not just pass these values around, I'd like to access them when I need them but each project sets up its values with slightly different names and therefore aren't reachable by the other projects.
Is there any way to share the contents of the app.config file between an .exe and a .dll using the settings.settings approach? Or do I need to go back to using ConfigurationManager in order to do this?
Just put your settings in the App.config file, and read them from your dll. In fact I believe it's the only place your dll will look for settings/config, local config for the dll is ignored.
Here's a quick example to ensure the dll has no strong references to the application. This code isn't great but you get the idea.
private string GetSettingValue(string key)
{
string executingAssembly = Assembly.GetEntryAssembly().GetName().Name;
string sectionName = "applicationSettings/" + executingAssembly
+ ".Properties.Settings";
ClientSettingsSection section =
(ClientSettingsSection)ConfigurationManager.GetSection(sectionName);
// add null checking etc
SettingElement setting = section.Settings.Get(key);
return setting.Value.ValueXml.InnerText;
}
Alternatively have a common dll with the shared settings and take a dependency from each assembly that needs to share the config. This is far cleaner.
When I try and use code that makes use of the Enterprise Library Caching Block I get the following error:
The "cachingConfiguration" section is not available in the supplied configuration source.
The section is in my app.config file for that particular assembly though. If I copy the file into the unit test assembly that makes use of the afore mentioned code everything works. Is there any way that I can force it to use the app config that exists in the referenced library so I don't need to duplicate it in every assembly that makes use of it?
Yes.
Select an app.config file to be your master config file (a good choice would be the one in the project of the main application executable).
Now go to your other project (fx. the unit test project). Right-click and select Add Existing Item. Point to the master app.config file and add using the "As link" option:
Add as link http://blog.codevelop.dk/pics/AddAsLink.png
Now you only need to manage one app.config file, and the other projects will 'reference' this file.
Option 2: If you wan't to control what config file the Enterprise Library uses for caching configuration, use:
var fileSource = new FileConfigurationSource(configFilePath);
var factory = new CacheManagerFactory(fileSource);
ICacheManager manager = factory.CreateDefault();
The dll config file that you see in the IDE (if you are using the designer to add settings etc) is largely for convenience. The runtime won't look for it; it wants the file from yourexename.config. Some components provide the facility to specify a separate config file path - I don't know if this is the case for entlib.
Alternatively if you are spawning your own AppDomains you can specify the config file path. And finally some config sections can be referenced in from other files rather than using the file completely (see configSource here) - but in general (and especially for tests) it is easier to just copy the configuration section into the top-level app's config file (or the unit test's config file in this case).
I have a .NET 3.5 class library I built that reads an App.config file for values it needs. It can pull the config values just fine when I test it in Visual Studio. To test it, I just change the project to a console application and execute a method call.
I have the need to call this class library from many other .NET programs, and I want the class library to be self sufficient (I should be able to call it from any other program, and it should use its own config file, not know about any calling config file etc.).
I can add a reference to the dll (since I am still development I am using VS 2008, haven't thrown anything into the GAC yet) but the App.config that the class library is reading is from the calling program's App.config, not the class library's App.config.
The class library dll has it's config file in the same directory, so it should be able to find it just fine, and the calling application is named differently. I am using the standard key value pairs in the App.config (e.g. name of config file myClassLibrary.dll.config) and getting values out with the following line of code:
String myVal = ConfigurationSettings.AppSettings["myConfigSetting"];
Does anyone know how to fix this?
An app domain in C# can have only one assembly level app.config file. See here on MSDN. An executable will always start up an AppDomain and by default look for a config file with name: EXECUTABLE_NAME.config. For example, SampleApp01.exe will look for SampleApp01.exe.config as its configuration file.
you can place your configs in the machine.config file inside the framework folder by this way you can globally use your configuration in all .Net applications running in that machine,
I believe app.config will always be used by the executable. Just drop it in that directory.
They would do that to ensure the dll can be shared and not have to share the same .config file.
You might be able to create a link from the executable .config file
<appSettings configSource="\lib\app.config">
Or change its name, i don't understand how you can have both app.config files in the same directory..don't they have the same name?
<appSettings configSource="\lib.app.config">
I can't find a way to avoid getting the app.config for the calling dll/exe etc. The only way I have found is to use a hardcoded path and load it that way. Here is code I am using to do that:
using System.Configuration;
...
public static KeyValueConfigurationCollection getAppSettingsFromAppConfig(String appConfigPath) {
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = appConfigPath;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
AppSettingsSection section = config.AppSettings;
KeyValueConfigurationCollection appsettings = section.Settings;
return appsettings;
}
You then have a collection of KeyValueConfigurationElement, which you can use .Value to get the string from config file with.