I am trying to access one of the section of my 'web.config' file using below code
public static string XMLCheck
{
get
{
var section = (Hashtable)ConfigurationManager.GetSection("Default.Framework");
return (string)section["ConnectionString"];
}
}
but getting execption as Unable to cast object of type 'System.Configuration.ConfigXmlElement' to type 'System.Collections.Hashtable' What's wrong here? How to correct
?
Update
<Resources>
<Resource Uri="resource:Default:CrossDomain" Version="1.0" Id="8ae96c54" IsEnabled="True" Handler="handler:Default:Framework:Resources:Data:Oracle">
<Properties>
<Property Name="ConnectionString" Value="Data Source=TESTDB;User Id=TESTUSR;password=TESTPWD;Persist Security Info=false"/>
</Properties>
</Resource>
</Resources>
Verify that the configSections entry in your web.config is a DictionarySectionHandler:
<configuration>
<configSections>
<section name="Default.Framework" type="System.Configuration.DictionarySectionHandler" />
</configSections>
<configuration>
From your updated code, it looks like you're using a library or framework that defines a custom XML structure for its config section. Normally, you would rely on this library to expose the config settings through its properties. If you really want to parse the XML, you could use XPath like the below:
public static string XMLCheck
{
get
{
var section = (XmlElement)ConfigurationManager.GetSection("Default.Framework");
var connectionString = section.SelectSingleNode(#"
descendant::Resource[#Uri='resource:Default:CrossDomain']
/Properties
/Property[#Name='ConnectionString']
/#Value");
return connectionString.Value;
}
}
Related
I have an MVC project and am trying to store my API keys in a separate config file which I will ignore when pushing the code to Git. According to MSDN I should be able to store them in an App.config like like so
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="APIKey" value="APIKeyValue" />
</appSettings>
</configuration>
I should then be able to read from the file by creating a method in a model
public class KeyTest
{
public string KeyTestCall()
{
string testkey = ConfigurationManager.AppSettings.Get("APIKey");
return testkey;
}
}
and then invoke the method in my controller to assign the value from my App.config file (just so I know I'm getting the value).
public void Testing()
{
KeyTest k = new KeyTest();
ViewBag.x = k;
}
At no point will the code break for a breakpoint, the build will succeed and I can't tell if I'm getting the value or not. Any help is much appreciated. Thanks!
For a web application such as an MVC app, it's a Web.config file, not an App.config
In addition to above (re: web.config vs app.config) if you want to remove "secrets" from source control, this is one way to do it:
In web.config
<?xml version="1.0" encoding="utf-8"?>
<cofiguration>
....
<appSettings file="AppKeys.config">
<add key="SomeOtherSettingThatHasNoSecrets" value="foo" />
...
Then in a separte AppKeys.config file (you can name this whatever.config, sample as named in the above), that you don't add to Git/source control:
<appSettings>
<add key="SomeSecretKey" value="the secret" />
...
Note that AppKeys.config doesn't have an XML declaration.
Hth.
I am trying to Encrypt sensitive connection string information inside my app.config file for a C# applicaiton that I am developing. I am using the following command from the VS command promt running as administrator:
aspnet_regiis.exe -pef "Credentials" "C:\Users\.....\MyProjectFolderDir"
This is the structure of my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<config>
<configSections>
<section name="ApplicationSettings" type="sometype"/>
<section name="WebSettings" type="sometype"/>
<section name="Credentials" type="sometype"/>
<section name="SQLServerSettings" type="sometype"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<ApplicationSettings Mode="mymode"
FileSearchMode="myfilemode"
SubtractHoursDebugging="0"/>
<WebSettings WebApiServers=""
CredentialMethod="mymethod"/>
<Credentials
Domain="mydomain"
UserName="myusername"
Password="mypassword"/>
<SQLServerSettings
ConnectionString="Server=***********"/>
</config>
However, I keep getting the following error:
Encrypting configuration section...
The configuration section 'Credentials' was not found.
Failed!
How can I get this to encrypt my section?
Your config file should start with <configuration> element and not <config>. Since it's <config> aspnet_regiis.exe thinning Credentials as nested element and thus the error. With your current config file the command should be
aspnet_regiis.exe -pef "config\Credentials" "C:\Users\.....\MyProjectFolderDir"
First of all here's an answer that you can learn from about custom configuration section How to create custom config section in app.config? and here is an example from msdn https://msdn.microsoft.com/en-us/library/2tw134k3.aspx
Second, the type usually refer to a real model so you should enter the namespace and the class that you created to model the type of configuration you would like to use like so:
<configuration>
<configSections>
<section name="sampleSection"
type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<sampleSection setting1="Value1" setting2="value two"
setting3="third value" />
</configuration>
Hope it helps
So as it turns out, aspnet-regiis.exe is exclusively for web.config files. It doesn not work with app.config files unless you rename to web.config. Instead of renaming my app.config everytime I wanted to encrypt/decrypt, I ended up creating a class that would handle this each time I ran the application. Make sure you are using the following:
using System.Configuration;
using System.Web.Security;
Class:
internal class Crypto
{
internal static AppSettingsSection GetEncryptedAppSettingsSection(string exeConfigName)
{
// Open the configuration file and retrieve
// the connectionStrings section.
System.Configuration.Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);
AppSettingsSection section =
config.GetSection("appSettings")
as AppSettingsSection;
EncryptConfigSection(config, section);
return section;
}
internal static ConnectionStringsSection GetEncryptedConnectionStringsSection(string exeConfigName)
{
// Open the configuration file and retrieve
// the connectionStrings section.
System.Configuration.Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
EncryptConfigSection(config, section);
return section;
}
internal static void EncryptConfigSection(System.Configuration.Configuration config, ConfigurationSection section)
{
//Ensure config sections are always encrypted
if (!section.SectionInformation.IsProtected)
{
// Encrypt the section.
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
// Save the current configuration.
config.Save();
}
}
}
I would like to access the values in the ConfigurationManager.AppSettings object from a MEF plugin which has its own app.config file.
However, the keys from the app.config file are not present in AppSettings after the plugin is loaded.
The keys from the application loading the plugin are still present.
I noticed that using a Settings.settings file allows this behaviour, via the app.config file, so the file must be being loaded somehow.
My plugin looks like:
[Export(IPlugin)]
public class Plugin
{
public Plugin()
{
// reads successfully from app.config via Settings object
var value1 = Settings.Default["Key1"];
// returns null from app.config via ConfigurationManager
var value1 = ConfigurationManager.AppSettings["Key2"]
}
}
The app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="..." >
<section name="Plugin.Settings" type="..." />
</sectionGroup>
</configSections>
<appSettings>
<add key="Key2" value="Fails" />
</appSettings>
<applicationSettings>
<Plugin.Settings>
<setting name="Key1" serializeAs="String">
<value>Works</value>
</setting>
</Plugin.Settings>
</applicationSettings>
</configuration>
I can manually load the app.config file with:
var config = ConfigurationManager.OpenExeConfiguration("Plugin.dll");
var value = AppSettings.Settings["Key2"].Value
but this seems more like a workaround than a solution.
Is there a way to access a MEF plugin's <appSettings> directly, from inside the plugin?
If not, what is recommended?
By default the ConfigurationManager loads the .config for the entry assembly, i.e. the assembly that started the currently executing process.
The correct way to do this would be something like this:
[Export(IPlugin)]
public class Plugin
{
public Plugin()
{
var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
var value = config.AppSettings.Settings["Key2"].Value;
}
}
This would make the plugin automatically open the .config for the DLL it was compiled in, and fetch values from there.
I'd recommend you to use a dependency injection tool like Unity, in order to provide to your plug-ins the configuration they required. By proceeding in this way, your plug-ins will no longer need to reference System.Configuration.dll.
Inside my web.config file I've got code like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
<section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
</configSections>
...
<UninstallSurveySettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</UninstallSurveySettings>
...
</configuration>
I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.
I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.
Much easier to use AppSettings.
Web.config:
<configuration>
<appSettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</appSettings>
</configuration>
Code:
string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];
If your section will become more complex, then:
var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
// access section members
}
P.S.
Maybe you want to use ConfigurationSection class instead of handler.
In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).
How about adding your key to the section. Then you can easily access it via the ConfigurationManager.AppSettings collection.
using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config
I was able to solve this by creating a configuration class for it and placing this code in the web.config:
<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..
<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />
So this a new one for me.
I'm trying to define a ConfigurationSection class in my class library that pulls from App.Config in my WinForms app. I've never done this before but from following examples this is where I've got to.
app.config in my WinForms app
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ReportEngineConfig" type="Optima.ReportEngine.ReportEngineConfig" allowDefinition="Everywhere" allowLocation="true"/>
</configSections>
<ReportEngineConfig>
<ReportObjectVariableRegEx value="test" ></ReportObjectVariableRegEx>
</ReportEngineConfig>
</configuration>
And my ConfigurationSection class in my seperate class library.
using System.Configuration;
namespace Optima.ReportEngine
{
public class ReportEngineConfig : ConfigurationSection
{
[ConfigurationProperty("ReportObjectVariableRegEx")]
public string ReportObjectVariableRegEx
{
get
{
return (string)this["value"];
}
}
}
}
So any chance anyone can point out where I've gone wrong
Thanks!
Your type tag needs to reference the assembly name, not just the type name:
type="Optima.ReportEngine.ReportEngineConfig, Optima.ReportEngineAssembly"
Where the section after the comma is the name of the assembly containing ReportEngineConfig. You'll also have to make sure the application that is using this app.config has referenced the same assembly containing ReportEngineConfig.
Also you can get rid of the allowDefinition and allowLocation tags... you've put the defaults in.