Accessing Customizing in .Net

I am trying to access the settings in my configuration file, which is a series of xml elements listed as such:

<databases> <database name="DatabaseOne" Value="[value]" /> <database name="DatabaseTwo" Value="[value]" /> </databases> 

Now I want to access it. I created such classes:

 Public Class DatabaseConfigurationHandler Inherits ConfigurationSection <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _ Public ReadOnly Property Databases() As DatabaseCollection Get Return CType(Me("Databases"), DatabaseCollection) End Get End Property End Class Public Class DatabaseCollection Inherits ConfigurationElementCollection Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement Return (New Database()) End Function Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object Return (CType(element, Database).DatabaseName) End Function End Class Public Class Database Inherits ConfigurationElement <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _ Public Property DatabaseName() As String Get Return Me("name").ToString() End Get Set(ByVal Value As String) Me("name") = Value End Set End Property <ConfigurationProperty("value", IsRequired:=True)> _ Public Property DatabaseValue() As String Get Return Me("value").ToString() End Get Set(ByVal Value As String) Me("value") = Value End Set End Property End Class 

I want to get an element by its name and return a value, but I cannot do this:

 Dim config As New DatabaseConfigurationHandler config = System.Configuration.ConfigurationManager.GetSection("databases/database") Return config.Databases("DatabaseOne") 

I missed some code, what am I doing wrong? Any other errors in the above?

Thanks.

+7
configuration
source share
6 answers

Here I cut and paste from something very similar I did a few days ago.

Configuration:

  <ListConfigurations> <lists> <add Name="blah" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/> <add Name="blah2" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/> </lists> </ListConfigurations> 

C # configuration section:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace App { /// <summary> /// Individual list configuration /// </summary> class ListConfiguration : ConfigurationElement { [ConfigurationProperty("Name", IsKey = true, IsRequired = true)] public string Name { get { return (string)this["Name"]; } } [ConfigurationProperty("EndpointConfigurationName", IsRequired = true)] public string EndpointConfigurationName { get { return (string)this["EndpointConfigurationName"]; } } [ConfigurationProperty("ListName", IsRequired = true)] public string ListName { get { return (string)this["ListName"]; } } [ConfigurationProperty("ConnectionString", IsRequired = true)] public string ConnectionString { get { return (string)this["ConnectionString"]; } } [ConfigurationProperty("TableName", IsRequired = true)] public string TableName { get { return (string)this["TableName"]; } } [ConfigurationProperty("FieldsCsv", IsRequired = true)] public string FieldsCsv { get { return (string)this["FieldsCsv"]; } } [ConfigurationProperty("DbFieldsCsv", IsRequired = true)] public string DbFieldsCsv { get { return (string)this["DbFieldsCsv"]; } } } /// <summary> /// Collection of list configs /// </summary> class ListConfigurationCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ListConfiguration(); } protected override object GetElementKey(ConfigurationElement element) { return ((ListConfiguration)element).Name; } } /// <summary> /// Config section /// </summary> class ListConfigurationSection : ConfigurationSection { [ConfigurationProperty("lists")] public ListConfigurationCollection Lists { get { return (ListConfigurationCollection)this["lists"]; } } } } 

And the code to select it from the main application:

 ListConfigurationSection configSection = null; try { configSection = ConfigurationManager.GetSection("ListConfigurations") as ListConfigurationSection; } catch (System.Configuration.ConfigurationErrorsException) { } 
+7
source share

There is no good reason to create these kinds of things manually. Rather, you should use the configuration section constructor in CodePlex:

http://csd.codeplex.com/

After installation, you can simply add a new element to your project (constructor of the configuration section), and then add elements and restrictions. I found it VERY easy to use, and I will probably never write part of the code for the configuration files again.

+7
source share

Instead, you can use this configuration handler. It will work for ALL custom configuration sections.

  public class XmlConfigurator : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { if (section == null) throw new ArgumentNullException("section", "Invalid or missing configuration section " + "provided to XmlConfigurator"); XPathNavigator xNav = section.CreateNavigator(); if (xNav == null) throw new ApplicationException( "Unable to create XPath Navigator"); Type sectionType = Type.GetType((string) (xNav).Evaluate("string(@configType)")); XmlSerializer xs = new XmlSerializer(sectionType); return xs.Deserialize(new XmlNodeReader(section)); } } 

Then your configuration file should contain a reference to the type that represents the root element

 <ConnectionConfig configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" > 

An example configuration file might look like this:

 <?xml version="1.0" encoding="utf-8" ?> <ConnectionConfig configType="MyNamespace.ConnectionConfig, MyNamespace.AssmblyName" > <ConnCompanys> <ConnCompany companyName="CompanyNameHere"> <ConnApps> <ConnApp applicationName="Athena" vendorName="Oracle" > <ConnSpecs> <ConnSpec environments="DEV" serverName="Athena" port="1521" catalog="DatabaseName" logon="MyUserName" password="%%552355%8234^kNfllceHGp55X5g==" /> <!-- etc... 

And you will need to define the classes that each xml element maps to ... using the appropriate XmlSerialization attributes ...

 [XmlRoot("ConnectionConfig")] public class ConnectionConfig { private ConnCompanys comps; [XmlArrayItem(ElementName = "ConnCompany")] public ConnCompanys ConnCompanys { get { return comps; } set { comps = value; } } public ConnApp this[string CompanyName, string AppName] { get { return ConnCompanys[CompanyName][AppName]; } } public ConnSpec this[string CompanyName, string AppName, APPENV env] { get { return ConnCompanys[CompanyName][AppName, env]; } } } public class ConnCompanys : List<ConnCompany> { public ConnCompany this[string companyName] { get { foreach (ConnCompany comp in this) if (comp.CompanyName == companyName) return comp; return null; } } public bool Contains(string companyName) { foreach (ConnCompany comp in this) if (comp.CompanyName == companyName) return true; return false; } } public class ConnCompany { #region private state fields private string compNm; private ConnApps apps; #endregion private state fields #region public properties [XmlAttribute(DataType = "string", AttributeName = "companyName")] public string CompanyName { get { return compNm; } set { compNm = value; } } [XmlArrayItem(ElementName = "ConnApp")] public ConnApps ConnApps { get { return apps; } set { apps = value; } } #endregion public properties #region indexers public ConnApp this[string applicationName] { get { return ConnApps[applicationName]; } } public ConnSpec this[string applicationName, APPENV environment] { get { foreach (ConnSpec con in this[applicationName].ConnSpecs) if (con.Environment == environment) return con; return null; } } #endregion indexers } 

etc.

+2
source share

My VB is not very sorry, but here is how you do it in C #.

FROM#

 public class AppState : IConfigurationSectionHandler { static AppState() { xmlNode myConfigNode = (XmlNode)ConfigurationManager.GetSection("databases"); } public object Create(object parent, object context, XmlNode configSection) { return configSection; } } 

App.Config

 <configuration> <configSections> <section name="databases" type="MyAssembly.AppState, MyAssembly" /> </configSections> <databases> <database name="DatabaseOne" Value="[value]" /> <database name="DatabaseTwo" Value="[value]" /> </databases> </configuration> 
0
source share

You may be interested in using ConfigurationElementCollection, where T is the type of the child of ConfigurationElements. You can find sample code in C # at http://devpinoy.org/blogs/jakelite/archive/2009/01/10/iconfigurationsectionhandler-is-dead-long-live-iconfigurationsectionhandler.aspx

Hooray!

0
source share

A good easy way is also shown here:

codeproject.com/KB/XML/xml_config_section.aspx

0
source share

All Articles