Click here to Skip to main content
12,629,886 members (30,759 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

7.2K views
12 bookmarked
Posted

How to Implement Custom configSection in your Configuration

, 13 Feb 2014 CPOL
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 - Enjoying Full Stack Development
Software Developer (Senior)
India India
 Innovative & tech-savvy software development professional with 6+ years of progressive experience specializing in object-oriented approach to enterprise commercial solution delivery utilizing latest technologies.
 Extensive background in Full Life-Cycle of Software Development and Automation process including requirements gathering, design, coding, unit testing, automation, debugging and maintenance.
 Comprehensive knowledge of Relational Database technology, queries and procedures.
 Excellent understanding of OOPS Concepts, Design Patterns & Best Coding Practices.
 Strong architectural knowledge of designing n-tier and n-layer solutions using Application blocks, Enterprise library, SOA, Software factories.
 Working experience of IIS administration and website deployment and configuration.

Strengths & Area of expertise include:

 Full Stack Enterprise Web Development
 Multi-Threaded Programming
 Object Oriented Development
 REST APIs Development & Integration
 Distributed/Client Server System
 TDD & Behavior Driven Development (BDD)
 Database Design & Development
 Exceptional Analytical & Quick Learning Skill
 Team & Client Communication
 Proactive & Organization Development Attitude

You may also be interested in...

Pro
Pro

Comments and Discussions

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

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web02 | 2.8.161205.3 | Last Updated 13 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia - Enjoying Full Stack Development
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid