ConfigurationSettings.cs 13 KB

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