DrewB
DrewB

Reputation: 1536

Problems with custom config section

I am trying to make a fairly simple custom configuration section. My class is:

namespace NetCenterUserImport
{
    public class ExcludedUserList : ConfigurationSection
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)base["name"]; }
        }

        [ConfigurationProperty("excludedUser")]
        public ExcludedUser ExcludedUser
        {
            get { return (ExcludedUser)base["excludedUser"]; }
        }

        [ConfigurationProperty("excludedUsers")]
        public ExcludedUserCollection ExcludedUsers
        {
            get { return (ExcludedUserCollection)base["excludedUsers"]; }
        }
   }

   [ConfigurationCollection(typeof(ExcludedUser), AddItemName = "add")]
   public class ExcludedUserCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ExcludedUserCollection();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ExcludedUser)element).UserName;
        }
    }

    public class ExcludedUser : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string UserName
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }
    }
}

My app.config is:

  <excludedUserList name="test">
<excludedUser name="Hello" />
<excludedUsers>
  <add name="myUser" />
</excludedUsers>

When I attempt to get the custom config section using:

var excludedUsers = ConfigurationManager.GetSection("excludedUserList");

I get an exception saying

"Unrecognized attribute 'name'."

I'm sure I'm missing something simple, but I've looked at a dozen examples and answers on here and can't seem to find where I'm going wrong.

Upvotes: 2

Views: 88

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6957

In ExcludedUserCollection.CreateNewElement method you are creating a ExcludedUserCollection instance, it should be a single element such as:

protected override ConfigurationElement CreateNewElement()
{
    return new ExcludedUser();
}

Changing the method as above worked for me.

Upvotes: 2

Related Questions