style='font-size:14.0pt;font-family:"Courier New"'>Accessing Dynamic Properties
in ASP.NET using Configuration files
Introduction:
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.
Dynamic Properties:
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.
Lets look at a simple example of Web.config file.
Â
xml style='font-family:"Courier New";color:fuchsia'> version="1.0" encoding style='font-family:"Courier New";color:blue'>="utf-8" style='font-family:"Courier New";color:fuchsia'> ?>
<configuration style='font-family:"Courier New";color:blue'>>
style='font-family:"Courier New";color:blue'><system.web>
           Â
style='font-family:"Courier New";color:blue'> style='font-family:"Courier New";color:maroon'>system.web style='font-family:"Courier New";color:blue'>>
style='font-family:"Courier New";background:silver'>
          Â
           Â
style='font-family:"Courier New";background:silver'>
configuration style='font-family:"Courier New";color:blue'>>
All the configuration information we need can be given as key-value
pairs as shown above.
The
element, i.e.
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.
 Â
    Â
    Â
    Â
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 aelement.
Â
/>
 Â
    Â
    Â
    Â
Geek
 Â
The “configSections” tag has “section” tags which indicate
the custom sections present in the Web.config. Each “section” tag has two
attributes:
- name:Â The name of the custom section element.
- 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
{
    Â
style='color:gray'>///
style='color:gray'>
    Â
style='color:gray'>/// The obejct into which
the configuration info will be stored.
     style='color:gray'>/// style='color:gray'>
     style='color:blue'>public class SchoolStudent
     {
          Â
style='color:blue'>public string Name                 =
null;
          Â
style='color:blue'>public string RollNo         =
null;
          Â
style='color:blue'>public string
Description    = null;
           style='color:blue'>public override style='color:blue'>string ToString()
           {
style='font-family:"Courier New";color:blue'>return
style='font-family:"Courier New"'> "Name1::"+Name +" Rollno::"
+ RollNo + " Desc::"+ Description;
           }
  } style='color:green'>//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:
style='font-family:"Courier New";color:blue'>public
style='font-family:"Courier New"'> object
Create(object parent,object
configContext, XmlNode section)
style='font-family:"Courier New"'>
     This
method is passed 3 parameters by the ASP.NET runtime.
·
parent
The configuration settings in a corresponding parent configuration
section.
·
configContext
An
href="ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemwebconfigurationhttpconfigurationcontextclasstopic.htm">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
href="ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemxmlxmlnodeclasstopic.htm">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.   Â
style='font-family:"Courier New"'>
SchoolSectionHandler.cs
namespace Demo
{
    Â
style='color:gray'>///
style='color:gray'>
    Â
style='color:gray'>/// Summary description for
SchoolSectionHandler.
     style='color:gray'>/// style='color:gray'>
    Â
style='color:blue'>public class SchoolSectionHandler:IConfigurationSectionHandler
     {
           style='color:blue'>public const style='color:blue'>string SECTION_NAME="school";
style='font-family:"Courier New";color:green'>//implementation of the Create
method in //IConfigurationSectionHandler interface.
style='font-family:"Courier New";color:blue'>public
style='font-family:"Courier New"'> object
Create(object parent,object
configContext, XmlNode section)
           {
                 SchoolStudent
Student = new SchoolStudent();
                 style='color:blue'>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;
                 }
                 style='color:blue'>catch (Exception ex)
                 {
style='font-family:"Courier New";color:blue'>throw
style='font-family:"Courier New"'> new ConfigurationException("Error
while parsing configuration section.",ex,section);
                 }
          Â
                 style='color:blue'>return (object)Student;
           }
          Â
          Â
style='color:gray'>///
style='color:gray'>
style='font-family:"Courier New";color:gray'>/// The method which will return the populated ///SchoolStudent
object.
           style='color:gray'>/// style='color:gray'>
          Â
style='color:gray'>///
style='color:gray'>
Student object
          Â
style='color:blue'>public static SchoolStudent
getStudentInfo()
           {
style='font-family:"Courier New";color:blue'>return style='font-family:"Courier New"'> (SchoolStudent) ConfigurationSettings.GetConfig(SECTION_NAME);
           }
     } style='color:green'>//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:
style='font-family:"Courier New"'>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
style='color:blue'>void Page_Load(object
sender, System.EventArgs e)
{
style='font-family:"Courier New"'>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.
Thanks,
naren