views:

19

answers:

1

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?

A: 

Do you mean that your app.config was in the project for the library?

The configuration files must be in the same project as your executable. The definition for the custom section can remain in the library, but the configuration file itself must be in the same project as the one you are intending to run.

In your case, it should be in the same project as ConsoleApplication1 rather than ClassLibrary1

Jonn
Actually, you are right. The same app.config should be in Console application rather than in ClassLibrary. Thank you!
apros