14.13. Inspect and Change Your Web Application Configuration
Problem
You want to be able to modify some settings in your web application configuration file from within a web page.
Solution
Use the System.Configuration.WebConfigurationManager and System.Configuration.Configuration classes to access elements of your web application's configuration settings.
First, get a Configuration object for the configuration settings by calling the OpenWebConfiguration method on the WebConfigurationManager:
System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(@"/CSCBWeb");
Now, use the Configuration object to get a specific section of the settings. The following code retrieves the SqlCacheDependencySection of the configuration:
SqlCacheDependencySection sqlCacheDep =
(SqlCacheDependencySection)cfg.GetSection("system.web/caching/sqlCacheDependency");The SqlCacheDependencySection allows for creating a new SqlCacheDependencyDatabase and adding it to the configuration, and then saving the new configuration:
SqlCacheDependencyDatabase sqlCacheDb = new
SqlCacheDependencyDatabase("pubs","LocalPubs",9000000);
sqlCacheDep.Databases.Add(sqlCacheDb);
SqlCacheDependencyDatabase sqlCacheDb = new
SqlCacheDependencyDatabase("pubs","LocalPubs",9000000);
sqlCacheDep.Databases.Add(sqlCacheDb);This creates the following section in the web.config file for the application:
<sqlCacheDependency enabled="True" pollTime="60000"> <databases> <add name="pubs" connectionStringName="LocalPubs" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access