Load custom serviceModel in C# - c#

In my C# program I load a custom app.config, using this code:
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = location };
Config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
In my app.config, there is also a section <system.serviceModel> with a service reference. This server reference is used like this:
var client = new MyClient();
However, this client is using the configuration of the original app.config, and not of the loaded configuration from the "Config".
How can I use a the serviceModel part from an external app.config?

Related

How to load external App.Config dynamically in C# Console application?

I have a console application and the App.Config is outside the appdomain, I want to load it programmatically(not with powershell). I already pass the path of the external App.Config as a command argument but I don't know how to load it in the appdomain once I run the application.
for load app config you can use below code:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var readerConnectionString = builder.Build().GetSection("Parameter")
.GetSection("DbConnectionRead").Value;
and this is a JSON sample:
{
"Parameter":
{
"DbConnectionRead": ""
}
}
I am not sure whether you can edit your App.Config from outside folder. Here is something I found about reading appsettings from App.Config outside of project folder.
static void Main(string[] args)
{
IntializeConfigurationFile();
var check = ConfigurationManager.AppSettings["conn"];
}
static void IntializeConfigurationFile()
{
//ConfigurationManager.RefreshSection("appSettings");
// Get the current configuration associated
// with the application.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Associate the auxiliary with the default
// configuration file.
System.Configuration.AppSettingsSection appSettings = config.AppSettings;
appSettings.File = "C:\\Personal\\Learning\\Docs\\App.config";
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload in memory of the
// changed section.
ConfigurationManager.RefreshSection("configuration");
}
I have place my App.Config in C:\ drive. But your App.Config should be like this, only appsetting element to be added in your App.Config.
<appSettings>
<add key="conn" value="test" />
</appSettings>
So Basically what it does is when you call the IntializeConfigurationFile() method it writes appsetting location to your local path in your filename.exe.config. In the project I have tried was added like this
Reference: AppSettingsSection Class

Specify AppSettingsReader() to look in different app.config for key

I'm using the AppSettingsReader() method to get a value from a given key in the app.config file:
var value = new AppSettingsReader().GetValue("SomeKey", typeof(string)) as string;
This is done in a class which is in a seperate assembly with its own app.config file. Now if I specify the key/value pair in this app.config:
<appSettings>
<add key="SomeKey" value="MyValue" />
</appSettings>
It throws the error:
"The key 'SomeKey' does not exist in the appSettings configuration section."
Because it looks in the App.config file from my main application which is, as stated before, in a different assembly. When I put my key/value pairs in there it works properly.
Is there a way of telling AppSettingsReader() to look in the app.config of the assembly from which it is called and not in the main (parent) assembly?
For this case you can use the ConfigurationManager class. It allows you to open configuration files from various places. To open a .config file, other than the one from the .exe, you could use the method OpenMappedExeConfiguration.
string pathToOtherConfigFile = ""; //you need to specify the path
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = pathToOtherConfig;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var value = config.AppSettings["SomeKey"];

.NET settings files in class library projects

I want to use a .NET settings file in an external dll library. This article explains exactly what I am trying to do.
partial class LastState
{
public LastState() : base(new ConfigurationFileApplicationSettings("LastState.config", typeof(LastState))) { }
}
Unfortunately, using this implementation, it is not possible to save settings back to the config file. If I try to use Save(), SetPropertyValues throws a NotSupportedException. Is there any way to save a .NET settings file from an external dll library?
I would use custom configuration files.
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = #"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel)
Have a look here for more détails.
You can save with
config.AppSettings.Settings["YourThing"].Value = "New Value";
config.Save();

exePath must be specified when not running inside a stand alone exe

When i am using a web application, the line of code below
Configuration objConfig =
ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None);
in class library are giving this error:
"exePath must be specified when not running inside a stand alone exe."
Previously a console application was being used, and the code could access the app.config. I tried using the System.Web.Configuration in class library but the dll was not present in the .Net tab for "Add reference".
Kindly help :)
You need to use a different configuration manager in a web context. The following code
block shows an example of how to deal with this:
System.Configuration.Configuration configuration = null;
if (System.Web.HttpContext.Current != null)
{
configuration =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configuration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
I'm not sure what you're doing; but at first glance it looks like you're trying to use code written for a WinForms application in a web environment. This almost certainly will not work, since your web app won't have the permissions you need.
Try looking up how to do this in a web environment (since you seem to be dealing with config files, try searching on WEB.CONFIG to start)
I tried to use the answer from #shane but ended up with the same exception using Hangfire. This code worked for me though:
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = $"{System.AppDomain.CurrentDomain.BaseDirectory}Web.Config" };
configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
}
Note that editing Web.config will cause the application pool to restart!

ConfigurationErrorsException using WCF serviceModel for Addin VS2008

I have a DLL (library project in vs2008), that calls to external web service. Project has a Service reference to external webservice
I have Unit test, and app.config (with servicemodel configuration) in unit test project, and all is right.
Now, I use Addin VS 2008, and has'nt configuration file like Windows Forms or Asp.net.
the addin is a dll and it has config file.
If I use WCF (using my project DLL), the config system.servicemodel not found
I have seen this:
http://vassiltonev.blogspot.com/2009/03/loading-custom-config-file-instead-of.html
but Adding a custom wcf behavior extension causes a ConfigurationErrorsException
The type 'Microsoft.ServiceModel.Samples.CustomTextMessageEncodingElement, CalidadCodigo.Integracion.CustomTextEncoder' registered for extension 'customTextMessageEncoding' could not be loaded. (E:\TFS\pro\AddIn\bin\Debug\MyAddIn.dll.config line 123
I test with Assembly QualifiedName in my extensions WCF but wrong.
any more suggestions or any sample code ?
my config
<extensions>
<bindingElementExtensions>
<add name="customTextMessageEncoding"
type="Microsoft.ServiceModel.Samples.CustomTextMessageEncodingElement,CalidadCodigo.Integracion.CustomTextEncoder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bindingElementExtensions>
</extensions>
The code
internal static WebServicePortTypeClient CrearClienteWCF()
{
try
{
return new WebServicePortTypeClient();
}
catch (Exception ex)
{
//TODO: not found serviceModel config
var addInConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
var endpointAddress = addInConfig.AppSettings.Settings[EasyVistaSvcEndPointAddress].Value;
var endpoint = new System.ServiceModel.EndpointAddress(endpointAddress);
return new WebServicePortTypeClient(EndPointConfigurationName, endpoint);
// The type 'Microsoft.ServiceModel.Samples.CustomTextMessageEncodingElement, CalidadCodigo.Integracion.CustomTextEncoder' registered for extension 'customTextMessageEncoding' could not be loaded. (E:\TFS\pro\AddIn\bin\Debug\MyAddIn.dll.config line 123)
}
}
AFAIK its not possible to use the ConfigurationManager in a DLL. I ran in the same issue while I wrote a Plugin for VS2010.
My Solution was to load the settings from a file an create the endpoint and endpointadress by myself in the code like this:
Uri myUri = loadUriFromFile();
var endpoint = new EndpointAddress(myUri);
NetTcpBinding binding = GetNewTcpBindingFromFile();
return new WebServicePortTypeClient(binding, endpoint);

Categories

Resources