Advertisment

Accessing Dynamic Properties in ASP.NET using Configuration files

author-image
CIOL Bureau
Updated On
New Update

Advertisment

Many a times, developers feel the need to store properties in external text

files, rather than hard -coding them in the application code. The advantages of

keeping these values in text files outside the application offer the following

benefits:

  • We can change a configuration property without having to recompile the

    code again.
  • These property values can be changed at deployment time.

For e.g. Storing the IP address of an m/c. Storing Locale specific

information.

Advertisment

Dynamic Properties:

Advertisment

Such properties are known as Dynamic properties and are read from the configuration files at runtime by the application.Almost all popular platforms/languages have some support for writing such

Configuration files.For e.g. we have *.ini files in Windows, *.properties files in Java, web.xml in Servlet Engines.In ASP.NET, configuration information can be easily stored and retrieved in

Web.config files.

Let's look at a simple example of Web.config file.

xml

version="1.0"

encoding="utf-8"

?>

Advertisment

<configuration>

<system.web>

system.web>

Advertisment

Advertisment

Advertisment

configuration>

All the configuration information we need can be given as key-value pairs

as shown above.

The tag is a child element of the root element, i.e.

tag.

Now this configuration file can easily be accessed in code with just a single

line of code.

String WhoIsCool = ConfigurationSettings.AppSettings<"CoolGeek ">;

The first time a configuration dynamic property is accessed, the application

reads the xml file and stores all the key-value pairs in a hashtable. So the

first time will consume a bit more time. This performance impact will be very

minor and often unnoticeable. For all future access, the values will be

retrieved from the in-memory hashtable, so the access is faster.

The advantage of this is that you need now worry about where to place the

code for accessing the dynamic properties. You can add the above method call

anywhere in your code.

Creating Custom XML configuration tags

Sometimes we may feel the need to have more flexible and richer configuration

settings, for e.g. the ability to define your own xml tags to build configurable

information.

For e.g. we can have a section as follows in our configuration file

consisting of custom XML tags.

Naren

91160

Cool Geek

To access this section, we need to create our own custom configuration

section handler. The handler must be a .NET Framework class that implements the IConfigurationSectionHandler

interface. The section handler interprets and processes the settings defined

in XML tags within a specific portion of a "Web.config" file and

returns an appropriate configuration object based on the configuration settings.

The configuration object that the handler class returns can be any data

structure; it is not limited to any base configuration class or configuration

format. So we can even return a custom object populated with all the values in

the xml file.

The following steps are to be followed to write custom configuration sections

in Web.config

  • Create a custom section as shown below in Web.config and declare that

    configuration section using a element.





   

/>



   






 

   





            Naren


            91160


            Cool Geek


       







   



The "configSections" tag has "section" tags which

indicate the custom sections present in the Web.config. Each "section"

tag has two attributes:

  1. name: The name of the custom section element.
  2. type: The name of the SectionHandler followed by the name of the assembly

    which contains the SectionHandler.
  • Create a custom Model object which would store the data from the config

    file. Here we would create a SchoolStudent.cs file. Here’s the code:

SchoolStudent.cs

namespace Demo

{

///



///

The obejct into which the configuration info will be stored.

///

public

class

SchoolStudent

{

    public

string

Name =
null;

    public

string

RollNo =
null;

    public

string

Description =
null;

    public

override

string

ToString()

    {

        return

"Name1::"+Name +" Rollno::" + RollNo + " Desc::"+

Description;

    }

    }//end of

SchoolStudent

  }

  • Code the ConfigurationSectionHandler. Our ConfigurationSectionHandler must

    implement the IConfigurationSectionHandler

    interface and override the

    "Create" method.

The signature of the method is as given below:






public object
Create(
object

parent,
object

configContext, XmlNode section)

This method is passed 3 parameters by the

ASP.NET runtime.

    • parent

The configuration settings in a corresponding parent configuration

section.

    • configContext

An HttpConfigurationContext

when Create is called from the ASP.NET configuration system.

Otherwise, this parameter is reserved and is a null reference (Nothing

in Visual Basic).

    • section

The XmlNode

that contains the configuration information from the configuration

file. Provides direct access to the XML contents of the configuration

section.

Here the last parameter is of great use to us. It directly gives us the

XmlNode object for the root element of our section. So we can easily get

access to all the child nodes and it’s contents. See the code below to see

how simple it is to retrieve information from XmlElements.

SchoolSectionHandler.cs

namespace Demo

{

///



///

Summary description for SchoolSectionHandler.

///

public

class

SchoolSectionHandler:IConfigurationSectionHandler

{

public

const

string

SECTION_NAME="school";

//implementation of the Create method in //IConfigurationSectionHandler

interface.

public object

Create(
object

parent,
object

configContext, XmlNode section)

{

SchoolStudent Student = new

SchoolStudent();

try

{

XmlNode StudentElement = section<"student">;

XmlElement Element = StudentElement<"name">;

Student.Name = Element.InnerText;

Element = StudentElement<"rollno">;

Student.RollNo = Element.InnerText;

Element = StudentElement<"description">;

Student.Description = Element.InnerText;

}

catch

(Exception ex)

{

throw new

ConfigurationException("Error while parsing configuration

section.",ex,section);

}

return

(
object)Student;

}

///



/// The

method which will return the populated ///SchoolStudent object.

///

///

The

School Student object

public

static

SchoolStudent getStudentInfo()

{

return (SchoolStudent)

ConfigurationSettings.GetConfig(SECTION_NAME);

}

}//end of

SchoolSectionHandler

}

The code above, retrieves the information from the XML and stores it in the

SchoolStudent object.

The signature of the "Create" method is defined to return an

"object" type, hence we need to type cast the return value into a

"SchoolStudent" object.

We can get the configuration setting of the custom section by calling:

object obj = ConfigurationSettings.GetConfig(SECTION_NAME);

where SECTION_NAME is

the string containing the "section" xml element name.

We can now call the static method getStudentInfo()

of SchoolSectionHandler class
inside our

"code-behind" aspx.cs file.

Here’s a snippet of a code-behind file:

private void

Page_Load(
object

sender, System.EventArgs e)

{

SchoolStudent Student = SchoolSectionHandler.getStudentInfo();

Trace.Write(">>> "+Student);

}

Enable the Trace on the ASPX page and see the output on the browser. It would

be something like this:

Trace Information

Category

Message

From First(s)

From Last(s)

aspx.page

Begin Init

   

aspx.page

End Init

0.001996

0.001996

 

>>> Name1::Naren Rollno::91160 Desc::Cool Geek

0.013930

0.011934

aspx.page

Begin PreRender

0.014082

0.000152

aspx.page

End PreRender

0.014136

0.000054

aspx.page

Begin SaveViewState

0.014948

0.000812

aspx.page

End SaveViewState

0.016565

0.001617

aspx.page

Begin Render

0.016650

0.000085

aspx.page

End Render

0.075696

0.059045

Conclusion:

As we have seen it is very simple to add and retrieve configuration

information from Web.config file. The most wonderful thing about keeping dynamic

properties in Web.config is that you can change them even when the application

is running and the new values will automatically be taken for the next request.

So no need to restart or unload the application.

About the author:

Narendra is an architect specializing in Enterprise Applications using J2EE and .NET technologies. He is a Java evangelist and also a SUN certified Java Programmer. Currently working in Wipro Technologies and involved in the implementation of J2EE/.NET projects. Other areas of interest include Web Services, Design Patterns, J2ME . Been a active freelance Java trainer for corporates and training institutes. Can be reached at naren@sulekha.com

tech-news