Skip to main content

How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net

In this tutorial i am going to explain about how to add Custom objects in configuration file(web.config) and access it in the pages. Custom objects can be created by creating the class that inherit From ConfigurationSection (It is available under namespace System.Configuration ).

In my previous article i have explained about Create Simple Mathmatical Captcha In ASP.Net , Visual Studio Keyboard Shortcuts , How To get data from WEB API , How To Create Your First WEB API Project, Check Container Exists In Azure Blob , Convert Datatable To Json Data Array and many articles in C#.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.

It is commonly known fact that configuration file(web.config and app.config) is used to store the application specific constants instead of hard coding it inside the application. So that in future if we need to do the changes in this constants we can do it easily without the need for rebuilding and deploying the entire application. Now we will see how we can create the custom attribute that inherits from ConfigurationSection and add it to the configuration file.

Open the visual studio and go to the file menu and select new website as shown in the figure.


Step 1 of How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net

And then under C# select Empty Website template and select the suitable folder and name the project. Here i named it as CustomObjectsInWebConfig. The same is shown in the figure.
Step 2 of How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net
After creating the project right click the project then Add --> Add New Item --> Class as shown in the below figure.
Step 3 of How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net

Now name the class as MailDetails.cs. Then open the MailDetails.cs if it is not already open and then inherit it from ConfigurationSection class which is available under System.Configuration namespace( You have to include System.Configuration namespace if it is not already there). And then all the properties in the Class should have an attribute ConfigurationProperty and some other attributes like attributename, Isrequired,IsKey etc.. This name is directly mapped to web.config file. Below is the class which i have created.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Include it if it is not already there
using System.Configuration;

/// <summary>
/// Summary description for MailDetails
/// </summary>

namespace CustomObjectsInWebConfig
{
    public class MailDetails : ConfigurationSection
    {
        private static MailDetails mailDetails
     = ConfigurationManager.GetSection("mailDetail") as MailDetails;

        public static MailDetails Details
        {
            get
            {
                return mailDetails;
            }
        }
        //Empty Constructor
        public MailDetails()
        {

        }
        [ConfigurationProperty("Server", IsRequired = true)]
        public string SMTPServer
        {
            get { return (string)this["Server"]; }
            set { this["Server"] = value; }
        }
        [ConfigurationProperty("Username", IsRequired = true)]
        public string Username
        {
            get { return (string)this["Username"]; }
            set { this["Username"] = value; }
        }
        [ConfigurationProperty("Password", IsRequired = true)]
        public string Password
        {
            get { return (string)this["Password"]; }
            set { this["Password"] = value; }
        }
        [ConfigurationProperty("Port", IsRequired = true)]
        public string SMTPPort
        {
            get { return (string)this["Port"]; }
            set { this["Port"] = value; }
        }
    }
}

I have also added a static property named Details for convenience of reading the custom attribute values from the config file.

Now we have to add/register a section in the web.config to tell the configuration file that we are going to use this kind of data. And that must be inside configSections tag of the configuration file. Once you registed then you can add your custom attribute anywhere in the web.config file. Note that you should have only one section(Custom attribute section) other wise you will encounter the below mentioned error.

For having the multiple combinations of Custom objects in web.config we must follow different implementation. I will explain it separately in my next blog post. Below is the entire web.config file code.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="mailDetail"  type="CustomObjectsInWebConfig.MailDetails" allowLocation="true"
     allowDefinition="Everywhere"/>
  </configSections>
  <mailDetail Server="127.0.0.1" Username="MailserverUsername" Password="MailserverPassword" Port="MailserverPort" ></mailDetail>
  <system.web>
    <compilation debug="true" targetFramework="4.5.3" />
    <httpRuntime targetFramework="4.5.3" />
  </system.web>
</configuration>

Now to read the custom attribute values from the web.config i have added a file named Default.aspx and added the below html markup in the file.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Custom Attributes In Web.Config</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 800px;">
    <div>
        <h2>Custom Attributes In Web.Config</h2>
        <table style="border-collapse: collapse;" border="1">
            <tr>
                <th width="150">Field</th>
                <th width="150">Value</th>
            </tr>
            <tr>
                <td>SMTP Server</td>
                <td>
                    <asp:Label ID="lblSMTPServer" runat="server" />
                </td>
            </tr>
            <tr>
                <td>UserName</td>
                <td>
                    <asp:Label ID="lblUserName" runat="server" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <asp:Label ID="lblPassword" runat="server" /></td>
            </tr>
            <tr>
                <td>SMTP Port</td>
                <td>
                    <asp:Label ID="lblSMTPPort" runat="server" /></td>
            </tr>
        </table>
    </div>
</div>
</form>
</body>
</html>

The markup contains four labels to display the 4 attributes available. The code behind file is below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using CustomObjectsInWebConfig;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblSMTPServer.Text = MailDetails.Details.SMTPServer;
        lblUserName.Text = MailDetails.Details.Username;
        lblPassword.Text = MailDetails.Details.Password;
        lblSMTPPort.Text = MailDetails.Details.SMTPPort;
    }
}

Now if you run the project the output will look like below..
Output of How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net

Sourcecode:

Source code of How to Add Store Custom Objects in Configuration File(web.config & app.config) in ASP.Net & C#.Net
If you like this article then share with your friends and comment your valuable feedback.. Happy coding..

You May Also Like...

Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...