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

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"];

Related

Unable to add behaviorExtension in machine.config via c#

My BizTalk application requires me to add a custom behaviorExtension to my machine.config file. I install my application via MSI, via BizTalk Deployment Framework (BTDF), so I would like this to be done programmatically as well.
Now I cannot seem to find a way to either list installed behaviors not edit them.
I have the following code, but after that I'm stuck.
// Get the machine.config file.
Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();
// Get the machine.config file path.
ConfigurationFileMap configFile = new ConfigurationFileMap(machineConfig.FilePath);
// Map the application configuration file to the machine
// configuration file.
Configuration config = ConfigurationManager.OpenMappedMachineConfiguration(configFile);
ConfigurationSectionGroup svcModel = config.SectionGroups.Get("system.serviceModel");
ConfigurationSection extensions = svcModel.Sections.Get("extensions");
Can anyone give me some pointers on how to approach this?
You are almost there. Your extensions variable is of type System.ServiceModel.Configuration.ExtensionsSection, which has property BehaviorExtensions containing what you are looking for. So:
var extensions = (System.ServiceModel.Configuration.ExtensionsSection) svcModel.Sections.Get("extensions");
var behaviors = extensions.BehaviorExtensions;

Read web.config from library consumed by the webapplicaion deployed using IIS

I have a web application deployed on IIS. This web application is consuming a library which wants to access the Web.config.
Example :
Foo.dll is the web application deployed on IIS
Foo.Utility.dll is consumed by Foo.dll
There is a piece of code in Foo.Utility namepsace which wants to access the web.config from Foo application and read the config values
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
string cacheDir = config.AppSettings.Settings["abc"].Value;
Currently config.FilePath = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
Changed my code to :
Configuration config = WebConfigurationManager.OpenWebConfiguration(Assembly.GetCallingAssembly().Location);
string cacheDir = config.AppSettings.Settings["abc"].Value;
Now my Assembly.GetCallingAssembly().Location is : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\62f5c902\849205ff\assembly\dl3\c28d4647\10e128d3_7449d001\foo.dll
Can someone help me to understand how to read the web.config from the place where my application is deployed using IIS?
For more information or if the question is not clear then comment below. Will update it
You have to use ConfigurationManager from System.Configuration. First, you'll have to add a reference to System.Configuration.dll assembly, and then use it like this:
using System.Configuration;
...
string valueOfAbc = ConfigurationManager.AppSettings["abc"];
ConfigurationManager will read the config file from the application's host. In your case, the web.config file.
Reference:
ConfigurationManager Class
Application Configuration Files

Issue with a DLL reading a ConfigurationSection when called through Service Reference

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

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!

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