ConfigurationSettings.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. #if CONFIGURATION_DEP
  34. extern alias PrebuiltSystem;
  35. using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
  36. #endif
  37. using System;
  38. using System.Collections;
  39. using System.Collections.Specialized;
  40. using System.IO;
  41. using System.Runtime.CompilerServices;
  42. using System.Security.Permissions;
  43. #if (XML_DEP)
  44. using System.Xml;
  45. using System.Xml.XPath;
  46. #endif
  47. namespace System.Configuration
  48. {
  49. public sealed class ConfigurationSettings
  50. {
  51. static IConfigurationSystem config = DefaultConfig.GetInstance ();
  52. static object lockobj = new object ();
  53. private ConfigurationSettings ()
  54. {
  55. }
  56. #if NET_2_0
  57. [Obsolete ("This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.GetSection")]
  58. #endif
  59. public static object GetConfig (string sectionName)
  60. {
  61. return config.GetConfig (sectionName);
  62. }
  63. #if NET_2_0
  64. [Obsolete ("This property is obsolete. Please use System.Configuration.ConfigurationManager.AppSettings")]
  65. #endif
  66. public static NameValueCollection AppSettings
  67. {
  68. get {
  69. #if NET_2_0 && CONFIGURATION_DEP
  70. object appSettings = ConfigurationManager.GetSection ("appSettings");
  71. #else
  72. object appSettings = GetConfig ("appSettings");
  73. #endif
  74. if (appSettings == null)
  75. appSettings = new NameValueCollection ();
  76. return (NameValueCollection) appSettings;
  77. }
  78. }
  79. // Invoked from System.Web, disable warning
  80. internal static IConfigurationSystem ChangeConfigurationSystem (IConfigurationSystem newSystem)
  81. {
  82. if (newSystem == null)
  83. throw new ArgumentNullException ("newSystem");
  84. lock (lockobj) {
  85. IConfigurationSystem old = config;
  86. config = newSystem;
  87. return old;
  88. }
  89. }
  90. }
  91. //
  92. // class DefaultConfig: read configuration from machine.config file and application
  93. // config file if available.
  94. //
  95. class DefaultConfig : IConfigurationSystem
  96. {
  97. static readonly DefaultConfig instance = new DefaultConfig ();
  98. ConfigurationData config;
  99. private DefaultConfig ()
  100. {
  101. }
  102. public static DefaultConfig GetInstance ()
  103. {
  104. return instance;
  105. }
  106. #if NET_2_0
  107. [Obsolete ("This method is obsolete. Please use System.Configuration.ConfigurationManager.GetConfig")]
  108. #endif
  109. public object GetConfig (string sectionName)
  110. {
  111. Init ();
  112. return config.GetConfig (sectionName);
  113. }
  114. public void Init ()
  115. {
  116. lock (this) {
  117. if (config != null)
  118. return;
  119. ConfigurationData data = new ConfigurationData ();
  120. if (!data.Load (GetMachineConfigPath ()))
  121. throw new ConfigurationException ("Cannot find " + GetMachineConfigPath ());
  122. string appfile = GetAppConfigPath ();
  123. if (appfile == null) {
  124. config = data;
  125. return;
  126. }
  127. ConfigurationData appData = new ConfigurationData (data);
  128. if (appData.Load (appfile))
  129. config = appData;
  130. else
  131. config = data;
  132. }
  133. }
  134. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  135. extern private static string get_machine_config_path ();
  136. internal static string GetMachineConfigPath ()
  137. {
  138. return get_machine_config_path ();
  139. }
  140. private static string GetAppConfigPath ()
  141. {
  142. AppDomainSetup currentInfo = AppDomain.CurrentDomain.SetupInformation;
  143. string configFile = currentInfo.ConfigurationFile;
  144. if (configFile == null || configFile.Length == 0)
  145. return null;
  146. return configFile;
  147. }
  148. }
  149. enum AllowDefinition
  150. {
  151. Everywhere,
  152. MachineOnly,
  153. MachineToApplication
  154. }
  155. class SectionData
  156. {
  157. public readonly string SectionName;
  158. public readonly string TypeName;
  159. public readonly bool AllowLocation;
  160. public readonly AllowDefinition AllowDefinition;
  161. public string FileName;
  162. public SectionData (string sectionName, string typeName,
  163. bool allowLocation, AllowDefinition allowDefinition)
  164. {
  165. SectionName = sectionName;
  166. TypeName = typeName;
  167. AllowLocation = allowLocation;
  168. AllowDefinition = allowDefinition;
  169. }
  170. }
  171. class ConfigurationData
  172. {
  173. ConfigurationData parent;
  174. Hashtable factories;
  175. Hashtable pending;
  176. string fileName;
  177. static object removedMark = new object ();
  178. static object groupMark = new object ();
  179. static object emptyMark = new object ();
  180. Hashtable cache;
  181. Hashtable FileCache {
  182. get {
  183. if (cache != null)
  184. return cache;
  185. cache = new Hashtable ();
  186. return cache;
  187. }
  188. }
  189. public ConfigurationData () : this (null)
  190. {
  191. }
  192. public ConfigurationData (ConfigurationData parent)
  193. {
  194. this.parent = (parent == this) ? null : parent;
  195. factories = new Hashtable ();
  196. }
  197. // SECURITY-FIXME: limit this with an imperative assert for reading the specific file
  198. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  199. public bool Load (string fileName)
  200. {
  201. this.fileName = fileName;
  202. if (fileName == null || !File.Exists (fileName))
  203. return false;
  204. #if (XML_DEP)
  205. XmlTextReader reader = null;
  206. try {
  207. FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  208. reader = new XmlTextReader (fs);
  209. InitRead (reader);
  210. ReadConfigFile (reader);
  211. } catch (ConfigurationException) {
  212. throw;
  213. } catch (Exception e) {
  214. throw new ConfigurationException ("Error reading " + fileName, e);
  215. } finally {
  216. if (reader != null)
  217. reader.Close();
  218. }
  219. #endif
  220. return true;
  221. }
  222. object GetHandler (string sectionName)
  223. {
  224. lock (factories) {
  225. object o = factories [sectionName];
  226. if (o == null || o == removedMark) {
  227. if (parent != null)
  228. return parent.GetHandler (sectionName);
  229. return null;
  230. }
  231. if (o is IConfigurationSectionHandler)
  232. return (IConfigurationSectionHandler) o;
  233. o = CreateNewHandler (sectionName, (SectionData) o);
  234. factories [sectionName] = o;
  235. return o;
  236. }
  237. }
  238. object CreateNewHandler (string sectionName, SectionData section)
  239. {
  240. Type t = Type.GetType (section.TypeName);
  241. if (t == null)
  242. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  243. #if false
  244. Type iconfig = typeof (IConfigurationSectionHandler);
  245. if (!iconfig.IsAssignableFrom (t))
  246. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  247. #endif
  248. object o = Activator.CreateInstance (t, true);
  249. if (o == null)
  250. throw new ConfigurationException ("Cannot get instance for " + t);
  251. return o;
  252. }
  253. #if (XML_DEP)
  254. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  255. {
  256. if (++i >= sectionPath.Length)
  257. return doc;
  258. if (doc.DocumentElement == null)
  259. return null;
  260. XmlNode node = doc.DocumentElement.FirstChild;
  261. while (node != null) {
  262. if (node.Name == sectionPath [i]) {
  263. ConfigXmlDocument result = new ConfigXmlDocument ();
  264. result.Load (new StringReader (node.OuterXml));
  265. return GetInnerDoc (result, i, sectionPath);
  266. }
  267. node = node.NextSibling;
  268. }
  269. return null;
  270. }
  271. XmlDocument GetDocumentForSection (string sectionName)
  272. {
  273. ConfigXmlDocument doc = new ConfigXmlDocument ();
  274. if (pending == null)
  275. return doc;
  276. string [] sectionPath = sectionName.Split ('/');
  277. string outerxml = pending [sectionPath [0]] as string;
  278. if (outerxml == null)
  279. return doc;
  280. StringReader reader = new StringReader (outerxml);
  281. XmlTextReader rd = new XmlTextReader (reader);
  282. rd.MoveToContent ();
  283. doc.LoadSingleElement (fileName, rd);
  284. return GetInnerDoc (doc, 0, sectionPath);
  285. }
  286. object GetConfigInternal (string sectionName)
  287. {
  288. object handler = GetHandler (sectionName);
  289. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  290. if (iconf == null)
  291. return handler;
  292. object parentConfig = null;
  293. if (parent != null)
  294. parentConfig = parent.GetConfig (sectionName);
  295. XmlDocument doc = GetDocumentForSection (sectionName);
  296. if (doc == null || doc.DocumentElement == null)
  297. return parentConfig;
  298. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  299. }
  300. #else
  301. object GetConfigInternal (string sectionName)
  302. {
  303. return null;
  304. }
  305. #endif
  306. public object GetConfig (string sectionName)
  307. {
  308. object config;
  309. lock (this) {
  310. config = this.FileCache [sectionName];
  311. }
  312. if (config == emptyMark)
  313. return null;
  314. if (config != null)
  315. return config;
  316. lock (this) {
  317. config = GetConfigInternal (sectionName);
  318. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  319. }
  320. return config;
  321. }
  322. private object LookForFactory (string key)
  323. {
  324. object o = factories [key];
  325. if (o != null)
  326. return o;
  327. if (parent != null)
  328. return parent.LookForFactory (key);
  329. return null;
  330. }
  331. #if (XML_DEP)
  332. private void InitRead (XmlTextReader reader)
  333. {
  334. reader.MoveToContent ();
  335. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  336. ThrowException ("Configuration file does not have a valid root element", reader);
  337. if (reader.HasAttributes)
  338. ThrowException ("Unrecognized attribute in root element", reader);
  339. MoveToNextElement (reader);
  340. }
  341. private void MoveToNextElement (XmlTextReader reader)
  342. {
  343. while (reader.Read ()) {
  344. XmlNodeType ntype = reader.NodeType;
  345. if (ntype == XmlNodeType.Element)
  346. return;
  347. if (ntype != XmlNodeType.Whitespace &&
  348. ntype != XmlNodeType.Comment &&
  349. ntype != XmlNodeType.SignificantWhitespace &&
  350. ntype != XmlNodeType.EndElement)
  351. ThrowException ("Unrecognized element", reader);
  352. }
  353. }
  354. private void ReadSection (XmlTextReader reader, string sectionName)
  355. {
  356. string attName;
  357. string nameValue = null;
  358. string typeValue = null;
  359. string allowLoc = null, allowDef = null;
  360. bool allowLocation = true;
  361. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  362. while (reader.MoveToNextAttribute ()) {
  363. attName = reader.Name;
  364. if (attName == null)
  365. continue;
  366. if (attName == "allowLocation") {
  367. if (allowLoc != null)
  368. ThrowException ("Duplicated allowLocation attribute.", reader);
  369. allowLoc = reader.Value;
  370. allowLocation = (allowLoc == "true");
  371. if (!allowLocation && allowLoc != "false")
  372. ThrowException ("Invalid attribute value", reader);
  373. continue;
  374. }
  375. if (attName == "allowDefinition") {
  376. if (allowDef != null)
  377. ThrowException ("Duplicated allowDefinition attribute.", reader);
  378. allowDef = reader.Value;
  379. try {
  380. allowDefinition = (AllowDefinition) Enum.Parse (
  381. typeof (AllowDefinition), allowDef);
  382. } catch {
  383. ThrowException ("Invalid attribute value", reader);
  384. }
  385. continue;
  386. }
  387. if (attName == "type") {
  388. if (typeValue != null)
  389. ThrowException ("Duplicated type attribute.", reader);
  390. typeValue = reader.Value;
  391. continue;
  392. }
  393. if (attName == "name") {
  394. if (nameValue != null)
  395. ThrowException ("Duplicated name attribute.", reader);
  396. nameValue = reader.Value;
  397. if (nameValue == "location")
  398. ThrowException ("location is a reserved section name", reader);
  399. continue;
  400. }
  401. ThrowException ("Unrecognized attribute.", reader);
  402. }
  403. if (nameValue == null || typeValue == null)
  404. ThrowException ("Required attribute missing", reader);
  405. if (sectionName != null)
  406. nameValue = sectionName + '/' + nameValue;
  407. reader.MoveToElement();
  408. object o = LookForFactory (nameValue);
  409. if (o != null && o != removedMark)
  410. ThrowException ("Already have a factory for " + nameValue, reader);
  411. SectionData section = new SectionData (nameValue, typeValue, allowLocation, allowDefinition);
  412. section.FileName = fileName;
  413. factories [nameValue] = section;
  414. MoveToNextElement (reader);
  415. }
  416. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  417. {
  418. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  419. ThrowException ("Unrecognized attribute.", reader);
  420. string removeValue = reader.Value;
  421. if (removeValue == null || removeValue.Length == 0)
  422. ThrowException ("Empty name to remove", reader);
  423. reader.MoveToElement ();
  424. if (sectionName != null)
  425. removeValue = sectionName + '/' + removeValue;
  426. object o = LookForFactory (removeValue);
  427. if (o != null && o == removedMark)
  428. ThrowException ("No factory for " + removeValue, reader);
  429. factories [removeValue] = removedMark;
  430. MoveToNextElement (reader);
  431. }
  432. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  433. {
  434. if (!reader.MoveToNextAttribute ())
  435. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  436. string value = null;
  437. do {
  438. if (reader.Name == "name") {
  439. if (value != null)
  440. ThrowException ("Duplicate 'name' attribute.", reader);
  441. value = reader.Value;
  442. }
  443. else
  444. #if NET_2_0
  445. if (reader.Name != "type")
  446. #endif
  447. ThrowException ("Unrecognized attribute.", reader);
  448. } while (reader.MoveToNextAttribute ());
  449. if (value == null)
  450. ThrowException ("No 'name' attribute.", reader);
  451. if (value == "location")
  452. ThrowException ("location is a reserved section name", reader);
  453. if (configSection != null)
  454. value = configSection + '/' + value;
  455. object o = LookForFactory (value);
  456. if (o != null && o != removedMark && o != groupMark)
  457. ThrowException ("Already have a factory for " + value, reader);
  458. factories [value] = groupMark;
  459. MoveToNextElement (reader);
  460. ReadSections (reader, value);
  461. }
  462. private void ReadSections (XmlTextReader reader, string configSection)
  463. {
  464. int depth = reader.Depth;
  465. while (reader.Depth == depth) {
  466. string name = reader.Name;
  467. if (name == "section") {
  468. ReadSection (reader, configSection);
  469. continue;
  470. }
  471. if (name == "remove") {
  472. ReadRemoveSection (reader, configSection);
  473. continue;
  474. }
  475. if (name == "clear") {
  476. if (reader.HasAttributes)
  477. ThrowException ("Unrecognized attribute.", reader);
  478. factories.Clear ();
  479. MoveToNextElement (reader);
  480. continue;
  481. }
  482. if (name == "sectionGroup") {
  483. ReadSectionGroup (reader, configSection);
  484. continue;
  485. }
  486. ThrowException ("Unrecognized element: " + reader.Name, reader);
  487. }
  488. }
  489. void StorePending (string name, XmlTextReader reader)
  490. {
  491. if (pending == null)
  492. pending = new Hashtable ();
  493. pending [name] = reader.ReadOuterXml ();
  494. }
  495. private void ReadConfigFile (XmlTextReader reader)
  496. {
  497. int depth = reader.Depth;
  498. while (!reader.EOF && reader.Depth == depth) {
  499. string name = reader.Name;
  500. if (name == "configSections") {
  501. if (reader.HasAttributes)
  502. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  503. MoveToNextElement (reader);
  504. if (reader.Depth > depth)
  505. ReadSections (reader, null);
  506. } else if (name != null && name != "") {
  507. StorePending (name, reader);
  508. MoveToNextElement (reader);
  509. } else {
  510. MoveToNextElement (reader);
  511. }
  512. }
  513. }
  514. private void ThrowException (string text, XmlTextReader reader)
  515. {
  516. throw new ConfigurationException (text, fileName, reader.LineNumber);
  517. }
  518. #endif
  519. }
  520. }