ConfigurationSettings.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. //
  2. // System.Configuration.ConfigurationSettings.cs
  3. //
  4. // Author:
  5. // Christopher Podurgiel ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Eric Lindvall ([email protected])
  8. //
  9. // (c) Christopher Podurgiel
  10. // (c) 2002 Ximian, Inc. (http://www.ximian.com)
  11. // (c) 2003 Novell, Inc. (http://www.novell.com)
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Collections;
  35. using System.Collections.Specialized;
  36. using System.IO;
  37. using System.Runtime.CompilerServices;
  38. #if (XML_DEP)
  39. using System.Xml;
  40. using System.Xml.XPath;
  41. #endif
  42. namespace System.Configuration
  43. {
  44. public sealed class ConfigurationSettings
  45. {
  46. static IConfigurationSystem config = DefaultConfig.GetInstance ();
  47. static object lockobj = new object ();
  48. private ConfigurationSettings ()
  49. {
  50. }
  51. public static object GetConfig (string sectionName)
  52. {
  53. return config.GetConfig (sectionName);
  54. }
  55. #if NET_2_0
  56. [Obsolete ("This property is obsolete. Please use System.Configuration.ConfigurationManager.AppSettings")]
  57. #endif
  58. public static NameValueCollection AppSettings
  59. {
  60. get {
  61. object appSettings = GetConfig ("appSettings");
  62. if (appSettings == null)
  63. appSettings = new NameValueCollection ();
  64. return (NameValueCollection) appSettings;
  65. }
  66. }
  67. // Invoked from System.Web
  68. static IConfigurationSystem ChangeConfigurationSystem (IConfigurationSystem newSystem)
  69. {
  70. if (newSystem == null)
  71. throw new ArgumentNullException ("newSystem");
  72. lock (lockobj) {
  73. IConfigurationSystem old = config;
  74. config = newSystem;
  75. return old;
  76. }
  77. }
  78. }
  79. //
  80. // class DefaultConfig: read configuration from machine.config file and application
  81. // config file if available.
  82. //
  83. class DefaultConfig : IConfigurationSystem
  84. {
  85. static readonly DefaultConfig instance = new DefaultConfig ();
  86. ConfigurationData config;
  87. private DefaultConfig ()
  88. {
  89. }
  90. public static DefaultConfig GetInstance ()
  91. {
  92. return instance;
  93. }
  94. #if NET_2_0
  95. [Obsolete ("This method is obsolete. Please use System.Configuration.ConfigurationManager.GetConfig")]
  96. #endif
  97. public object GetConfig (string sectionName)
  98. {
  99. Init ();
  100. return config.GetConfig (sectionName);
  101. }
  102. public void Init ()
  103. {
  104. lock (this) {
  105. if (config != null)
  106. return;
  107. ConfigurationData data = new ConfigurationData ();
  108. if (!data.Load (GetMachineConfigPath ()))
  109. throw new ConfigurationException ("Cannot find " + GetMachineConfigPath ());
  110. string appfile = GetAppConfigPath ();
  111. if (appfile == null) {
  112. config = data;
  113. return;
  114. }
  115. ConfigurationData appData = new ConfigurationData (data);
  116. if (appData.Load (appfile))
  117. config = appData;
  118. else
  119. config = data;
  120. }
  121. }
  122. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  123. extern private static string get_machine_config_path ();
  124. internal static string GetMachineConfigPath ()
  125. {
  126. return get_machine_config_path ();
  127. }
  128. private static string GetAppConfigPath ()
  129. {
  130. AppDomainSetup currentInfo = AppDomain.CurrentDomain.SetupInformation;
  131. string configFile = currentInfo.ConfigurationFile;
  132. if (configFile == null || configFile.Length == 0)
  133. return null;
  134. return configFile;
  135. }
  136. }
  137. enum AllowDefinition
  138. {
  139. Everywhere,
  140. MachineOnly,
  141. MachineToApplication
  142. }
  143. class SectionData
  144. {
  145. public readonly string SectionName;
  146. public readonly string TypeName;
  147. public readonly bool AllowLocation;
  148. public readonly AllowDefinition AllowDefinition;
  149. public string FileName;
  150. public SectionData (string sectionName, string typeName,
  151. bool allowLocation, AllowDefinition allowDefinition)
  152. {
  153. SectionName = sectionName;
  154. TypeName = typeName;
  155. AllowLocation = allowLocation;
  156. AllowDefinition = allowDefinition;
  157. }
  158. }
  159. class ConfigurationData
  160. {
  161. ConfigurationData parent;
  162. Hashtable factories;
  163. Hashtable pending;
  164. string fileName;
  165. static object removedMark = new object ();
  166. static object groupMark = new object ();
  167. static object emptyMark = new object ();
  168. Hashtable cache;
  169. Hashtable FileCache {
  170. get {
  171. if (cache != null)
  172. return cache;
  173. cache = new Hashtable ();
  174. return cache;
  175. }
  176. }
  177. public ConfigurationData () : this (null)
  178. {
  179. }
  180. public ConfigurationData (ConfigurationData parent)
  181. {
  182. this.parent = (parent == this) ? null : parent;
  183. factories = new Hashtable ();
  184. }
  185. public bool Load (string fileName)
  186. {
  187. this.fileName = fileName;
  188. if (fileName == null || !File.Exists (fileName))
  189. return false;
  190. #if (XML_DEP)
  191. XmlTextReader reader = null;
  192. try {
  193. FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  194. reader = new XmlTextReader (fs);
  195. InitRead (reader);
  196. ReadConfigFile (reader);
  197. } catch (ConfigurationException) {
  198. throw;
  199. } catch (Exception e) {
  200. throw new ConfigurationException ("Error reading " + fileName, e);
  201. } finally {
  202. if (reader != null)
  203. reader.Close();
  204. }
  205. #endif
  206. return true;
  207. }
  208. object GetHandler (string sectionName)
  209. {
  210. lock (factories) {
  211. object o = factories [sectionName];
  212. if (o == null || o == removedMark) {
  213. if (parent != null)
  214. return parent.GetHandler (sectionName);
  215. return null;
  216. }
  217. if (o is IConfigurationSectionHandler)
  218. return (IConfigurationSectionHandler) o;
  219. o = CreateNewHandler (sectionName, (SectionData) o);
  220. factories [sectionName] = o;
  221. return o;
  222. }
  223. }
  224. object CreateNewHandler (string sectionName, SectionData section)
  225. {
  226. Type t = Type.GetType (section.TypeName);
  227. if (t == null)
  228. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  229. #if false
  230. Type iconfig = typeof (IConfigurationSectionHandler);
  231. if (!iconfig.IsAssignableFrom (t))
  232. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  233. #endif
  234. object o = Activator.CreateInstance (t, true);
  235. if (o == null)
  236. throw new ConfigurationException ("Cannot get instance for " + t);
  237. return o;
  238. }
  239. #if (XML_DEP)
  240. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  241. {
  242. if (++i >= sectionPath.Length)
  243. return doc;
  244. if (doc.DocumentElement == null)
  245. return null;
  246. XmlNode node = doc.DocumentElement.FirstChild;
  247. while (node != null) {
  248. if (node.Name == sectionPath [i]) {
  249. ConfigXmlDocument result = new ConfigXmlDocument ();
  250. result.Load (new StringReader (node.OuterXml));
  251. return GetInnerDoc (result, i, sectionPath);
  252. }
  253. node = node.NextSibling;
  254. }
  255. return null;
  256. }
  257. XmlDocument GetDocumentForSection (string sectionName)
  258. {
  259. ConfigXmlDocument doc = new ConfigXmlDocument ();
  260. if (pending == null)
  261. return doc;
  262. string [] sectionPath = sectionName.Split ('/');
  263. string outerxml = pending [sectionPath [0]] as string;
  264. if (outerxml == null)
  265. return doc;
  266. StringReader reader = new StringReader (outerxml);
  267. XmlTextReader rd = new XmlTextReader (reader);
  268. rd.MoveToContent ();
  269. doc.LoadSingleElement (fileName, rd);
  270. return GetInnerDoc (doc, 0, sectionPath);
  271. }
  272. object GetConfigInternal (string sectionName)
  273. {
  274. object handler = GetHandler (sectionName);
  275. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  276. if (iconf == null)
  277. return handler;
  278. object parentConfig = null;
  279. if (parent != null)
  280. parentConfig = parent.GetConfig (sectionName);
  281. XmlDocument doc = GetDocumentForSection (sectionName);
  282. if (doc == null || doc.DocumentElement == null)
  283. return parentConfig;
  284. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  285. }
  286. #else
  287. object GetConfigInternal (string sectionName)
  288. {
  289. return null;
  290. }
  291. #endif
  292. public object GetConfig (string sectionName)
  293. {
  294. object config;
  295. lock (this) {
  296. config = this.FileCache [sectionName];
  297. }
  298. if (config == emptyMark)
  299. return null;
  300. if (config != null)
  301. return config;
  302. lock (this) {
  303. config = GetConfigInternal (sectionName);
  304. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  305. }
  306. return config;
  307. }
  308. private object LookForFactory (string key)
  309. {
  310. object o = factories [key];
  311. if (o != null)
  312. return o;
  313. if (parent != null)
  314. return parent.LookForFactory (key);
  315. return null;
  316. }
  317. #if (XML_DEP)
  318. private void InitRead (XmlTextReader reader)
  319. {
  320. reader.MoveToContent ();
  321. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  322. ThrowException ("Configuration file does not have a valid root element", reader);
  323. if (reader.HasAttributes)
  324. ThrowException ("Unrecognized attribute in root element", reader);
  325. MoveToNextElement (reader);
  326. }
  327. private void MoveToNextElement (XmlTextReader reader)
  328. {
  329. while (reader.Read ()) {
  330. XmlNodeType ntype = reader.NodeType;
  331. if (ntype == XmlNodeType.Element)
  332. return;
  333. if (ntype != XmlNodeType.Whitespace &&
  334. ntype != XmlNodeType.Comment &&
  335. ntype != XmlNodeType.SignificantWhitespace &&
  336. ntype != XmlNodeType.EndElement)
  337. ThrowException ("Unrecognized element", reader);
  338. }
  339. }
  340. private void ReadSection (XmlTextReader reader, string sectionName)
  341. {
  342. string attName;
  343. string nameValue = null;
  344. string typeValue = null;
  345. string allowLoc = null, allowDef = null;
  346. bool allowLocation = true;
  347. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  348. while (reader.MoveToNextAttribute ()) {
  349. attName = reader.Name;
  350. if (attName == null)
  351. continue;
  352. if (attName == "allowLocation") {
  353. if (allowLoc != null)
  354. ThrowException ("Duplicated allowLocation attribute.", reader);
  355. allowLoc = reader.Value;
  356. allowLocation = (allowLoc == "true");
  357. if (!allowLocation && allowLoc != "false")
  358. ThrowException ("Invalid attribute value", reader);
  359. continue;
  360. }
  361. if (attName == "allowDefinition") {
  362. if (allowDef != null)
  363. ThrowException ("Duplicated allowDefinition attribute.", reader);
  364. allowDef = reader.Value;
  365. try {
  366. allowDefinition = (AllowDefinition) Enum.Parse (
  367. typeof (AllowDefinition), allowDef);
  368. } catch {
  369. ThrowException ("Invalid attribute value", reader);
  370. }
  371. continue;
  372. }
  373. if (attName == "type") {
  374. if (typeValue != null)
  375. ThrowException ("Duplicated type attribute.", reader);
  376. typeValue = reader.Value;
  377. continue;
  378. }
  379. if (attName == "name") {
  380. if (nameValue != null)
  381. ThrowException ("Duplicated name attribute.", reader);
  382. nameValue = reader.Value;
  383. if (nameValue == "location")
  384. ThrowException ("location is a reserved section name", reader);
  385. continue;
  386. }
  387. ThrowException ("Unrecognized attribute.", reader);
  388. }
  389. if (nameValue == null || typeValue == null)
  390. ThrowException ("Required attribute missing", reader);
  391. if (sectionName != null)
  392. nameValue = sectionName + '/' + nameValue;
  393. reader.MoveToElement();
  394. object o = LookForFactory (nameValue);
  395. if (o != null && o != removedMark)
  396. ThrowException ("Already have a factory for " + nameValue, reader);
  397. SectionData section = new SectionData (nameValue, typeValue, allowLocation, allowDefinition);
  398. section.FileName = fileName;
  399. factories [nameValue] = section;
  400. MoveToNextElement (reader);
  401. }
  402. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  403. {
  404. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  405. ThrowException ("Unrecognized attribute.", reader);
  406. string removeValue = reader.Value;
  407. if (removeValue == null || removeValue.Length == 0)
  408. ThrowException ("Empty name to remove", reader);
  409. reader.MoveToElement ();
  410. if (sectionName != null)
  411. removeValue = sectionName + '/' + removeValue;
  412. object o = LookForFactory (removeValue);
  413. if (o != null && o == removedMark)
  414. ThrowException ("No factory for " + removeValue, reader);
  415. factories [removeValue] = removedMark;
  416. MoveToNextElement (reader);
  417. }
  418. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  419. {
  420. if (!reader.MoveToNextAttribute ())
  421. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  422. string value = null;
  423. do {
  424. if (reader.Name == "name") {
  425. if (value != null)
  426. ThrowException ("Duplicate 'name' attribute.", reader);
  427. value = reader.Value;
  428. }
  429. else
  430. #if NET_2_0
  431. if (reader.Name != "type")
  432. #endif
  433. ThrowException ("Unrecognized attribute.", reader);
  434. } while (reader.MoveToNextAttribute ());
  435. if (value == null)
  436. ThrowException ("No 'name' attribute.", reader);
  437. if (value == "location")
  438. ThrowException ("location is a reserved section name", reader);
  439. if (configSection != null)
  440. value = configSection + '/' + value;
  441. object o = LookForFactory (value);
  442. if (o != null && o != removedMark && o != groupMark)
  443. ThrowException ("Already have a factory for " + value, reader);
  444. factories [value] = groupMark;
  445. MoveToNextElement (reader);
  446. ReadSections (reader, value);
  447. }
  448. private void ReadSections (XmlTextReader reader, string configSection)
  449. {
  450. int depth = reader.Depth;
  451. while (reader.Depth == depth) {
  452. string name = reader.Name;
  453. if (name == "section") {
  454. ReadSection (reader, configSection);
  455. continue;
  456. }
  457. if (name == "remove") {
  458. ReadRemoveSection (reader, configSection);
  459. continue;
  460. }
  461. if (name == "clear") {
  462. if (reader.HasAttributes)
  463. ThrowException ("Unrecognized attribute.", reader);
  464. factories.Clear ();
  465. MoveToNextElement (reader);
  466. continue;
  467. }
  468. if (name == "sectionGroup") {
  469. ReadSectionGroup (reader, configSection);
  470. continue;
  471. }
  472. ThrowException ("Unrecognized element: " + reader.Name, reader);
  473. }
  474. }
  475. void StorePending (string name, XmlTextReader reader)
  476. {
  477. if (pending == null)
  478. pending = new Hashtable ();
  479. pending [name] = reader.ReadOuterXml ();
  480. }
  481. private void ReadConfigFile (XmlTextReader reader)
  482. {
  483. int depth = reader.Depth;
  484. while (!reader.EOF && reader.Depth == depth) {
  485. string name = reader.Name;
  486. if (name == "configSections") {
  487. if (reader.HasAttributes)
  488. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  489. MoveToNextElement (reader);
  490. if (reader.Depth > depth)
  491. ReadSections (reader, null);
  492. } else if (name != null && name != "") {
  493. StorePending (name, reader);
  494. MoveToNextElement (reader);
  495. } else {
  496. MoveToNextElement (reader);
  497. }
  498. }
  499. }
  500. private void ThrowException (string text, XmlTextReader reader)
  501. {
  502. throw new ConfigurationException (text, fileName, reader.LineNumber);
  503. }
  504. #endif
  505. }
  506. }