Adding and reading a custom section in AppSettings in C# - c#

I hope you can help me.
I'm supposed to add a new type of values to an AppSettings file (already existing with some values). Those values are a whole list of special folders so I thought the best way would be to have a new section for those folder values so that the file would look like this:for
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="usPath" value="folderName1" />
<add key="tcPath" value="folderName2" />
<add key="usGUID" value="folderID1" />
<add key="tcGUID" value="folderID2" />
</appSettings>
<updateFolders>
<add key="folderID3" value="folderName3">
<add key="folderID4" value="folderName4">
</updateFolders>
</configuration>
Reading and writing within the already existing appSettings-tag is no problem but I haven't find a way yet to modify the updateFolders section. I'm really new to using AppSettings in this way so I don't know too much about what's possible and what's not. In addition to that I think the AppSettings file might have been set up in a wrong way from the very beginning (it gets created by using a System.IO.File-Writer).

see ConfigurationManager.GetSection
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection(v=vs.110).aspx

Related

How to Read Items into Arrays in web.config

I'm trying to build an array of strings from items in a web.config file (in IIS).
web.config
<appSettings>
<add key="favourite" value="url1; site1" />
<add key="favourite" value="url2; site2" />
<add key="favourite" value="url3; site3" />
</appSettings>
C#
// Reads first favourite into string.
public string _favourites = ConfigurationManager.AppSettings ["favourite"];
I would like each favourite to be read into string [ ] _favourites array with the semi-colon (I would parse that out later). web.config is an XML file so I can open it as one and pull the data out, but is there an easier way to do this using ConfigurationManager?
What if you add all Array values in single key like -
<appSettings>
<add key="favourite" value="url1;site1,url2;site2,url3;site3" />
</appSettings>
Read that key value as a string -
public string _favourites = ConfigurationManager.AppSettings["favourite"];
and then split the string by ','(comma) like this -
string[ ] _favouritesArr = _favourites.Split(',');
This will give all values in array _favouritesArr.
I don't know if there is a hack to do it, but I would just have one setting with multiple values;
<appSettings>
<add key="favourite" value="url1;site1;url2;site2;url3;site3;" />
</appSettings>
or
<appSettings>
<add key="favourite" value="url1=site1;url2=site2;url3=site3;" />
</appSettings>
Another solution is a separate configuration file or store this in a database.
I imagine that the favourites would change and changing web.config has consequences - it may cause your app to restart.
How about:
1.right click on project > properties
2.Navigate to settings. If it shows, This project does not have settings file. click to create one.
3.Create a SystemCollections.Speciliazed.StringCollection
4.Name it, as you want (my example StatusReason). and in end of line on e right there is ...(three) dots
5.Press them and add as much settings needed. One per line.
Sample:
Valid=979580000
Invalid=979580001
Broken=979580002
ReadyForCollect=979580003
Missing=979580004
Refine=979580005
and in web config it looks like that.
<applicationSettings>
<WebApplication.BookServices>
<setting name="StatusReason" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Valid=979580000</string>
<string>Invalid=979580001</string>
<string>Broken=979580002</string>
<string>ReadyForCollect=979580003</string>
<string>Missing=979580004</string>
<string>Refine=979580005</string>
</ArrayOfString>
</value>
</setting>
</WebApplication.BookServices>
</applicationSettings>
and get your array of strings :
var settings = Settings.Default.StatusReason;
//TODO add any logic, if needed to split
add your project reference to properties:
using WebApplication.BookServices.Properties;
and there you have a array of settings.

Custom config elements collection in Web.config - Using a key to choose

