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

By
Advertisement
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...

0 comments:

Post a Comment

Online Casino