I want ta change another Webconfig but I'm getting erors
What I tried is
string path = "E:\\username\\myprojects\\myproject\\Web.config";
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(path);
webConfig.AppSettings.Settings.Add("DBNAME", "DEV_TEMP");
webConfig.Save();
This said " Web.config denied relative virtual paths"
and another I tried on webconfig
<configuration>
<appSettings>
<add key="DBNAME" value="DEV_DEVELOPMENT"/>
</appSettings>
DBNAME value change to "DEV_TEMP"
XDocument doc=XDocument.Load("E:\\username\\myprojects\\myproject\\Web.config");
doc.Element("appSettings").Element("DBNAME").Value = "DEV_TEMP";
doc.Save("Web.config");
and it says Null reference
Assuming you have a good reason to do this, you could use something like:
var addElement = doc.Element("configuration").Element("appSettings").Elements().First(x => x.Attribute("key").Value == "DBNAME");
var valueAttribute = addElement.Attribute("value");
valueAttribute.Value = "DEV_TEMP";
Note that you also need to get the configuration element, and you can get the add element by selecting the element where the key attribute matches DBNAME as there could be multiple add elements. Also value is the attribute of add, not an element itself. See the XML Document Object Model (DOM)
for further information.
Related
This is my current solution structure
Solution ABC
ProjectA
ProjectB
ProjectWeb
AppData --> CMS --> Configurations -->oneABC.config
Areas -->Produts --> Web --> abc.cs [where I need to access that config]
Web.config
ProjectC
PFB oneABC.config file
<?xml version="1.0" encoding="utf-8"?>
<oneABC xmlns:config="urn:configuration" xmlns:type="urn:configuration:type" config:version="12.2.7239.0">
<countrycredentials>
<add name="abbpoland" password="d0da0956b411" view="True" code="PL" />
<add name="abbitaly" password="25430aa9fa22" view="True" code="IT" />
</countrycredentials>
</oneAbbExternalDistributorInventoryConfig>
its not part of web.config and the value inside oneABC.config are not static as we can have multiple add or single add as well.
Right now i need to fetch the details from this config file and use it to do some operations, I have done some digging to fetch these details but found none related to my problem.
PFB the function that i have written inside abc.cs to fetch the details:
//in culture im getting lang like 'en' ,'pl' or 'it' as per the url
public static bool GetConfigurationValue(string culture)
{
string lang = culture;// im storing that language
ExeConfigurationFileMap customConfigFileMap = new ExeConfigurationFileMap();
// in below i need to mention the path of config file right now its not working as its checking this file from C:\Program Files (x86)\IIS Express\OneABC.Config
customConfigFileMap.ExeConfigFilename = "OneABC.Config";
Configuration customConfig = ConfigurationManager.OpenMappedExeConfiguration(customConfigFileMap, ConfigurationUserLevel.None);
AppSettingsSection appSettings = (customConfig.GetSection("countrycredentials") as AppSettingsSection);
// below i need to save those tag value in such a way that if lang = PL then ill use view as true and return true
//and if ill get it in lang then ill use view as false and return false
}
is there any universal way to set the file path of this file since currently im checking this in local and the ill need to deploy it to some server so file path will change.
I'm trying to pull data from the web config file as outlined by this msdn resource.
Here is my code:
System.Configuration.Configuration activeCampaignApiSetting1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
if (activeCampaignApiKeySetting != null) {
activeCampaignApiKey = activeCampaignApiKeySetting.Value;
}
System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
if (activeCamapignApiUrlSetting != null) {
activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
}
}
When I try to instantiate this class:
var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);
it throws an exception telling me that the values are blank.
The values in the web config file are there:
<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
Anyone know where I may be going wrong?
Cheers
If they are appSetting inside web.config, you can access them via ConfigurationManager.AppSettings.
<?xml version="1.0"?>
<configuration>
<configSections>
<appSettings>
<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
</appSettings>
</configSections>
</configuration>
string activeCampaignApiKeySetting
= ConfigurationManager.AppSettings["ActiveCampaignApiKey"];
string activeCamapignApiUrlSetting
= ConfigurationManager.AppSettings["ActiveCampaignApiUrl"];
Please make sure you reference System.Configuration, and include using System.Configuration; directive.
FYI: They return string value (not key value pair).
Ok so I have a better solution,
As I'm working with nopCommerce I need to use:
private readonly ISettingService _settingService = EngineContext.Current.Resolve<ISettingService>();
string apikey = _settingService.GetSettingByKey<string>("apikey_removed");
string apiurl = _settingService.GetSettingByKey<string>("apiurl_removed");
As outlined in this forum thread
Then in the administration backend under configuration > settings > all settings I add the key there.
This is a much better solution because if the api key or url ever need to be changed it can be done through the nopcommerce administration panel. rather than rebuilding/publishing the solution to a web server.
Hope this helps someone :)
I'd like to get a value from this config file from within an MVC view. How is this achieved?
Thanks
UnsupportedBrowsers.config (projectRoot/config/..)
<UnsupportedBrowsers>
<Browser alias="Internet Explorer">
<Version>
<add key="ie6" value="IE6"/>
<add key="ie7" value="IE7"/>
<add key="ie8" value="IE8"/>
</Version>
</Browser>
</UnsupportedBrowsers>
First, it would be better to do it in the Controller rather than in the View.
Second, reading an XML file is an easy task, use XDocument class for example:
var xDoc = XDocument.Load("projectRoot\config\UnsupportedBrowsers.config");
var versionKeys = xDoc.Descendants("Version").First().Descendants();
foreach(var key in versionKeys)
{
//Do something with the retrived keys..
}
Side note:
In any case, you're better cache this object in order to avoid of I/O blockings if each new incoming request need to use it.
I'm trying to read some configuration in my global.aspx Application_Start method. When I read ConfigurationManager.GetSection("system.web/httpHandlers") everything is fine:
ConfigurationManager.GetSection("system.web/httpHandlers")
{System.Web.Configuration.HttpHandlersSection}
base {System.Configuration.ConfigurationSection}: {System.Web.Configuration.HttpHandlersSection}
Handlers: Count = 48
But when I read ConfigurationManager.GetSection("system.webServer/handlers") (which contains my custom handlers, it returns null. What am I doing wrong?
The section looks like this:
<system.webServer>
<handlers>
<add verb="*" path="*.loc" name="LocalizedResourceStreamer"
type="CFW.WebUI.HttpHandlers.LocalizedResourceStreamer,WebUI" />
</handlers>
</system.webServer>
Notes:
Web.configs are nested, ConfigurationManager.GetSection takes nesting into account by default.
The overall problem is trying to see if *.loc files are being served.
So far:
Looks like the system.webServer is ignored.
Depending on your OS/setup, the system.webServer element may be configured to be ignored - and so the config system will not be constructing any inner configuration items from it. E.g. on my machine (WinXP, IIS 5.1), it's set to ignored by default.
Check the machine.config on the machine where this code is running, and see how the system.webServer element is configured. I don't have machines available with suitable later OSes at the moment, but it may be that this element is always set to be ignored - after all, that part of the config is for IIS' use, rather than our own.
try :
**p.s. my web.config contains : <httpHandlers> and not handlers as yours. change as necessarily :) - also the webserver vs system.web **
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection webConfigSections = webConfig.GetSection("system.web/httpHandlers");
if (webConfigSections != null)
{
// PropertyInformationCollection t = webConfigSections.ElementInformation.Properties;
XDocument xmlFile = XDocument.Load(new StringReader(webConfigSections.SectionInformation.GetRawXml()));
IEnumerable<XElement> query = from c in xmlFile.Descendants("add") select c;
foreach (XElement band in query)
{
}
}
p.s. thats the problem with this section - he doesnt have a uniquee element name that can be taken. thats why you take it whole("add" element) and parse it.
I am trying to use a config file in my C# console application. I created the file within the project by going New --> Application Configuration File, and naming it myProjectName.config. My config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SSDirectory" value="D:\Documents and Settings\****\MyDocuments\****" />
</appSettings>
</configuration>
The code to access it looks like this:
private FileValidateUtil()
{
sSDirFilePath = ConfigurationSettings.AppSettings["SSDirectory"];
if (sSDirFilePath == null)
Console.WriteLine("config file not reading in.");
}
Can anyone lend a hint as to why this is not working? (I am getting the error message.)
Thanks!!
badPanda
You can't change the name from app.config and expect ConfigurationManager to find it without providing it more information. Change the name of myProjectName.config back to app.config, rebuild, and you will see a file in the bin folder called myProjectName.exe.config. Then your call to ConfigurationManager.AppSettings should work correctly.
check the documentation
http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
First off, use ConfigurationManager instead of ConfigurationSettings.
Second, instead of saying "doesn't work", which provides no useful information, tell us what you're seeing. Does it compile? Does it throw an exception at runtime? Does your PC start to smoke and smell like melting plastic?
Try this:
public string GetSSDirectory()
{
string sSDirFilePath = string.Empty;
if (!ConfigurationManager.AppSettings.AllKeys.Contains("SSDirectory"))
{
Console.WriteLine("AppSettings does not contain key \"SSDirectory\"");
}
else
{
sSDirFilePath = ConfigurationManager.AppSettings["SSDirectory"];
Console.WriteLine("AppSettings.SSDirectory = \"" + sSDirFilePath + "\"");
}
return sSDirFilePath;
}