Intro
I'm developing a WebApp built on C# ASP.NET.
I've been researching creating a "Custom Configuration" section with child elements in the Web.config file, and I've hit a bit of a snag when it comes to consuming the keys/values in the data.
I seem to be going round in circles and I don't know how to tackle the issue I'm having.
Situation
I have a few different Connection Strings defined in the Web.Config file, in the <connectionStrings> section. They are for dev, test, and live databases.
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
The WebApp is currently hard-coded to use one of these connection strings - if I need to change which one to use, I need to re-compile.
Desired Functionality
I'd like to define a section in the Web.config, let's say DbSettings.
In that, I'd then like to be able to define some child elements for, let's say DbSettings, in which I could define dbConnectionName, foo, bar etc. as attributes.
For example:
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
... and so on
</dbSettings>
Then, perhaps in the <appSettings> section, define which of these DbSettings elements I want to use to get the settings from:
<appSettings>
<add name="dbSettingsKey" value="DbSetting1" />
</appSettings>
Desired Web.config section
Here is a fuller example of what I'd imagine my Web.config file to look like:
Connection Strings
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
App Settings
<add key="dbSettingsKey" value="DbSetting1" /> // or 2, or 3 etc.
DbSettings (custom section)
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
<dbSetting key="DbSetting2"
dbConnectionName="connectionTwo"
foo="fooTwo"
bar="barTwo" />
<dbSetting key="DbSetting3"
dbConnectionName="connectionThree"
foo="fooThree"
bar="barThree" />
</dbSettings>
My question...
How the devil am I going to get this desired functionality in the C# code?
I've read loads on "creating your own custom section", and similarly "creating a custom config collection". But, I just can't seem to glue it all together to apply for my situation.
I'd like to be able to have a class (like the one I'm using at the moment with the hard-coded strings), which I can reference necessary properties (as I am doing, at the moment) - and then the code can dynamically load the correct settings at run-time from the sections I've described above.
As always, thank you in advance for your suggestions and help.
I agree with the comments. The way this is usually done is you deploy a different web.config to each environment. When your deployment group (or you) deploys, you deploy everything EXCEPT the web.config unless you have changes to push.
In answer to your other question, adding a custom section is not trivial. It's quite a bit of work. Custom section handler which requires a whole bunch of configuration element classes and a bunch of configuration element collection classes... and then, if you want it to "work" correctly, you also need to create a schema and register that with the IDE, etc.
For your particular case, I'd just do it the "normal" way :).

Dynamically add and remove key-value pairs from a section in app.config

My XML file looks like:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="databaseTypes" type="System.Configuration.NameValueSectionHandler" />
<section name="dataDictionary" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<databaseTypes>
<add key="ExampleServerPrefix_T" value="Connection_String_For_ExampleServer" />
<add key="ExampleServer2Prefix_T" value="Connection_String_For_ExampleServer_2" />
<add key="COPYLIVE_" value="ODBC;DSN=s2;" />
</databaseTypes>
<dataDictionary>
<!-- Other pairs in this section -->
</dataDictionary>
</configuration>
What I am trying to achieve is to be able to add and remove key-value pairs from the databaseTypes section. So for example to would like to dynamically add a run time a new pair <add key="blah" value="ODBC;blah" />.
First its useful to know is this possible? If so how because I can't find any relevant documentation or examples on how this is done.
Ben,
Here are two articles that will help you with adding key/value pairs to the config:
Writing custom sections to app.config
Writing custom sections into app.config
Update AppSettings and custom configuration sections in App.config at runtime
http://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/

web.config c# .net web application

How to read a personal section in a web.config ?
<MyPersonalSection>
<add name="toto" enable="true" URL="http://localhost:43242" />
<add name="titi" enable="false" URL="http://localhost:98762" />
<MyPersonalSection/>
I'd like to get the enable value and/or URL value with the name value.
I also have this mistake : Unrecognized configuration section MyPersonalSection
I been trying
var config = ConfigurationManager.GetSection("MyPersonalSection");
Here is a cool example for that.
You don't need to write a custom configuration handler to get what you want. There are built-in configuration handlers that you can use if you simply want key-value entries. But, you'll have to use key instead of name and value instead of URL. For example:
<configuration>
<configSections>
<section name="MyPersonalSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyPersonalSection>
<add key="toto" value="http://localhost:43242" />
<add key="titi" value="http://localhost:98762" />
</MyPersonalSection>
</configuration>
And you can access them via code:
var myValues = ConfigurationSettings.GetConfig("MyPersonalSection") as NameValueCollection;
var url = myValues["toto"];
I would suggest naming your keys in a way that makes it clear what the value should be, like "totoUrl" and "titiUrl".
If you want something other than string value pairs, you'll have to write your own custom handler.
You can add appSettings section in your web.config with key that you will need. For example:
<configuration>
<appSettings>
<add key="FirstUrl" value="http://localhost:43242"/>
<add key="SecondUrl" value="http://localhost:98762" />
</appSettings>
...
</configuration>
So, since aspx.cs file, you can declare directive
using System.Configuration;
And later, you can retrieve FirstUrl value in this way:
var myUrl = ConfigurationManager.AppSettings["FirstUrl"];

How can I access web.config from an ASP.NET Custom Control?

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" />

Categories