Click here to Skip to main content
11,581,186 members (65,215 online)
Click here to Skip to main content

Tagged as

How to Implement Custom configSection in your Configuration

, 13 Feb 2014 CPOL 5.6K 11
Rate this:
Please Sign up or sign in to vote.
Details about how to implement custom configSection in your application

Introduction

Here, I will provide the details about how to implement custom configSection in your application.

Suppose you want to create a configSection for your custom membership implementation as below:

  <memberships>
    <member username="test" password="testpassword" role="client" />
    <member username="hostuser" password="private" role="client,host" />
  </memberships>

For this, you need to create the required classes as below.

MembershipElement.cs

    public class MembershipElement : ConfigurationElement
    {
        [ConfigurationProperty("username", IsRequired = true, IsKey = true)]
        public string Username
        {
            get { return base["username"] as string; }
            set { base["username"] = value; }
        }

        [ConfigurationProperty("password", IsRequired = true, IsKey = false)]
        public string Password
        {
            get { return base["password"] as string; }
            set { base["password"] = value; }
        }

        [ConfigurationProperty("role")]
        public string Role
        {
            get { return base["role"] as string; }
            set { base["role"] = value; }
        }
    }

MembershipCollection.cs

    public class MembershipCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new MembershipElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MembershipElement)element).Username;
        }

        protected override string ElementName
        {
            get
            {
                return "member";
            }
        }

        protected override bool IsElementName(string elementName)
        {
            return !String.IsNullOrEmpty(elementName) && elementName == "member";
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }

        public MembershipElement this[int index]
        {
            get
            {
                return base.BaseGet(index) as MembershipElement;
            }
        }

        public MembershipElement this[string key]
        {
            get
            {
                return base.BaseGet(key) as MembershipElement;
            }
        }

    }

MembershipConfigurationHandler.cs

    public class MembershipConfigurationHandler : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection = true, IsKey = false, IsRequired = true)]
        public MembershipCollection Members
        {
            get
            {
                return base[""] as MembershipCollection;
            }

            set
            {
                base[""] = value;
            }
        }
    }

Now you are ready to use your custom configSection in your application. Your application’s config file will have the elements as below:

  <configSections>
    <section name="memberships" type="Authentication.Configuration.MembershipConfigurationHandler, Authentication"/>
  </configSections>
  <memberships>
    <member username="test" password="testpassword" role="client" />
    <member username="hostuser" password="private" role="client,host" />
  </memberships>

I have a created a helper class to access the member details with ease.

MembershipProvider.cs

    public static class MembershipProvider
    {
        public static MembershipElement GetMember(string userName)
        {
            var memberships = ConfigurationManager.GetSection("memberships") as MembershipConfigurationHandler;

            if(memberships == null || memberships.Members == null || memberships.Members.Count < 1)
                return null;

            return memberships.Members[userName];
        }

        public static MembershipElement ValidateUser(string userName, string password)
        {
            var member = GetMember(userName);
            if (member != null && member.Password.Equals(password))
                return member;                
            return null;
        }
    }

You can use this provider to validate the member or get the member details. I have used this provider in my application to authenticate the member and set the roles in current thread.

CustomUsernamePasswordValidator.cs

    public class CustomUsernamePasswordValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            var member = MembershipProvider.ValidateUser(userName, password);

            if(member == null)
                throw new FaultException<SecurityTokenException>
                (new SecurityTokenException("Authentication failed"),
                "Unknown Username or Password");

            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), 
            member.Role.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
        }
    }

I have used this validator in WCF service application to validate using custom username and password. I will explain that in other post.

Appreciate your query and suggestions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adarsh Chaurasia (Learner|Consultant|Mentor|Tech
Software Developer (Senior)
India India
I have 5.5+ years of experience in SaaS, SOA based Enterprise Web Application design and development using Microsoft technology stack. I have mostly worked on Business layer, Data access layer, WCF, Entity Framework, Microsoft Application Blocks, Search engines, APIs integration, Third party APIs/Product Research & Development.

I am a huge fan of Design Patterns. I also work as Software Consultant. I read/write blogs, help and learn from other developers.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
Dave Kreskowiak26-Mar-14 3:46
mvpDave Kreskowiak26-Mar-14 3:46 
QuestionMy Vote of 5. Pin
Pankaj Kolhe12-Mar-14 17:57
memberPankaj Kolhe12-Mar-14 17:57 
GeneralMy vote of 5 Pin
David Days14-Feb-14 11:10
memberDavid Days14-Feb-14 11:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 13 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia (Learner|Consultant|Mentor|Tech
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid