Is it possible to overwrite class attributes using web.config in C#? - c#

I have a class that is decorated with a custom attribute derived from System.Attribute.
I want to change one property of this attribute.
Is it possible without modifying the code? Web.config maybe?

If you don't refer to your WebConfig from your compiled code, you won't be able to change the compiled Code later via WebConfig.
I think what you are looking for is something like this:
var name = Settings.Default.Name;
You can change this value later in your app/web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- ... -->
<setting name="Name" serializeAs="String">
<value>Robert</value>
</setting>
<!-- ... -->
</configuration>

Related

Problem calling a second .config for keys in C#

I need a second .config to manage alot of keys. I tried using
<configSections>
<section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
</configSections>
<apiConnection configSource ="ApiConnection.config"/>
Where "ApiConnection.config" is my .config file to manage keys but this didn't work.
Then i tried the "file" property in appSettings.
<appSettings file="ApiConnection.config">
This didn't work either. I Tried with:
../ApiConnection.config
~/ApiConnection.config
But nothing...
Some ideas?
The program doesnt break, just not show me the keys when i try with the ConfigurationManager.
https://i.stack.imgur.com/6xHK2.png
<img src= https://i.stack.imgur.com/6xHK2.png/>
EDIT
My file is in root path (with web.config)
The file looks like
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="Secret" value="z8xyHkN3Eju2TS9u-4MXeI2AbZiuTsF7xYJcjIJ" />
<add key="Audience" value="keyforms"/>
</appSettings>
Ok I think I know what your problem is based on your last comment.
This code is creating a new configuration section called apiConnection.
<configSections>
<section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
</configSections>
<apiConnection configSource ="ApiConnection.config"/>
This section's values will not be contained in app settings. So you won't be able to access it via
ConfigurationManager.AppSettings
You will need to access it in a different manner. Now the exact manner will depend on your implementation of CustomConfig.apiConnectionSection and CustomConfig. I would search your code to find the class that defines how this works.
This example shows how to pull values from a custom config section, SecureAppSettings that uses the NameValueCollection in the same manner as AppSettings. You will have to do some digging to figure out what Types you will need to utilize.
NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];

Where to store global variables (like paths) in C#?

I'm new to C# and am still in the process of figuring out the best practices for certain things.
I want to know where I could store settings such as paths (eg. For file uploads) and other assorted variables so that they can be accessed anywhere in the project.
Should I just create a class with static variables or is there a better approach to storing these settings?
You'd better save this in the web.config since this can be changed after compilation.
The appSettings element is reserved for this kind of functionality. You can even split this part off in a different file so it is totally clear this in your specific config.
Example web.config only:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DocumentDirectory" value="~/Documents" />
</appSettings>
</configuration>
Or:
web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="appSettings.xml" />
</configuration>
And a separate appSettings.xml:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="DocumentDirectory" value="~/Documents" />
</appSettings>
You can read those settings like this:
using System.Configuration;
using System.Web.Configuration;
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
if (config.AppSettings.Settings.Count > 0)
{
KeyValueConfigurationElement customSetting = config.AppSettings.Settings["DocumentDirectory"];
if (customSetting != null)
{
string directory = customSetting.Value;
}
}

How to deal with changed ConfigurationSection-Definition?

I have a Configuration-File that I read with the ConfigurationManager. There are some Sections that I defined by myself.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="applicationWideSettingsSection" type="MyTestApp.ApplicationSettings.ApplicationWideSettingsSection, MyTestAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<applicationWideSettingsSection>
<pathToSomeFile value="C:\Users\..." />
</applicationWideSettingsSection>
</configuration>
There are new requirements: now I have to store another value in the applicationWideSettingsSection like this:
<applicationWideSettingsSection>
<pathToSomeFile value="C:\Users\..." />
<pathToSomeOtherFile value="C:\Programs\..." />
</applicationWideSettingsSection>
So I change my definition of the applicationWideSettingsSection. If I now run the application with an old config-File it throws an exception on this line:
var configSection = _config.GetSection("applicationWideSettingsSection");
because there is only the pathToSomeFile-Setting and the other one is missing.
Is there a way to manually add another (default value) to this section?
How would you deal with this??
Thanks in advance, Joerg
Because I didn't want to change my design away from my custom Setting-Types I found a different way:
I set the IsRequired to false so no exception is thrown when the setting is missing. If it's missing I set it to some value from code.
In a different approach I wanted to override some of the Configuration-Section methods but did not get it to work...
now I have to store another value in the applicationWideSettingsSection
Instead of your custom type ApplicationWideSettingsSection you can use a key-value pairs, so
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="applicationWideSettingsSection"
type="System.Configuration.NameValueSectionHandler" />
</configSections>
<applicationWideSettingsSection>
<pathToSomeFile value="C:\Users\..." />
</applicationWideSettingsSection>
</configuration>
This will store 1 or many parameters and allow you to enumerate on the inner parameters. You can also try DictionarySectionHandler. I found sample code in this post.

