Im having problems accessing a proprties collection attribute “name” for my pages element. Pages has a collection of page field that have attributes Could someone have a look at my code and show me how have a collection of pages with a name attribute on each one and access its value. At the moment my code return nothing but the page loads without any errors so I don’t know whats going on and how to get the attribute field.
<configSections>
<sectionGroup name="site" type="MyProject.Configuration.Site">
<section name="pages" type="MyProject.Configuration.Pages"/>
</sectionGroup>
</configSections>
<site>
<pages>
<page name="test">
</page>
</pages>
</site>
Classes:
public class Site : ConfigurationSection
{
[ConfigurationProperty("pages")]
[ConfigurationCollection(typeof(PageCollection), AddItemName="page")]
public PageCollection Pages
{
get
{
return base["pages"] as PageCollection;
}
}
}
public class PageCollection : ConfigurationElementCollection
{
public PageCollection()
{
PageElement element = (PageElement)CreateNewElement();
BaseAdd(element); // doesn't work here does if i remove it
}
protected override ConfigurationElement CreateNewElement()
{
return new PageElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((PageElement)element).Name;
}
public PageElement this[int index]
{
get
{
return (PageElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
}
public class PageElement : ConfigurationElement
{
public PageElement() { }
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get
{
return (string)base["name"];
}
set
{
base["name"] = value;
}
}
}
Code to access my attribute:
Pages pageSettings = ConfigurationManager.GetSection("site/pages") as Pages;
lblPage.Text = pageSettings.Page[0].Name;
The issue is that your section element should be site, not pages:
Update
It turns out that there were a few issues that needed to be addressed:
1) The web.config needs to be changed to be a section instead of a sectiongroup and the pages element should be removed:
2) The Site class needs to be modified:
3) The PageCollection constructor needs to have its code removed.
4) The name property needs to be removed from the PageCollection, or at least marked as not required.
5) The call to retrieve the settings is now:
I have tested this and verified that these changes will successfully read in the config.