As an example, let’s examine this minimal web.config with an appSetting entry to hold our connection string:

    1 <?xml version=”1.0″ encoding=”utf-8″ ?>

    2 <configuration>  

    3 

    4   <system.web>

    5    <compilation defaultLanguage=”c#” debug=”true” />

    6  </system.web>

    7 

    8   <appSettings>

    9    <add key=”ConnectionInfo” value=”server=(local);database=Northwind;Integrated Security=SSPI” />

   10   </appSettings>

   11 

   12 </configuration>

To read the key we use the ConfigurationSettings class from the System.Configuration namespace, as shown below.

   12 private void Page_Load(object sender, EventArgs e)

   13 {

   14    string connectionInfo = ConfigurationSettings.AppSettings[“ConnectionInfo”];

   15    using(SqlConnection connection = new SqlConnection(connectionInfo))

   16    {

   17       connection.Open();

   18 

   19       // perform work with connection

   20 

   21    }        

   22 }

— ถ้าจะใช้ ConnectionStrings  ———————–

/*<?xml version=”1.0″?><configuration>

<connectionStrings>

<add name=”Northwind”

connectionString=”server=localhost;uid=sa;pwd=thiru;

database=northwind”>

</add>

</connectionStrings>

*

<system.web>

</system.web>
</configuration>*/

public string cnStr = System.Configuration.ConfigurationManager.ConnectionStrings[“connectionStrings”].ToString();

——————————————————————-

Encapsulation

Let’s abstract away the source of the connection string using a class with a static property.

    1 using System.Configuration;

    2 

    3 namespace aspnet.config

    4 {

    5    public class Configuration

    6    {

    7       public static string ConnectionInfo

    8       {

    9          get

   10          {

   11             return ConfigurationSettings.AppSettings[“ConnectionInfo”];

   12          }

   13 

   14       }

   15    }

   16 }

Now our Page_Load method looks like the following.

   11 private void Page_Load(object sender, EventArgs e)

   12 {

   13    using(SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))

   14    {

   15       connection.Open();

   16 

   17       // perform work with connection

   18 

   19    }        

   20 }

The changes we made to the above code were relatively small – but powerful. Now the Page_Load function doesn’t know where the connection string comes from. We could easily change the ConnectionInfo property to retrieve the string from a different source without modifying any other code in the application. We also no longer have to remember the key string and hard code the string at various points in the application. Instead, we can utilize Visual Studio Intellisense when accessing the Configuration class to find the setting we need. The key value only appears once – inside the ConnectionInfo property – so we could again change the key name in the web.config and have only one line of code to update.