Getting error in loading Configuration file,Parameter is not valid - c#

I have an installer class which is retrieving the parameters from the Visual Studio Setup project.Now on opening the exeConfiguration i am getting following error..
Error 1001:An error occurred loading a configuration file.
The parameter 'exePath' is invalid.
Parameter name:exepath-->The Parameter 'exePath' is invalid.
Parameter name:exePath
And here is my Installer.cs Code..
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["targetdir"];
string param1 = Context.Parameters["Param1"];
string param2 = Context.Parameters["Param2"];
string param3 = Context.Parameters["Param3"];
string exePath = string.Format("{0}TechSoft CallBill.exe", targetDirectory);
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
config.AppSettings.Settings["Param1"].Value = param1;
config.AppSettings.Settings["Param2"].Value = param2;
config.AppSettings.Settings["Param3"].Value = param3;
config.Save();
}
Please help me to sort out this error As i am not able to figure out.
Any suggestion is heartily welcomed.
Thanks in advance

If the Config file belongs to the same project then try this, If the config file belongs to the same project then you don't have to use config file path.
Configuration config= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Param1"].Value = param1;
config.AppSettings.Settings["Param2"].Value = param2;
config.AppSettings.Settings["Param3"].Value = param3;
//Save only the modified section of the config
config.Save(ConfigurationSaveMode.Modified);
//Refresh the appSettings section to reflect updated configurations
ConfigurationManager.RefreshSection(Constants.AppSettingsNode);

Related

Exception : System.InvalidOperationException: An unexpected error occurred in 'ClientConfigurationHost::Init'

I am trying to read the custom-defined configuration file from the library project that I have created in c#.
To read the configuration file, There is a ConfigManager i have created as below,
static Configuration ConfigManager
{
get
{
if (_configuration == null)
{
//Map the new configuration file.
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = _assemblyLocation;
// Get the mapped configuration file
_configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
}
return _configuration;
}
}
I am getting the exception at OpenMappedExeConfiguration() Method.
Any help would be appreciated.
Thanks in advance.

Relative virtual path is not allowed when using server.MapPath()

I am Trying to get the configuration file using the following code:
public void EncryptConnString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Server.MapPath(#"/"));
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
config.Save(ConfigurationSaveMode.Modified);
}
}
But i am getting the error
The relative virtual path 'F:/xxxx/yyyy/sample/' is not allowed here.
Note: I am accessing this code in global.asax page What i am doing wrong?
If you pass null to this method, it will return the root config file for you:
var config = WebConfigurationManager.OpenWebConfiguration(null);

ExeConfigurationFileMap: InvalidArgumentException, The string parameter 'fileMap.ExeConfigFilename' cannot be null or empty

I am getting an InvalidArgumentException when I run my application. I am attempting to create a new ExeConfigurationFileMap, and then load it with ConfigurationManager.
public static ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\QuikSnap\\QuikSnap.config");
public static Configuration config = ConfigurationManager.OpenMappedExeConfiguration(Settings.configFile, ConfigurationUserLevel.None);
I have also attempted to set the configuration file after declaring it, but still didn't have any luck.
If I attempt to continue after this exception, I next receive a TypeInitalizationException upon trying to set a variable to one of the values in the configuration file.
Ran into this same problem. For some ridiculous reason, initializing ExeConfigurationFileMap even with the filepath does not set the property ExeConfigFilename which is required by the Configuration objects constructor. I fixed it by immediately setting that property after instantiating the ExeConfigurationFileMap object like below:
public static ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\QuikSnap\\QuikSnap.config");
configFile.ExeConfigFilename = "QuikSnap.config";
public static Configuration config = ConfigurationManager.OpenMappedExeConfiguration(Settings.configFile, ConfigurationUserLevel.None);
You didn't set the right property with the value of the config file path.
Also, you have a static variable dependency on another static variable in the same class. There could be potentially an issue of order of execution here (though i'm not sure)
Try this instead:
public static Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
{
ExeConfigFilename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\QuikSnap\\QuikSnap.config"
}, ConfigurationUserLevel.None);

Modifying app.config via custom msi installer

I need to create an address string in app.config as:
<client>
<endpoint address="http://ServerName/xxx/yyy.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IClientIInfoService"
contract="DocuHealthLinkSvcRef.IClientIInfoService" name="BasicHttpBinding_IClientIInfoService" />
</client>
The ServerName need to be entered by the user during installation.
For that i have created a new UI dialog in the Installer. I have also written an Installer.cs class and overrided the install () as:
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["targetdir"];
string ServerName = Context.Parameters["ServerName"];
System.Diagnostics.Debugger.Break();
string exePath = string.Format("{0}myapp.exe", targetDirectory);
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
config.AppSettings.Settings["ServerName"].Value = ServerName;
config.Save();
}
}
But how do i use this ServerName in my app.config to create the specified string.
I'm working on VS2010.
You could use WiX (Windows Installer XML toolset) to build your MSI, in which case you can use the XmlFile utility tag to update the server name:
<util:XmlFile Id="UpdateServerName" File="[INSTALLLOCATION]AppName.exe.config" Action="setValue" ElementPath="/client/endpoint" Name="address" Value="http://[SERVERNAME]/xxx/yyy.svc" />
You can capture the server name during installation using a WixUI extension form.
Advantages of WiX: WiX is msbuild compliant (unlike .vdproj files), and gives you much finer-grained control over your installer, among other things
Assuming you are using the full ServiceModel section group in the app.config
Essentially you follow these steps:
Load ServiceModel config section
Get Client Section
Get ChannelEndpoint Element
Change Address value by replacing string "ServerName" with entered value
Set Address attribute to new value
Save config
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["targetdir"];
string ServerName = Context.Parameters["ServerName"];
System.Diagnostics.Debugger.Break();
string exePath = string.Format("{0}myapp.exe", targetDirectory);
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
config.AppSettings.Settings["ServerName"].Value = ServerName;
//Get ServiceModelSectionGroup from config
ServiceModelSectionGroup group = ServiceModelSectionGroup.GetSectionGroup (config);
//get the client section
ClientSection clientSection = group.Client;
//get the first endpoint
ChannelEndpointElement channelEndpointElement = clientSection.Endpoints[0];
//get the address attribute and replace servername in the string.
string address = channelEndpointElement.Address.ToString().Replace("ServerName", ServerName);
//set the Address attribute to the new value
channelEndpointElement.Address = new Uri(address);
config.Save();
}
At the end of the day, app.config is xml file. You can use Linq To XML or XPathNavigator to replace the address attribute of endpoint element.
Below code uses Linq to Xml
using System.Xml.Linq;
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["targetdir"];
string ServerName = Context.Parameters["ServerName"];
System.Diagnostics.Debugger.Break();
string configPath = string.Format("{0myapp.exe.config", targetDirectory);
XElement root = XElement.Load(configPath);
var endPointElements = root.Descendants("endpoint");
foreach(var element in endPointElements)
{
element.Attribute("address").Value = ServerName;
}
root.Save(configPath);
}
}
Since you have a windows-installer tag, I assume you either have an MSI package, or can create one...
Then:
You can create a public MSI property like ENDPOINTSERVER you require
during installation.
Add a custom action that modifies app.config to
run after "InstallFinalize" with the value of ENDPOINTSERVER
A silent installation will be possible using:
msiexec /i app.msi ENDPOINTSERVER=www.MyServer.com /qb-
try to use below two lines before saving the config file changes:
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("Section Name");
root.Save(configPath);
P.S: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

Problems in reading DLL app.setting

i have problems in reading DLL application setting in c# Visual Studio 2010.
I post a sample code of the get workarounded using reflection because with the ConfigurationManager fails.
private string LDAPDomain
{
get
{
string strPath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
string val = GetValues(strPath, "LDAPDomain");
return val;
}
}
//strPath is path of the file.
//strKey is key to access
private string GetValues(string strPath, string strKey)
{
System.Configuration.Configuration con = System.Configuration.ConfigurationManager.OpenExeConfiguration(strPath);
string strValue = con.AppSettings.Settings[strKey].Value;
return strValue;
}
If you are expecting the main project referencing the DLL to pick up the app settings it doesn't work like that. The ConfigurationManager will read the config for the executing assembly, you need to put all the necessary configuration into your app if you want to use this.
Alternatively you can manually read the contents of your DLL's app.config file - see this question for some example code.

Categories

Resources