Reputation: 2046
I am trying setting up application configuration. Problem is that nothing is readed from the configuration. I am using this code:
Sections:
public class TownSection : ConfigurationSection
{
public static TownSection.GetConfig()
{
return (TownSection)System.Configuration.ConfigurationManager
.GetSection("TownSection") ?? new TownSection();
}
[System.Configuration.ConfigurationProperty("TownProperties")]
[ConfigurationCollection(typeof(TownProperties), AddItemName = "TownProperty")]
public TownProperties TownProperties
{
get
{
object o = this["TownProperties"];
return o as TownProperties;
}
}
}
List of the entities:
public class TownProperties: ConfigurationElementCollection
{
public TownProperty this[int index]
{
get
{
return base.BaseGet(index) as TownProperty ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new TownProperty this[string responseString]
{
get { return (TownProperty)BaseGet(responseString); }
set
{
if (BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new TownProperty();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((TownProperty)element).Name;
}
}
Entity:
public class TownProperty: ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true)]
public string Name
{
get
{
return this["Name"] as string;
}
}
[ConfigurationProperty("Distance", IsRequired = true)]
public string Distance
{
get
{
return this["Distance"] as string;
}
}
}
Configuration in app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="TownSection">
<section
name="TownSection"
type="App.Configurations.TownSection"
allowLocation="true"
allowDefinition="Everywhere" />
</sectionGroup>
</configSections>
<TownSection>
<TownProperties>
<TownProperty Name="A" Distance="1.8"/>
<TownProperty Name="B" Distance="5.8"/>
</TownProperties>
</TownSection>
in code:
var config = TownSection.GetConfig();
foreach(TownProperty item in config.TownProperties) /// cycle is skipped
{
Console.WriteLine(item.Name);
Console.WriteLine(item.Distance);
}
What could be the problem?
Upvotes: 1
Views: 53
Reputation: 73442
I've changed couple of things in xml and that works.
1.Removed Section group tag
2.Added assembly name in section
tag's type attribute. In format (Full type name, Assembly name)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section
name="TownSection"
type="App.Configurations.TownSection, App.Configurations"
allowLocation="true"
allowDefinition="Everywhere" />
</configSections>
<TownSection>
<TownProperties>
<TownProperty Name="A" Distance="1.8"/>
<TownProperty Name="B" Distance="5.8"/>
</TownProperties>
</TownSection>
</configuration>
Upvotes: 3