TheBeerHouse读书笔记(二)
Storing Connection Strings and Other Settings (web config)-Custom configuration sections
Connection String
<connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLExpress; Integrated Security=True;User Instance=True; AttachDBFilename=|DataDirectory|TheBeerHouse.mdf" /> </connectionStrings>
Removing a connection string element means to remove a reference to an inherited connection string from the collection of connections strings. If there is an inherited connectionstring (not defined in current web.config, for example may be inherited from machine.config) named LocalSqlServer, it will no longer exist in current context. But this will not effect the original connectionstring (LocalSqlServer in machine.config in this case).
Configuration settings
public class SiteSection : ConfigurationSection { [ConfigurationProperty("title", DefaultValue="Sample Title")] public string Title { get { return (string)base["title"]; } set { base["title"] = value; } } [ConfigurationProperty("homePage", IsRequired=true)] public HomePageElement HomePage { get { return (HomePageElement)base["homePage"]; } } } public class HomePageElement : ConfigurationElement { [ConfigurationProperty("showAdBanners", DefaultValue="true")] public bool ShowAdBanners { get { return (bool)base["showAdBanners "]; } set { base["showAdBanners "] = value; } } } Web.config <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <configSections> <section name="site" type="Company.Project.SiteSection, __code"/> </configSections> <site title="Some nice title for the site"> <homePage showAdBanners="false" /> </site> <!-- other configuration sections... --> </configuration>
To read SiteSection site = (SiteSection)WebConfigurationManager.GetSection("site"); string title = site.Title; bool showAdBanners = site.HomePage.ShowAdBanners;