How to use ConfigurationManager.AppSettings with a custom section?

I need to get "http://example.com" from using App.config file.
But at the moment I am using:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
I cannot get the value.
Could you point out what I am doing wrong?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.SingleTagSectionHandler" />
<section name="server" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<device id="1" description="petras room" location="" mall="" />
<server url="http://example.com" />
</configuration>
I think you need to get the config section, and access that:
var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];
And you also need to update your config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.NameValueSectionHandler" />
<section name="server" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<device>
<add key="id" value="1" />
<add key="description" value="petras room" />
<add key="location" value="" />
<add key="mall" value="" />
</device>
<server>
<add key="url" value="http://example.com" />
</server>
</configuration>
Edit: As CodeCaster mentioned in his answer, SingleTagSectionHandler is for internal use only. I think NameValueSectionHandler is the preferred way to define config sections.
The SingleTagSectionHandler documentation says:
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
You can retrieve it as a HashTable and access its entries using Configuration.GetSection():
Hashtable serverTag = (Hashtable)ConfigurationManager.GetSection("server");
string serverUrl = (string)serverTag["url"];
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
gets the value from the appSettings part of the app.config file but you are storing your value in
<server url="http://example.com" />
Either put the value in the appSettings section as below or retrieve the value from its current location.
You need to add a key value pair to your config's appSettings section. As below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
</configuration>
Your reading code is correct but you should probably check for null. If the code fails to read the config value the string variable will be null.
You're defining a configuration section instead of a value in AppSettings. You can simply add your setting to AppSettings:
<appSettings>
... may be some settings here already
<add key="server" value="http://example.com" />
</appSettings>
Custom config sections are typically used for more complicated configurations (e.g. multiple values per key, non-string values, etc.
If you want to get the value from the app settings your appsetting element in configuration file must have a key.
define your sever value as mentioned below under configuration section:
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
...
...
...
</configuration>
Now execute below code line to get the server url:
string peopleXMLPath = ConfigurationManager.AppSettings["server"].ToString();

GetSection object cannot be cast to IDictionary<>

I hope I'm just missing something simple. I need to read/write to a section of my exe.config file. I have this in my code:
var appConfiguration = ConfigurationManager.OpenExeConfiguration("Mytest.Console.exe");
var fileEnvironment = appConfiguration.GetSection("fileEnvironment");
and this is my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="fileEnvironment" type="System.Configuration.DictionarySectionHandler"/>
</configSections>
<fileEnvironment>
<add key="TestEntry1" value="A nice value"/>
<add key="TestEntry2" value="Another value"/>
</fileEnvironment>
</configuration>
My appConfiguration variable is returned as {System.Configuration.Configuration} and the "HasFile" property is set to true.
Without casting my variable "fileEnvironment" is returned as System.Configuration.DefaultSection. When I add as IDictionary<string, string> to the GetSection method fileEnvironment is null.
Any ideas?
I kept researching the dictionary issue and came up with this stackoverflow Q&A! It produces a collection instead of a dictionary, but points the way to a solution. Thanks for everyone's time.
According to this old article, when a section is implemented using DictionarySectionHandler, ConfigurationManager.GetSection() will return a non-generic IDictionary, and not an IDictionary<T,V>. That's why your cast failed.
Although in modern times, it looks like it actually returns a HashTable.

Categories

Resources