Estoy leyendo la configuración de 'App.config'. Acabo de descubrir cómo trabajar con ConfigurationSection
, ConfigurationElementCollection
y ConfigurationelElement
.¿Por qué no puedo convertir un atributo en un elemento anidado?
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="notificationSettingsGroup">
<section name="mailTemplates" type="Project.Lib.Configuration.MailTemplateSection, Project.Lib"
allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" requirePermission="false"/>
</sectionGroup>
</configSections>
<notificationSettingsGroup>
<mailTemplates>
<items>
<mailTemplate name="actionChain" subject="Subject bla-bla">
<body>Body bla-bla</body>
</mailTemplate>
</items>
</mailTemplates>
</notificationSettingsGroup>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
Mi código C#:
public class MailTemplateSection : ConfigurationSection
{
[ConfigurationProperty("items", IsDefaultCollection = false)]
public MailTemplateCollection MailTemplates
{
get { return (MailTemplateCollection)this["items"]; }
set { this["items"] = value; }
}
}
[ConfigurationCollection(typeof(MailTemplateElement), AddItemName = "mailTemplate",
CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class MailTemplateCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new MailTemplateElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MailTemplateElement) element).Name;
}
}
public class MailTemplateElement : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "action", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("subject", DefaultValue = "Subject", IsKey = false, IsRequired = true)]
public string Subject
{
get { return (string)this["subject"]; }
set { this["subject"] = value; }
}
[ConfigurationProperty("body", DefaultValue = "Body", IsKey = false, IsRequired = true)]
public string Body
{
get { return (string)this["body"]; }
set { this["body"] = value; }
}
}
Y el código de trabajo:
class Program
{
static void Main(string[] args)
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var mailTemplatesSection =
config.GetSection("notificationSettingsGroup/mailTemplates") as MailTemplateSection;
}
}
Todas las obras, cuando estoy declarando campos como atributos en XML. Pero cuando intento convertir los atributos en un elemento anidado, "Propiedad 'Cuerpo' no es un elemento de configuración" se produce el error.
¿Qué estoy haciendo mal?
Consulte esto [cómo utilizar el elemento de texto en lugar del atributo en la configuración personalizada] (http://stackoverflow.com/questions/5078758/can-i-add-a-textnode-instead-of-an-attribute-in -a-net-configurationsection) –