Working with Special Members


Working with Special Members

In this section you are going to create a single class that illustrates the principles of this chapter.

You may have noticed from previous Web projects a file called web.config. The wizard adds this file to all Web projects. This file is in XML format and it contains settings that let you control how your application behaves or how the Web server behaves. For example, this file has a section called compilation that tells ASP.NET what language (VB or C#) to use by default if the individual Web pages don't specify a language. In addition, ASP.NET lets you add your own configuration information to this file. One good use for this file then is to store information to open a database.

You may recall from previous chapters that to open a database you need to build a connection string. The connection string looks like this: "server=home;database=food;uid=sa;pwd=;".

Suppose then that we would like our configuration file to look like the one in Figure 6.23 . To read the configuration information we may want to create a class as follows .

Figure 6.23 ASP.NET enables you to insert your own sections to the web.config file. The new section here is < dbConfig>; inside the section you add keys and values using the syntax < add key="whatever" value="whatever" />; the idea is you read from a section a key to obtain a value.
 <?xml version="1.0" encoding="utf-8" ?> <configuration>  <dbConfig>   <add key="server" value="Home" />   <add key="database" value="Food" />   </dbConfig>  

To write a class that reads configuration information:

  1. Declare a public class called ConfigInfo.

  2. Inherit the class from System.Configuration .NameValueFileSectionHandler. The reason it needs to be inherited from NameValueFileSectionHandler is that whenever you add a new section to the configuration file you need a class to be able to interpret the section. Later, we are going to tell the web.config file that this class is the handler for the new section.

  3. Add a private static variable called sCS to hold the connection string. Your class should look like the code in Figure 6.24 .

    Figure 6.24 The sCS will store the configuration string. The variable is static because the configuration string is the same no matter who reads it. So it doesn't make sense for the string to be dependent on a particular instance of the class.
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS; } 
  4. Add a public static property called ConnectionString with a get handler and no set. The get handler will first check if the configuration information has been read once. If it hasn't, then it will read it from the web.config file and set the value of the sCS variable. From then on any time ConnectionString is requested the class will just return the value stored in sCS ( Figure 6.25 shows the code to accomplish this).

    Figure 6.25 Having a class that lets you obtain configuration information by calling a property is easier than repeating the code required to read from the configuration file.
     public static string ConnectionString {    get    {       if (sCS == "")       {          System.Collections.          Specialized.NameValueCollection          nvh;          nvh = (System.Collections.          Specialized.NameValueCollection)          System.Web.HttpContext.          GetAppConfig("DBConfig");          sCS = "server=" + nvh["server"]                + ";database=" +                nvh["database"] +                ";uid=sa;pwd=;";       }       return sCS;    } } 
  5. Add the code in Figure 6.26 to the configuration file. This code tells ASP.NET that your new class will serve as a handler for the dbConfig section. Notice that the type="" portion of the code is supposed to contain the name of the class you created, comma, and the name of the project (or assembly) the class is in.

    Figure 6.26 Just adding a custom configuration section isn't enough. ASP.NET requires you to declare a section and provide a class that can read the section. That is why our class derives from NameValueFileSectionHandler.
     <?xml version="1.0" encoding="utf-8" ?> <configuration>  <configSections>   <section name="dbConfig"   type="ConfigDB, advancedmembers" />   </configSections>  <dbConfig>             <add key="server" value="Home" />             <add key="database" value="Food" />       </dbConfig> 

That's all there is to it. All you need to do now is call ConfigInfo.ConnectionString to retrieve the connection string. As an added step you may want to enhance the ConfigInfo class to read information from any custom section you define and from any key within the section. For that you'll need to add just a little more code.

To enhance the class to read from any custom configuration section:

  1. Declare a private string variable called iCS ( Figure 6.27 ). Notice that this is an instance variable and not a static variable.

    Figure 6.27 iCS is an instance variable. It is instance instead of static because each instance of the class will be able to store a different element for a particular section.
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS;  string iCS;  
  2. Add a constructor that takes two parameters, one string parameter for the config section you would like to read, and one string parameter for the element within the section you would like to read. Inside the constructor add the code in Figure 6.28 .

    Figure 6.28 The constructor code is similar to the code in the ConnectionString section except that is more generalized. The ConnectionString property always reads from dbConfig, and the constructor lets you read from any section.
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS;    string iCS;    public ConfigInfo(string config,                     string element)    {  System.Collections.   Specialized.NameValueCollection   nvh;   nvh = (System.Collections.   Specialized.NameValueCollection)   System.Web.HttpContext.   GetAppConfig(config);   iCS = nvh[element];  } 
  3. To retrieve the string it might be interesting to use operator overloading. Unfortunately there is no way to override the = operator, which would be the best to override in this case. Instead let's say that if someone uses the + operator in front of a ConfigDB variable, we will return the configuration information stored in iCS. Then a developer would write string name=+info; where info is a variable of type ConfigDB. The code to do this is in Figure 6.29 .

    Figure 6.29 There are two versions of the + operator. One version is the binary form, requiring two parameters, for example z= x + y . The other version is the unary form, illustrated here, for example: z = +x .
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS;    string iCS;    public ConfigInfo(string config,                     string element)    {       System.Collections.       Specialized.NameValueCollection       nvh;       nvh = (System.Collections.       Specialized.NameValueCollection)       System.Web.HttpContext.       GetAppConfig(config);       iCS = nvh[element];    }  public static string operator + (ConfigInfo   cdb)   {   return cdb.iCS;   }  
  4. Now we have a little problem. We've added a parameterized constructor, which means that the default constructor is gone. The problem with that is that for our class to be a handler ASP.NET requires a default constructor. Therefore, we need to add one to our class ( Figure 6.30 ).

    Figure 6.30 A default constructor is required because ASP.NET needs to create an instance of our class when it sees the custom configuration section.
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS;    string iCS;  public ConfigInfo()   {   }  public ConfigInfo(string config,                     string element)    { 

graphics/tick.gif Tip

  • Figure 6.31 contains all the code for the class put together.

    Figure 6.31 You should now have a generic class that you can use to either read a connection string or to store different elements from a particular section in the config file.
     public class ConfigInfo : System.Configuration. NameValueFileSectionHandler {    static string sCS;    string iCS;    public ConfigInfo()    {    }    public ConfigInfo(string config,                     string element)    {       System.Collections.       Specialized.NameValueCollection       nvh;       nvh = (System.Collections.       Specialized.NameValueCollection)       System.Web.HttpContext.       GetAppConfig(config);       iCS = nvh[element];    }    public static string ConnectionString    {       get       {         if (sCS == "")         {           System.Collections.           Specialized.           NameValueCollection           nvh;           nvh = (System.Collections.           Specialized. NameValueCollection)           System.Web.HttpContext.           GetAppConfig("DBConfig");           sCS = "server=" +           nvh["server"] + ";database=" +           nvh["database"] +           ";uid=sa;pwd=;";         }         return sCS;       }    }    public static string operator +    (ConfigInfo cdb)    {       return cdb.iCS;    } } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net