Issue with a DLL reading a ConfigurationSection when called through Service Reference - c#

I have a project (A) referencing a Service (B) via. a Service Reference.
That Service (B) has a reference to a DLL (lets call it Business.dll)
That DLL has it's own accommodating app.config which has some configuration that I would assume would be easily read whether being called internally (as a console app) or externally from Service (B).
Currently, this isn't working. The app.config (or, more specifically, the Business.dll.config file) is not being read at all, and:
(BusinessConfigurationSection)ConfigurationManager.GetSection("GroupName/SectionName");
is always null when called from project (A). Can I not save the Business.dll.config within the bin directory of Service (B), or am I doing something that simply is not possible? Is there a better way that I should be doing this?
Thanks.

You can load a specific config file like this :
Configuration config;
ExeConfigurationFileMap ecfm = new ExeConfigurationFileMap();
ecfm.ExeConfigFilename = <your_config_file_path>;
config = ConfigurationManager.OpenMappedExeConfiguration(ecfm, ConfigurationUserLevel.None);
var mySection = (BusinessConfigurationSection)config.GetSection("GroupName/SectionName");

When you call from Project A, ConfigurationManager will always read from the ProjectA's App.config not from the DLLs
You can use following code to open DLL config,
// Get the configuration file. The file name has
// this format appname.exe.config.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(dllPath); //dll config

Related

Not able to access app.config in class library with window service

I have folder structure as below
ConsoleApp
app.config
WindowService
service
app.config
DataLayer
I need to get app.config data such as connection string in DataLayer.I am not able to get. It throws null reference. In consoleApp and WindowService project, its is working.
please suggest me how to resolve this issue.
By default .NET application uses it's own app.config file when you access it via ConfigurationManager. In order to open another project's configuration you have to load it manually.
The following code snippet opens an external app.config located under the data layer project and accesses the ConnectionStrings section of that file:
var map = new ExeConfigurationFileMap() { ExeConfigFilename = #"path\to\datalayer\app.config" };
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var connectionString = config.ConnectionStrings.ConnectionStrings["myDBConn"];

Excel Add-In not loading app.config with service reference config information

I've written an app with a service reference to make web services calls to a specific URL and it works great. I want to move this code into an Excel Add-In, but I run into this problem:
Unhandled Exception Message: Could not find endpoint element with name 'ConnectivityHttpsSoap12Endpoint' and contract 'Connectivity.ConnectivityPortType' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.
The problem is that my app.config (w/the service reference info) isn't being loaded because Excel is calling my class library, and the app.config of the calling application would need to have the service reference added to it. But can that be done with Excel? Better yet, is there a way to just load my app.config from code?
You would need to open it using the ConfigurationManager. You can find your app.config file in the calling assembly path (usually), so you could write a method like this:
public static Configuration LoadLocalConfigurationFile(string fileName)
{
// fileName is the configuration file you want to open
var configMap = new ExeConfigurationFileMap
{
ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName)
};
return ConfigurationManager.OpenMappedExeConfiguration(
configMap, ConfigurationUserLevel.None);
}
I have had the same problem recently myself and found that the best solution was contained in:
Change default app.config at runtime
pointing your config file at:
AppDomain.CurrentDomain.BaseDirectory + "AssemblyName.dll.config"
where AssemblyName is the name of your addin assembly
As #hexboy noted in his comment, the answer is that ExcelDNA requires the config file to be the same name as the "xll" file but with a ".config" extension. Then ExcelDNA will load the configuration automatically and no further code is required.
Note also that ExcelDNA produces various different files on build. E.g. addin.xll, addin-packed.xll, addin64.xll, addin64-packed.xll where the project assembly is named addin.
In order for a config file to be picked up, it needs to match the file name that is used for the add-in. E.g. addin-packed.xll.config if using addin-packed.xll as the registered Excel add-in.

How to use app config of an imported C# project

I'm using Visual Studio 2010 And C# 4.0. I have a project that exposes an interface to a webservice. It has an app.config that defines the bindings for the webservice. I want to expose this project as a library for other clients to use.
However, when I try to import this library project in a client project (say a console application), I get an error because it couldn't find any configuration file associated with the webservice.
Is there a way to use the app.config inside my library project, so that my clients can use it without having to define a config file of their own?
How about you change the library project a little bit:
Change the app.config in the library project build action to "Embedded Resource".
Change the code when reading config, check if config exist, if not extract the app.config from Embedded Resource to current folder and then use something like ConfigurationManager.OpenMappedExeConfiguration to read it.
After that any project use this library should be able to not worry about those settings.
First create a utility function like below. This function should be in a library or class which could be called from your web service (and of course your main project). Better to add reference to this library in your web service.
public static string GetAppConfigValue(string key)
{
return ConfigurationManager.AppSettings[key] ?? GetAppConfigValue(GetAppConfigFileName(), key);
}
private static string GetAppConfigValue(string appConfigFileName, string key)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = appConfigFileName;
Configuration appConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
return appConfig.AppSettings.Settings[key].Value;
}
Now if you can call GetAppConfigValue(string) from your main project, it returns the value of the cached app.config since it is its own configuration file. You can also call the public function from web service project when it would return the mapped configuration settings. The tricky part here is to properly supply the full path of the config file!

Multiple App.Config Files in .NET Class library project

I am creating one class library project.
Now by default I have one App.Config file so that I am putting all environment specific data in that Config file.
Now based on the Environment (whether Dev / Test / Production), I am planning to have three App.Config files in VS 2010 such as
App.Dev.Config
App.Test.Config
App.Prod.Config
Wondering how would the application know which config file to use.
Anyone implemented this scenario. Any Code samples / Articles would be helpful.
Thanks
The app will use the config file named YourExcecutable.exe.config which is by default the file App.config included in your (executable) project.
Note, that .NET only loads one config file for the whole application. You cannot use multiple configuration files (i.e. one per library project) without coding.
Option: You can use postbuild events and different solution configurations to copy one or another App.Config file to the output folder
Option: You can use the ConfigurationManager Class to load an alternate config file by code.
Loading a different application configuration file at run time can be done using the concept of mapped configuration file. To start with, you need to add reference to System.Configuration.dll in your project.
Set the value of Copy to Output Directory property to Copy if newer (Refer screenshot). This has to be done only for non-default configuration files e.g. App1.config, App2.config, etc. Leave the default configuration file namely App.config as it is . Due to this change, all the non-default application configuration files will be available in the project output directory (\bin\debug) when the project is built. Default value of this property is Do not copy.
Here is the code snippet on how to read configuration data from non-default configuration files:
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "App1.config"; // app1.config should be present in root directory from where application exe is kicked off
// Get the mapped configuration file
var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
//get the relevant section from the config object
AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
//get key value pair
var keyValueConfigElement = section.Settings["appSettingsKey"];
var appSettingsValue = keyValueConfigElement.Value;
If you have multiple application (aka app) configuration files then you can keep a setting in default App.config file with the help of which you can make a decision at run time about which non-default configuration file to load e.g. App1.config
Note: Now look at below code:
ConfigurationManager.AppSettings["DeployEnv"]
This code will still read the data from the default App.config file. This behavior can't be changed. There is no way to prohibit the Loading of default App.config file. You have to use alternate means as discussed in this post to read the data from non-default configuration files
Now there is an even better solution: SlowCheetah - XML Transforms

Wrong App.config being loaded

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.

Categories

Resources