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)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw