Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

How to Store Custom Objects in web.config

Rate me:
Please Sign up or sign in to vote.
4.97/5 (9 votes)
20 Apr 2011CPOL2 min read 42.4K   18   10
How to store custom objects in web.config

In this post, I am going to discuss about web.config. Normally in our daily life, we used to have some data in appSettings section of web.config and read it when required. That is in string form. But there are lot more than this. We can update the data in web.config programmatically as well.

Now another main point is, we can store some object of custom type in web.config as well, which we normally don’t do. But this can be very useful in several scenarios.

Has anyone tried to update some value or add some value in web.config? We’ll have a brief discussion about this.

First, this is very common to have some constant data at appSettings section of web.config and read it whenever required. So how to read this (for beginners).

XML
//The data is stored in web.config as
<appSettings>
		<add key="WelcomeMessage" 
		value="Hello All, Welcome to my Website." />
</appSettings>

// To read it
string message = ConfigurationManager.AppSettings["WelcomeMessage"];

Now if we want to update some data of appSettings programmatically, one can do it like this.

C#
//Update header at config
        Configuration config = 
        WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings["WelcomeMessage"].Value = 
        "Hello All, Welcome to my updated site.";
        config.Save();

Now what do you do if you want to add some data in appSettings. You can add some app.config data as below:

C#
//Update header at config
        Configuration config = 
        WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings.Add("ErrorMessage", 
          "An error has been occurred during processing this request.");
        config.Save();

The above code is adding one new key value pair in web.config file. Now this can be read anywhere in the application.

Now, the question is, can we store some custom data at config?

Yes…

We can store some object. Let’s see how.

I created a sample example. In this example, I saved an object of my custom class NewError in web.config file and updated it whenever required.

To do this, follow the below steps:

  1. Create a Class that inherits from ConfigurationSection (it is available under namespace System.Configuration). Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let’s see the NewError class:
    C#
    public class NewError:ConfigurationSection
    {
        [ConfigurationProperty ("Id",IsRequired = true)]
        public string ErrorId {
            get { return (string)this["Id"]; }
            set { this["Id"] = value; }
        }
        [ConfigurationProperty("Message", IsRequired = false)]
        public string Message {
            get { return (string)this["Message"]; }
            set { this["Message"] = value; }
        }
        [ConfigurationProperty("RedirectURL", IsRequired = false)]
        public string RedirectionPage
        {
            get { return (string)this["RedirectURL"]; }
            set { this["RedirectURL"] = value; }
        }
        [ConfigurationProperty("MailId", IsRequired = false)]
        public string EmailId
        {
            get { return (string)this["MailId"]; }
            set { this["MailId"] = value; }
        }
        [ConfigurationProperty("DateAdded", IsRequired = false)]
        public DateTime DateAdded
        {
            get { return (DateTime)this["DateAdded"]; }
            set { this["DateAdded"] = value; }
        }
    }

    As you can see, every property has attribute ConfigurationProperty with some value. As you can see, the property ErrorId has attribute:

    C#
    [ConfigurationProperty ("Id",IsRequired = true)]
    

    it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
    Now if you’ll see the property closely, it is a bit different.

    C#
    public string ErrorId {
    get { return (string)this["Id"]; }
    set { this["Id"] = value; }
    }

    Here the value is saved as the key “id”, that is mapped with web.config file.

  2. Now you are required to add/register a section in the section group to tell the web.config that you are going to have this kind of data. This must be in <configSections/> and will be as:
    XML
    <section name="errorList"  type="NewError" allowLocation="true"
         allowDefinition="Everywhere"/>
  3. Now one can add that object in your config file directly as:
    XML
    <errorList Id="1" Message="ErrorMessage" 
    RedirectURL="www.google.com" MailId="xyz@hotmail.com" >
    </errorList>
  4. And to read it at your page. Read it as follows:
    C#
    NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList");

    And also a new object can be saved programmatically as:

    C#
    NewError objNewError = new NewError()
           {
             RedirectionPage="www.rediff.com",
             Message = "New Message",
             ErrorId="0",
             DateAdded= DateTime.Now.Date
           };
           Configuration config =
               WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    
           config.Sections.Add("errorList", objNewError);
           config.Save();
    

Even one can add a custom group and have some custom elements in this section.

ASP.NET provides very powerful APIs to read/edit the web.config file easily.

Hope you all must have enjoyed this, and I will appreciate your feedback.

Thanks!

License

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


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
QuestionMy Vote of 5 Pin
Mohammad A. Amer6-Jun-15 21:54
professionalMohammad A. Amer6-Jun-15 21:54 
QuestionSilverlight? Pin
Horia Tudosie5-Sep-12 0:58
Horia Tudosie5-Sep-12 0:58 
How can I apply this technique in Silverlight?
Horia Tudosie

GeneralMy vote of 5 Pin
astodola26-Apr-11 4:37
astodola26-Apr-11 4:37 
GeneralRe: My vote of 5 Pin
Brij26-Apr-11 8:29
mentorBrij26-Apr-11 8:29 
GeneralMy Vote of 5 Pin
RaviRanjanKr21-Apr-11 6:09
professionalRaviRanjanKr21-Apr-11 6:09 
GeneralRe: My Vote of 5 Pin
Brij21-Apr-11 7:27
mentorBrij21-Apr-11 7:27 
GeneralMy vote of 5 Pin
Abhijit Jana20-Apr-11 21:20
professionalAbhijit Jana20-Apr-11 21:20 
GeneralRe: My vote of 5 Pin
Brij20-Apr-11 22:38
mentorBrij20-Apr-11 22:38 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»20-Apr-11 20:01
professionalKunal Chowdhury «IN»20-Apr-11 20:01 
GeneralRe: My vote of 5 Pin
Brij20-Apr-11 22:37
mentorBrij20-Apr-11 22:37 

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.