ConfigurationSettings.cs 15 KB

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