Early, I have defined custom section in Console application and it works fine. But now I want to move some of functionality to the library. But, unfortunately, I cannot. Because now my custom section was defined as null.
The simple console application include next code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NotificationsConfigurationSection section
= NotificationsConfigurationSection.GetSection();
string emailAddress = section.EmailAddress;
Console.WriteLine(emailAddress);
Console.Read();
}
}
}
The file with custom configuration which is situated in the separate library include next code:
namespace ClassLibrary1
{
public class NotificationsConfigurationSection : ConfigurationSection
{
private const string configPath = "cSharpConsultant/notifications";
public static NotificationsConfigurationSection GetSection()
{
return (NotificationsConfigurationSection)
ConfigurationManager.GetSection(configPath);
}
/*This regular expression only accepts a valid email address. */
[RegexStringValidator(@"[\w._%+-]+@[\w.-]+\.\w{2,4}")]
/*Here, we register our configuration property with an attribute.
Note that the default value is required if we use
the property validation attributes, which will unfortunately
attempt to validate the initial blank value if a default isn't found*/
[ConfigurationProperty("emailAddress", DefaultValue = "[email protected]")]
public string EmailAddress
{
get { return (string)this["emailAddress"]; }
set { this["emailAddress"] = value; }
}
}
}
In app.config for the library I include next nodes:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="cSharpConsultant">
<section name="notifications"
type="ClassLibrary1.NotificationsConfigurationSection,
ClassLibrary1"/>
</sectionGroup>
</configSections>
<cSharpConsultant>
<notifications emailAddress="[email protected]"/>
</cSharpConsultant>
</configuration>
Could anybody help me?