C# Custom Configuration

Hi,

I wanted to implement Custom configuration in c# project using the following classes

ConfigurationSection
ConfigurationElement
ConfigurationElementCollection

Here is how i implemented the class

    public class TestConfigurationSettings : ConfigurationSection
    {
        public const string SectionName = "TestConfigurationSettings";
        private const string TestCollectionName = "Counters";

        [ConfigurationProperty(TestCollectionName)]
        [ConfigurationCollection(typeof(CounterCollection), AddItemName = "Counter")]
        public CounterCollection Items
        {
            get { return (CounterCollection)base[TestCollectionName]; }
        }
    }

    public class CounterCollection : ConfigurationElementCollection
    {
        public void Counter(TestElement element)
        {
            BaseAdd(element);
        }

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

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TestElement)element).Name;
        }
    }

    public class TestElement : ConfigurationElement
    {
        [ConfigurationProperty("Name", IsRequired = true)]
        public string Name
        {
            get { return (string)this["Name"]; }
            set { this["Name"] = value; }
        }

        [ConfigurationProperty("ID", IsRequired = true)]
        public string ClientCode
        {
            get { return (string)this["ID"]; }
            set { this["ID"] = value; }
        }

        [ConfigurationProperty("Port", IsRequired = true)]
        public string AppPort
        {
            get { return (string)this["Port"]; }
            set { this["Port"] = value; }
        }
    }
	 

Open in new window


App.Config
    
	<configuration>
  <configSections>
    <section name ="MyConfig" type="TestConfigurationSettings, TestProject"/>
  </configSections>
  <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
    </startup>
  <MyConfig>
    <Counters>
      <TestElement Name="Test" ID="1280" Port="8000" />
    </Counters>
  </MyConfig>
</configuration>

Open in new window


Program.cs for reading the config values
  

            var testConfiguration = (TestConfigurationSettings) ConfigurationManager.GetSection("MyConfig");
            var counters = testConfiguration.Items.Cast<ProviderSettings>().ToList();
            foreach (var a in testConfiguration.Items)
            {
                //how to read Name, ID and Port here
            }

Open in new window


Inside the foreach loop i am not able to get ID Name and Port, Did i do anything wrong with setting up Config code or app.config

Please help me how can i read Name, ID and Port in the main program
SriAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Most likely you have mis-cast the elements in your collection, instead of casting as ProviderSettings, the counters should be cast as TestElement; e.g. -
// Not this
// var counters = testConfiguration.Items.Cast<ProviderSettings>().ToList();

// Should be this
var counters = testConfiguration.Items.Cast<TestElement>().ToList();
foreach (var a in counters)

Open in new window

 Proof of concept -

App.config -
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name ="MyConfigurationSection" type="EE_Q29095712.MyConfigurationSection, EE_Q29095712"/>
  </configSections>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <MyConfigurationSection>
    <MyElementCollection>
      <MyElement Name="Test" ClientCode="1280" AppPort="8000" />
    </MyElementCollection>
  </MyConfigurationSection>
</configuration>

Open in new window

Program.cs -
using System;
using System.Configuration;
using System.Linq;

namespace EE_Q29095712
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = (MyConfigurationSection)ConfigurationManager.GetSection(nameof(MyConfigurationSection));
            var elements = test.MyElements.Cast<MyElement>().ToList();
            foreach (var element in elements)
            {
                Console.WriteLine(element);
            }
            Console.ReadLine();
        }
    }

    public class MyConfigurationSection : ConfigurationSection
    {
        const string CollectionName = nameof(MyElementCollection);

        [ConfigurationProperty(CollectionName), ConfigurationCollection(typeof(MyElementCollection), AddItemName = nameof(MyElement))]
        public MyElementCollection MyElements { get { return (MyElementCollection)base[CollectionName]; } }
    }

    public class MyElementCollection : ConfigurationElementCollection
    {
        public void MyElement(MyElement element)
        {
            BaseAdd(element);
        }

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

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MyElement)element).Name;
        }
    }

    public class MyElement : ConfigurationElement
    {
        [ConfigurationProperty(nameof(Name), IsRequired = true)]
        public string Name
        {
            get { return (string)this[nameof(Name)]; }
            set { this[nameof(Name)] = value; }
        }

        [ConfigurationProperty(nameof(ClientCode), IsRequired = true)]
        public string ClientCode
        {
            get { return (string)this[nameof(ClientCode)]; }
            set { this[nameof(ClientCode)] = value; }
        }

        [ConfigurationProperty(nameof(AppPort), IsRequired = true)]
        public string AppPort
        {
            get { return (string)this[nameof(AppPort)]; }
            set { this[nameof(AppPort)] = value; }
        }

        public override string ToString()
        {
            return $"{{ Name: {Name}, ClientCode: {ClientCode}, AppPort: {AppPort} }}";
        }
    }
}

Open in new window

Produces the following output -Capture.PNG-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SriAuthor Commented:
This helped me
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.